CEventLoop.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. int rc = pipe2(s_wake_pipe_fds, O_CLOEXEC);
  125. ASSERT(rc == 0);
  126. s_event_loop_stack->append(this);
  127. auto rpc_path = String::format("/tmp/rpc.%d", getpid());
  128. rc = unlink(rpc_path.characters());
  129. if (rc < 0 && errno != ENOENT) {
  130. perror("unlink");
  131. ASSERT_NOT_REACHED();
  132. }
  133. s_rpc_server = CLocalServer::construct();
  134. s_rpc_server->set_name("CEventLoop_RPC_server");
  135. bool listening = s_rpc_server->listen(rpc_path);
  136. ASSERT(listening);
  137. s_rpc_server->on_ready_to_accept = [&] {
  138. auto client_socket = s_rpc_server->accept();
  139. ASSERT(client_socket);
  140. // NOTE: RPCClient will delete itself in RPCClient::shutdown().
  141. (void)RPCClient::construct(move(client_socket)).leak_ref();
  142. };
  143. }
  144. #ifdef CEVENTLOOP_DEBUG
  145. dbg() << getpid() << " CEventLoop constructed :)";
  146. #endif
  147. }
  148. CEventLoop::~CEventLoop()
  149. {
  150. }
  151. CEventLoop& CEventLoop::main()
  152. {
  153. ASSERT(s_main_event_loop);
  154. return *s_main_event_loop;
  155. }
  156. CEventLoop& CEventLoop::current()
  157. {
  158. return *s_event_loop_stack->last();
  159. }
  160. void CEventLoop::quit(int code)
  161. {
  162. dbg() << "CEventLoop::quit(" << code << ")";
  163. m_exit_requested = true;
  164. m_exit_code = code;
  165. }
  166. struct CEventLoopPusher {
  167. public:
  168. CEventLoopPusher(CEventLoop& event_loop)
  169. : m_event_loop(event_loop)
  170. {
  171. if (&m_event_loop != s_main_event_loop) {
  172. m_event_loop.take_pending_events_from(CEventLoop::current());
  173. s_event_loop_stack->append(&event_loop);
  174. }
  175. }
  176. ~CEventLoopPusher()
  177. {
  178. if (&m_event_loop != s_main_event_loop) {
  179. s_event_loop_stack->take_last();
  180. CEventLoop::current().take_pending_events_from(m_event_loop);
  181. }
  182. }
  183. private:
  184. CEventLoop& m_event_loop;
  185. };
  186. int CEventLoop::exec()
  187. {
  188. CEventLoopPusher pusher(*this);
  189. for (;;) {
  190. if (m_exit_requested)
  191. return m_exit_code;
  192. pump();
  193. }
  194. ASSERT_NOT_REACHED();
  195. }
  196. void CEventLoop::pump(WaitMode mode)
  197. {
  198. if (m_queued_events.is_empty())
  199. wait_for_event(mode);
  200. decltype(m_queued_events) events;
  201. {
  202. LOCKER(m_lock);
  203. events = move(m_queued_events);
  204. }
  205. for (int i = 0; i < events.size(); ++i) {
  206. auto& queued_event = events.at(i);
  207. ASSERT(queued_event.event);
  208. auto* receiver = queued_event.receiver.ptr();
  209. auto& event = *queued_event.event;
  210. #ifdef CEVENTLOOP_DEBUG
  211. if (receiver)
  212. dbg() << "CEventLoop: " << *receiver << " event " << (int)event.type();
  213. #endif
  214. if (!receiver) {
  215. switch (event.type()) {
  216. case CEvent::Quit:
  217. ASSERT_NOT_REACHED();
  218. return;
  219. default:
  220. dbg() << "Event type " << event.type() << " with no receiver :(";
  221. }
  222. } else if (event.type() == CEvent::Type::DeferredInvoke) {
  223. #ifdef DEFERRED_INVOKE_DEBUG
  224. printf("DeferredInvoke: receiver=%s{%p}\n", receiver->class_name(), receiver);
  225. #endif
  226. static_cast<CDeferredInvocationEvent&>(event).m_invokee(*receiver);
  227. } else {
  228. NonnullRefPtr<CObject> protector(*receiver);
  229. receiver->dispatch_event(event);
  230. }
  231. if (m_exit_requested) {
  232. LOCKER(m_lock);
  233. #ifdef CEVENTLOOP_DEBUG
  234. dbg() << "CEventLoop: Exit requested. Rejigging " << (events.size() - i) << " events.";
  235. #endif
  236. decltype(m_queued_events) new_event_queue;
  237. new_event_queue.ensure_capacity(m_queued_events.size() + events.size());
  238. for (; i < events.size(); ++i)
  239. new_event_queue.unchecked_append(move(events[i]));
  240. new_event_queue.append(move(m_queued_events));
  241. m_queued_events = move(new_event_queue);
  242. return;
  243. }
  244. }
  245. }
  246. void CEventLoop::post_event(CObject& receiver, NonnullOwnPtr<CEvent>&& event)
  247. {
  248. LOCKER(m_lock);
  249. #ifdef CEVENTLOOP_DEBUG
  250. dbg() << "CEventLoop::post_event: {" << m_queued_events.size() << "} << receiver=" << receiver << ", event=" << event;
  251. #endif
  252. m_queued_events.append({ receiver.make_weak_ptr(), move(event) });
  253. }
  254. void CEventLoop::wait_for_event(WaitMode mode)
  255. {
  256. fd_set rfds;
  257. fd_set wfds;
  258. FD_ZERO(&rfds);
  259. FD_ZERO(&wfds);
  260. int max_fd = 0;
  261. auto add_fd_to_set = [&max_fd](int fd, fd_set& set) {
  262. FD_SET(fd, &set);
  263. if (fd > max_fd)
  264. max_fd = fd;
  265. };
  266. int max_fd_added = -1;
  267. add_fd_to_set(s_wake_pipe_fds[0], rfds);
  268. max_fd = max(max_fd, max_fd_added);
  269. for (auto& notifier : *s_notifiers) {
  270. if (notifier->event_mask() & CNotifier::Read)
  271. add_fd_to_set(notifier->fd(), rfds);
  272. if (notifier->event_mask() & CNotifier::Write)
  273. add_fd_to_set(notifier->fd(), wfds);
  274. if (notifier->event_mask() & CNotifier::Exceptional)
  275. ASSERT_NOT_REACHED();
  276. }
  277. bool queued_events_is_empty;
  278. {
  279. LOCKER(m_lock);
  280. queued_events_is_empty = m_queued_events.is_empty();
  281. }
  282. timeval now;
  283. struct timeval timeout = { 0, 0 };
  284. bool should_wait_forever = false;
  285. if (mode == WaitMode::WaitForEvents) {
  286. if (!s_timers->is_empty() && queued_events_is_empty) {
  287. gettimeofday(&now, nullptr);
  288. get_next_timer_expiration(timeout);
  289. timeval_sub(timeout, now, timeout);
  290. } else {
  291. should_wait_forever = true;
  292. }
  293. } else {
  294. should_wait_forever = false;
  295. }
  296. int marked_fd_count = CSyscallUtils::safe_syscall(select, max_fd + 1, &rfds, &wfds, nullptr, should_wait_forever ? nullptr : &timeout);
  297. if (FD_ISSET(s_wake_pipe_fds[0], &rfds)) {
  298. char buffer[32];
  299. auto nread = read(s_wake_pipe_fds[0], buffer, sizeof(buffer));
  300. if (nread < 0) {
  301. perror("read from wake pipe");
  302. ASSERT_NOT_REACHED();
  303. }
  304. ASSERT(nread > 0);
  305. }
  306. if (!s_timers->is_empty()) {
  307. gettimeofday(&now, nullptr);
  308. }
  309. for (auto& it : *s_timers) {
  310. auto& timer = *it.value;
  311. if (!timer.has_expired(now))
  312. continue;
  313. #ifdef CEVENTLOOP_DEBUG
  314. dbg() << "CEventLoop: Timer " << timer.timer_id << " has expired, sending CTimerEvent to " << timer.owner;
  315. #endif
  316. post_event(*timer.owner, make<CTimerEvent>(timer.timer_id));
  317. if (timer.should_reload) {
  318. timer.reload(now);
  319. } else {
  320. // FIXME: Support removing expired timers that don't want to reload.
  321. ASSERT_NOT_REACHED();
  322. }
  323. }
  324. if (!marked_fd_count)
  325. return;
  326. for (auto& notifier : *s_notifiers) {
  327. if (FD_ISSET(notifier->fd(), &rfds)) {
  328. if (notifier->on_ready_to_read)
  329. post_event(*notifier, make<CNotifierReadEvent>(notifier->fd()));
  330. }
  331. if (FD_ISSET(notifier->fd(), &wfds)) {
  332. if (notifier->on_ready_to_write)
  333. post_event(*notifier, make<CNotifierWriteEvent>(notifier->fd()));
  334. }
  335. }
  336. }
  337. bool CEventLoop::EventLoopTimer::has_expired(const timeval& now) const
  338. {
  339. return now.tv_sec > fire_time.tv_sec || (now.tv_sec == fire_time.tv_sec && now.tv_usec >= fire_time.tv_usec);
  340. }
  341. void CEventLoop::EventLoopTimer::reload(const timeval& now)
  342. {
  343. fire_time = now;
  344. fire_time.tv_sec += interval / 1000;
  345. fire_time.tv_usec += (interval % 1000) * 1000;
  346. }
  347. void CEventLoop::get_next_timer_expiration(timeval& soonest)
  348. {
  349. ASSERT(!s_timers->is_empty());
  350. bool has_checked_any = false;
  351. for (auto& it : *s_timers) {
  352. auto& fire_time = it.value->fire_time;
  353. 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))
  354. soonest = fire_time;
  355. has_checked_any = true;
  356. }
  357. }
  358. int CEventLoop::register_timer(CObject& object, int milliseconds, bool should_reload)
  359. {
  360. ASSERT(milliseconds >= 0);
  361. auto timer = make<EventLoopTimer>();
  362. timer->owner = object.make_weak_ptr();
  363. timer->interval = milliseconds;
  364. timeval now;
  365. gettimeofday(&now, nullptr);
  366. timer->reload(now);
  367. timer->should_reload = should_reload;
  368. int timer_id = ++s_next_timer_id; // FIXME: This will eventually wrap around.
  369. ASSERT(timer_id); // FIXME: Aforementioned wraparound.
  370. timer->timer_id = timer_id;
  371. s_timers->set(timer_id, move(timer));
  372. return timer_id;
  373. }
  374. bool CEventLoop::unregister_timer(int timer_id)
  375. {
  376. auto it = s_timers->find(timer_id);
  377. if (it == s_timers->end())
  378. return false;
  379. s_timers->remove(it);
  380. return true;
  381. }
  382. void CEventLoop::register_notifier(Badge<CNotifier>, CNotifier& notifier)
  383. {
  384. s_notifiers->set(&notifier);
  385. }
  386. void CEventLoop::unregister_notifier(Badge<CNotifier>, CNotifier& notifier)
  387. {
  388. s_notifiers->remove(&notifier);
  389. }
  390. void CEventLoop::wake()
  391. {
  392. char ch = '!';
  393. int nwritten = write(s_wake_pipe_fds[1], &ch, 1);
  394. if (nwritten < 0) {
  395. perror("CEventLoop::wake: write");
  396. ASSERT_NOT_REACHED();
  397. }
  398. }