2 * Copyright (C) 2010 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23 * THE POSSIBILITY OF SUCH DAMAGE.
27 #include "Connection.h"
30 #include <wtf/CurrentTime.h>
31 #include <wtf/HashSet.h>
32 #include <wtf/NeverDestroyed.h>
33 #include <wtf/RunLoop.h>
34 #include <wtf/text/WTFString.h>
35 #include <wtf/threads/BinarySemaphore.h>
39 struct WaitForMessageState {
40 WaitForMessageState(StringReference messageReceiverName, StringReference messageName, uint64_t destinationID, unsigned waitForMessageFlags)
41 : messageReceiverName(messageReceiverName)
42 , messageName(messageName)
43 , destinationID(destinationID)
44 , waitForMessageFlags(waitForMessageFlags)
48 StringReference messageReceiverName;
49 StringReference messageName;
50 uint64_t destinationID;
52 unsigned waitForMessageFlags;
53 bool messageWaitingInterrupted = false;
55 std::unique_ptr<MessageDecoder> decoder;
58 class Connection::SyncMessageState : public ThreadSafeRefCounted<Connection::SyncMessageState> {
60 static Ref<SyncMessageState> getOrCreate(RunLoop&);
63 void wakeUpClientRunLoop()
65 m_waitForSyncReplySemaphore.signal();
68 bool wait(double absoluteTime)
70 return m_waitForSyncReplySemaphore.wait(absoluteTime);
73 // Returns true if this message will be handled on a client thread that is currently
74 // waiting for a reply to a synchronous message.
75 bool processIncomingMessage(Connection&, std::unique_ptr<MessageDecoder>&);
77 // Dispatch pending sync messages. if allowedConnection is not null, will only dispatch messages
78 // from that connection and put the other messages back in the queue.
79 void dispatchMessages(Connection* allowedConnection);
82 explicit SyncMessageState(RunLoop&);
84 typedef HashMap<RunLoop*, SyncMessageState*> SyncMessageStateMap;
85 static SyncMessageStateMap& syncMessageStateMap()
87 static NeverDestroyed<SyncMessageStateMap> syncMessageStateMap;
88 return syncMessageStateMap;
91 static std::mutex& syncMessageStateMapMutex()
93 static LazyNeverDestroyed<std::mutex> syncMessageStateMapMutex;
94 static std::once_flag onceFlag;
95 std::call_once(onceFlag, [] {
96 syncMessageStateMapMutex.construct();
99 return syncMessageStateMapMutex;
102 void dispatchMessageAndResetDidScheduleDispatchMessagesForConnection(Connection&);
105 BinarySemaphore m_waitForSyncReplySemaphore;
107 // Protects m_didScheduleDispatchMessagesWorkSet and m_messagesToDispatchWhileWaitingForSyncReply.
110 // The set of connections for which we've scheduled a call to dispatchMessageAndResetDidScheduleDispatchMessagesForConnection.
111 HashSet<RefPtr<Connection>> m_didScheduleDispatchMessagesWorkSet;
113 struct ConnectionAndIncomingMessage {
114 Ref<Connection> connection;
115 std::unique_ptr<MessageDecoder> message;
117 Vector<ConnectionAndIncomingMessage> m_messagesToDispatchWhileWaitingForSyncReply;
120 class Connection::SecondaryThreadPendingSyncReply {
122 // The reply decoder, will be null if there was an error processing the sync message on the other side.
123 std::unique_ptr<MessageDecoder> replyDecoder;
125 BinarySemaphore semaphore;
129 Ref<Connection::SyncMessageState> Connection::SyncMessageState::getOrCreate(RunLoop& runLoop)
131 std::lock_guard<std::mutex> lock(syncMessageStateMapMutex());
133 auto& slot = syncMessageStateMap().add(&runLoop, nullptr).iterator->value;
137 Ref<SyncMessageState> syncMessageState = adoptRef(*new SyncMessageState(runLoop));
138 slot = syncMessageState.ptr();
140 return syncMessageState;
143 Connection::SyncMessageState::SyncMessageState(RunLoop& runLoop)
148 Connection::SyncMessageState::~SyncMessageState()
150 std::lock_guard<std::mutex> lock(syncMessageStateMapMutex());
152 ASSERT(syncMessageStateMap().contains(&m_runLoop));
153 syncMessageStateMap().remove(&m_runLoop);
155 ASSERT(m_messagesToDispatchWhileWaitingForSyncReply.isEmpty());
158 bool Connection::SyncMessageState::processIncomingMessage(Connection& connection, std::unique_ptr<MessageDecoder>& message)
160 if (!message->shouldDispatchMessageWhenWaitingForSyncReply())
163 ConnectionAndIncomingMessage connectionAndIncomingMessage { connection, WTF::move(message) };
166 std::lock_guard<std::mutex> lock(m_mutex);
168 if (m_didScheduleDispatchMessagesWorkSet.add(&connection).isNewEntry) {
169 RefPtr<Connection> protectedConnection(&connection);
170 m_runLoop.dispatch([this, protectedConnection] {
171 dispatchMessageAndResetDidScheduleDispatchMessagesForConnection(*protectedConnection);
175 m_messagesToDispatchWhileWaitingForSyncReply.append(WTF::move(connectionAndIncomingMessage));
178 wakeUpClientRunLoop();
183 void Connection::SyncMessageState::dispatchMessages(Connection* allowedConnection)
185 ASSERT(&m_runLoop == &RunLoop::current());
187 Vector<ConnectionAndIncomingMessage> messagesToDispatchWhileWaitingForSyncReply;
190 std::lock_guard<std::mutex> lock(m_mutex);
191 m_messagesToDispatchWhileWaitingForSyncReply.swap(messagesToDispatchWhileWaitingForSyncReply);
194 Vector<ConnectionAndIncomingMessage> messagesToPutBack;
196 for (size_t i = 0; i < messagesToDispatchWhileWaitingForSyncReply.size(); ++i) {
197 ConnectionAndIncomingMessage& connectionAndIncomingMessage = messagesToDispatchWhileWaitingForSyncReply[i];
199 if (allowedConnection && allowedConnection != connectionAndIncomingMessage.connection.ptr()) {
200 // This incoming message belongs to another connection and we don't want to dispatch it now
201 // so mark it to be put back in the message queue.
202 messagesToPutBack.append(WTF::move(connectionAndIncomingMessage));
206 connectionAndIncomingMessage.connection->dispatchMessage(WTF::move(connectionAndIncomingMessage.message));
209 if (!messagesToPutBack.isEmpty()) {
210 std::lock_guard<std::mutex> lock(m_mutex);
212 for (auto& message : messagesToPutBack)
213 m_messagesToDispatchWhileWaitingForSyncReply.append(WTF::move(message));
217 void Connection::SyncMessageState::dispatchMessageAndResetDidScheduleDispatchMessagesForConnection(Connection& connection)
220 std::lock_guard<std::mutex> lock(m_mutex);
221 ASSERT(m_didScheduleDispatchMessagesWorkSet.contains(&connection));
222 m_didScheduleDispatchMessagesWorkSet.remove(&connection);
225 dispatchMessages(&connection);
228 Ref<Connection> Connection::createServerConnection(Identifier identifier, Client& client, RunLoop& clientRunLoop)
230 return adoptRef(*new Connection(identifier, true, client, clientRunLoop));
233 Ref<Connection> Connection::createClientConnection(Identifier identifier, Client& client, RunLoop& clientRunLoop)
235 return adoptRef(*new Connection(identifier, false, client, clientRunLoop));
238 Connection::Connection(Identifier identifier, bool isServer, Client& client, RunLoop& clientRunLoop)
240 , m_isServer(isServer)
242 , m_onlySendMessagesAsDispatchWhenWaitingForSyncReplyWhenProcessingSuchAMessage(false)
243 , m_shouldExitOnSyncMessageSendFailure(false)
244 , m_didCloseOnConnectionWorkQueueCallback(0)
245 , m_isConnected(false)
246 , m_connectionQueue(WorkQueue::create("com.apple.IPC.ReceiveQueue"))
247 , m_clientRunLoop(clientRunLoop)
248 , m_inSendSyncCount(0)
249 , m_inDispatchMessageCount(0)
250 , m_inDispatchMessageMarkedDispatchWhenWaitingForSyncReplyCount(0)
251 , m_didReceiveInvalidMessage(false)
252 , m_waitingForMessage(nullptr)
253 , m_syncMessageState(SyncMessageState::getOrCreate(clientRunLoop))
254 , m_shouldWaitForSyncReplies(true)
258 platformInitialize(identifier);
261 Connection::~Connection()
266 void Connection::setOnlySendMessagesAsDispatchWhenWaitingForSyncReplyWhenProcessingSuchAMessage(bool flag)
268 ASSERT(!m_isConnected);
270 m_onlySendMessagesAsDispatchWhenWaitingForSyncReplyWhenProcessingSuchAMessage = flag;
273 void Connection::setShouldExitOnSyncMessageSendFailure(bool shouldExitOnSyncMessageSendFailure)
275 ASSERT(!m_isConnected);
277 m_shouldExitOnSyncMessageSendFailure = shouldExitOnSyncMessageSendFailure;
280 void Connection::addWorkQueueMessageReceiver(StringReference messageReceiverName, WorkQueue* workQueue, WorkQueueMessageReceiver* workQueueMessageReceiver)
282 ASSERT(&RunLoop::current() == &m_clientRunLoop);
284 RefPtr<Connection> connection(this);
285 m_connectionQueue->dispatch([connection, messageReceiverName, workQueue, workQueueMessageReceiver] {
286 ASSERT(!connection->m_workQueueMessageReceivers.contains(messageReceiverName));
288 connection->m_workQueueMessageReceivers.add(messageReceiverName, std::make_pair(workQueue, workQueueMessageReceiver));
292 void Connection::removeWorkQueueMessageReceiver(StringReference messageReceiverName)
294 ASSERT(&RunLoop::current() == &m_clientRunLoop);
296 RefPtr<Connection> connection(this);
297 m_connectionQueue->dispatch([connection, messageReceiverName] {
298 ASSERT(connection->m_workQueueMessageReceivers.contains(messageReceiverName));
299 connection->m_workQueueMessageReceivers.remove(messageReceiverName);
303 void Connection::dispatchWorkQueueMessageReceiverMessage(WorkQueueMessageReceiver* workQueueMessageReceiver, MessageDecoder* incomingMessageDecoder)
305 std::unique_ptr<MessageDecoder> decoder(incomingMessageDecoder);
307 if (!decoder->isSyncMessage()) {
308 workQueueMessageReceiver->didReceiveMessage(*this, *decoder);
312 uint64_t syncRequestID = 0;
313 if (!decoder->decode(syncRequestID) || !syncRequestID) {
314 // We received an invalid sync message.
315 // FIXME: Handle this.
316 decoder->markInvalid();
321 auto replyEncoder = std::make_unique<MessageEncoder>("IPC", "SyncMessageReply", syncRequestID, incomingMessageDecoder->UUID());
323 auto replyEncoder = std::make_unique<MessageEncoder>("IPC", "SyncMessageReply", syncRequestID);
326 // Hand off both the decoder and encoder to the work queue message receiver.
327 workQueueMessageReceiver->didReceiveSyncMessage(*this, *decoder, replyEncoder);
329 // FIXME: If the message was invalid, we should send back a SyncMessageError.
330 ASSERT(!decoder->isInvalid());
333 sendSyncReply(WTF::move(replyEncoder));
336 void Connection::setDidCloseOnConnectionWorkQueueCallback(DidCloseOnConnectionWorkQueueCallback callback)
338 ASSERT(!m_isConnected);
340 m_didCloseOnConnectionWorkQueueCallback = callback;
343 void Connection::invalidate()
346 // Someone already called invalidate().
353 m_connectionQueue->dispatch(WTF::bind(&Connection::platformInvalidate, this));
356 void Connection::markCurrentlyDispatchedMessageAsInvalid()
358 // This should only be called while processing a message.
359 ASSERT(m_inDispatchMessageCount > 0);
361 m_didReceiveInvalidMessage = true;
364 std::unique_ptr<MessageEncoder> Connection::createSyncMessageEncoder(StringReference messageReceiverName, StringReference messageName, uint64_t destinationID, uint64_t& syncRequestID)
366 auto encoder = std::make_unique<MessageEncoder>(messageReceiverName, messageName, destinationID);
367 encoder->setIsSyncMessage(true);
369 // Encode the sync request ID.
370 syncRequestID = ++m_syncRequestID;
371 *encoder << syncRequestID;
376 bool Connection::sendMessage(std::unique_ptr<MessageEncoder> encoder, unsigned messageSendFlags, bool alreadyRecordedMessage)
381 if (messageSendFlags & DispatchMessageEvenWhenWaitingForSyncReply
382 && (!m_onlySendMessagesAsDispatchWhenWaitingForSyncReplyWhenProcessingSuchAMessage
383 || m_inDispatchMessageMarkedDispatchWhenWaitingForSyncReplyCount))
384 encoder->setShouldDispatchMessageWhenWaitingForSyncReply(true);
387 std::unique_ptr<MessageRecorder::MessageProcessingToken> token;
388 if (!alreadyRecordedMessage)
389 token = MessageRecorder::recordOutgoingMessage(*this, *encoder);
391 UNUSED_PARAM(alreadyRecordedMessage);
395 std::lock_guard<std::mutex> lock(m_outgoingMessagesMutex);
396 m_outgoingMessages.append(WTF::move(encoder));
399 // FIXME: We should add a boolean flag so we don't call this when work has already been scheduled.
400 m_connectionQueue->dispatch(WTF::bind(&Connection::sendOutgoingMessages, this));
404 bool Connection::sendSyncReply(std::unique_ptr<MessageEncoder> encoder)
406 return sendMessage(WTF::move(encoder));
409 std::unique_ptr<MessageDecoder> Connection::waitForMessage(StringReference messageReceiverName, StringReference messageName, uint64_t destinationID, std::chrono::milliseconds timeout, unsigned waitForMessageFlags)
411 ASSERT(&m_clientRunLoop == &RunLoop::current());
413 // First, check if this message is already in the incoming messages queue.
415 std::lock_guard<std::mutex> lock(m_incomingMessagesMutex);
417 for (auto it = m_incomingMessages.begin(), end = m_incomingMessages.end(); it != end; ++it) {
418 std::unique_ptr<MessageDecoder>& message = *it;
420 if (message->messageReceiverName() == messageReceiverName && message->messageName() == messageName && message->destinationID() == destinationID) {
421 std::unique_ptr<MessageDecoder> returnedMessage = WTF::move(message);
423 m_incomingMessages.remove(it);
424 return returnedMessage;
429 WaitForMessageState waitingForMessage(messageReceiverName, messageName, destinationID, waitForMessageFlags);
432 std::lock_guard<std::mutex> lock(m_waitForMessageMutex);
434 // We don't support having multiple clients waiting for messages.
435 ASSERT(!m_waitingForMessage);
437 m_waitingForMessage = &waitingForMessage;
440 // Now wait for it to be set.
442 std::unique_lock<std::mutex> lock(m_waitForMessageMutex);
444 if (m_waitingForMessage->decoder) {
445 auto decoder = WTF::move(m_waitingForMessage->decoder);
446 m_waitingForMessage = nullptr;
451 std::cv_status status = m_waitForMessageCondition.wait_for(lock, timeout);
452 // We timed out, lost our connection, or a sync message came in with InterruptWaitingIfSyncMessageArrives, so stop waiting.
453 if (status == std::cv_status::timeout || m_waitingForMessage->messageWaitingInterrupted)
457 m_waitingForMessage = nullptr;
462 std::unique_ptr<MessageDecoder> Connection::sendSyncMessage(uint64_t syncRequestID, std::unique_ptr<MessageEncoder> encoder, std::chrono::milliseconds timeout, unsigned syncSendFlags)
464 if (&RunLoop::current() != &m_clientRunLoop) {
465 // No flags are supported for synchronous messages sent from secondary threads.
466 ASSERT(!syncSendFlags);
467 return sendSyncMessageFromSecondaryThread(syncRequestID, WTF::move(encoder), timeout);
471 didFailToSendSyncMessage();
475 // Push the pending sync reply information on our stack.
477 MutexLocker locker(m_syncReplyStateMutex);
478 if (!m_shouldWaitForSyncReplies) {
479 didFailToSendSyncMessage();
483 m_pendingSyncReplies.append(PendingSyncReply(syncRequestID));
489 auto token = MessageRecorder::recordOutgoingMessage(*this, *encoder);
492 // First send the message.
493 sendMessage(WTF::move(encoder), DispatchMessageEvenWhenWaitingForSyncReply, true);
495 // Then wait for a reply. Waiting for a reply could involve dispatching incoming sync messages, so
496 // keep an extra reference to the connection here in case it's invalidated.
497 Ref<Connection> protect(*this);
498 std::unique_ptr<MessageDecoder> reply = waitForSyncReply(syncRequestID, timeout, syncSendFlags);
502 // Finally, pop the pending sync reply information.
504 MutexLocker locker(m_syncReplyStateMutex);
505 ASSERT(m_pendingSyncReplies.last().syncRequestID == syncRequestID);
506 m_pendingSyncReplies.removeLast();
510 didFailToSendSyncMessage();
515 std::unique_ptr<MessageDecoder> Connection::sendSyncMessageFromSecondaryThread(uint64_t syncRequestID, std::unique_ptr<MessageEncoder> encoder, std::chrono::milliseconds timeout)
517 ASSERT(&RunLoop::current() != &m_clientRunLoop);
522 SecondaryThreadPendingSyncReply pendingReply;
524 // Push the pending sync reply information on our stack.
526 MutexLocker locker(m_syncReplyStateMutex);
527 if (!m_shouldWaitForSyncReplies)
530 ASSERT(!m_secondaryThreadPendingSyncReplyMap.contains(syncRequestID));
531 m_secondaryThreadPendingSyncReplyMap.add(syncRequestID, &pendingReply);
535 auto token = MessageRecorder::recordOutgoingMessage(*this, *encoder);
538 sendMessage(WTF::move(encoder), 0, true);
540 pendingReply.semaphore.wait(currentTime() + (timeout.count() / 1000.0));
542 // Finally, pop the pending sync reply information.
544 MutexLocker locker(m_syncReplyStateMutex);
545 ASSERT(m_secondaryThreadPendingSyncReplyMap.contains(syncRequestID));
546 m_secondaryThreadPendingSyncReplyMap.remove(syncRequestID);
549 return WTF::move(pendingReply.replyDecoder);
552 std::unique_ptr<MessageDecoder> Connection::waitForSyncReply(uint64_t syncRequestID, std::chrono::milliseconds timeout, unsigned syncSendFlags)
554 double absoluteTime = currentTime() + (timeout.count() / 1000.0);
556 willSendSyncMessage(syncSendFlags);
558 bool timedOut = false;
560 // First, check if we have any messages that we need to process.
561 m_syncMessageState->dispatchMessages(nullptr);
564 MutexLocker locker(m_syncReplyStateMutex);
566 // Second, check if there is a sync reply at the top of the stack.
567 ASSERT(!m_pendingSyncReplies.isEmpty());
569 PendingSyncReply& pendingSyncReply = m_pendingSyncReplies.last();
570 ASSERT_UNUSED(syncRequestID, pendingSyncReply.syncRequestID == syncRequestID);
572 // We found the sync reply, or the connection was closed.
573 if (pendingSyncReply.didReceiveReply || !m_shouldWaitForSyncReplies) {
574 didReceiveSyncReply(syncSendFlags);
575 return WTF::move(pendingSyncReply.replyDecoder);
579 // Processing a sync message could cause the connection to be invalidated.
580 // (If the handler ends up calling Connection::invalidate).
581 // If that happens, we need to stop waiting, or we'll hang since we won't get
582 // any more incoming messages.
584 didReceiveSyncReply(syncSendFlags);
588 // We didn't find a sync reply yet, keep waiting.
589 // This allows the WebProcess to still serve clients while waiting for the message to return.
590 // Notably, it can continue to process accessibility requests, which are on the main thread.
591 if (syncSendFlags & SpinRunLoopWhileWaitingForReply) {
593 // FIXME: Although we run forever, any events incoming will cause us to drop out and exit out. This however doesn't
594 // account for a timeout value passed in. Timeout is always NoTimeout in these cases, but that could change.
595 RunLoop::current().runForDuration(1e10);
596 timedOut = currentTime() >= absoluteTime;
599 timedOut = !m_syncMessageState->wait(absoluteTime);
603 didReceiveSyncReply(syncSendFlags);
608 void Connection::processIncomingSyncReply(std::unique_ptr<MessageDecoder> decoder)
610 MutexLocker locker(m_syncReplyStateMutex);
612 // Go through the stack of sync requests that have pending replies and see which one
613 // this reply is for.
614 for (size_t i = m_pendingSyncReplies.size(); i > 0; --i) {
615 PendingSyncReply& pendingSyncReply = m_pendingSyncReplies[i - 1];
617 if (pendingSyncReply.syncRequestID != decoder->destinationID())
620 ASSERT(!pendingSyncReply.replyDecoder);
622 pendingSyncReply.replyDecoder = WTF::move(decoder);
623 pendingSyncReply.didReceiveReply = true;
625 // We got a reply to the last send message, wake up the client run loop so it can be processed.
626 if (i == m_pendingSyncReplies.size())
627 m_syncMessageState->wakeUpClientRunLoop();
632 // If it's not a reply to any primary thread message, check if it is a reply to a secondary thread one.
633 SecondaryThreadPendingSyncReplyMap::iterator secondaryThreadReplyMapItem = m_secondaryThreadPendingSyncReplyMap.find(decoder->destinationID());
634 if (secondaryThreadReplyMapItem != m_secondaryThreadPendingSyncReplyMap.end()) {
635 SecondaryThreadPendingSyncReply* reply = secondaryThreadReplyMapItem->value;
636 ASSERT(!reply->replyDecoder);
637 reply->replyDecoder = WTF::move(decoder);
638 reply->semaphore.signal();
641 // If we get here, it means we got a reply for a message that wasn't in the sync request stack or map.
642 // This can happen if the send timed out, so it's fine to ignore.
645 void Connection::processIncomingMessage(std::unique_ptr<MessageDecoder> message)
647 ASSERT(!message->messageReceiverName().isEmpty());
648 ASSERT(!message->messageName().isEmpty());
650 if (message->messageReceiverName() == "IPC" && message->messageName() == "SyncMessageReply") {
651 processIncomingSyncReply(WTF::move(message));
655 if (!m_workQueueMessageReceivers.isValidKey(message->messageReceiverName())) {
656 if (message->messageReceiverName().isEmpty() && message->messageName().isEmpty()) {
657 // Something went wrong when decoding the message. Encode the message length so we can figure out if this
658 // happens for certain message lengths.
659 CString messageReceiverName = "<unknown message>";
660 CString messageName = String::format("<message length: %zu bytes>", message->length()).utf8();
662 m_clientRunLoop.dispatch(bind(&Connection::dispatchDidReceiveInvalidMessage, this, messageReceiverName, messageName));
666 m_clientRunLoop.dispatch(bind(&Connection::dispatchDidReceiveInvalidMessage, this, message->messageReceiverName().toString(), message->messageName().toString()));
670 auto it = m_workQueueMessageReceivers.find(message->messageReceiverName());
671 if (it != m_workQueueMessageReceivers.end()) {
672 it->value.first->dispatch(bind(&Connection::dispatchWorkQueueMessageReceiverMessage, this, it->value.second, message.release()));
676 // Check if this is a sync message or if it's a message that should be dispatched even when waiting for
677 // a sync reply. If it is, and we're waiting for a sync reply this message needs to be dispatched.
678 // If we don't we'll end up with a deadlock where both sync message senders are stuck waiting for a reply.
679 if (m_syncMessageState->processIncomingMessage(*this, message))
682 // Check if we're waiting for this message.
684 std::lock_guard<std::mutex> lock(m_waitForMessageMutex);
686 if (m_waitingForMessage && m_waitingForMessage->messageReceiverName == message->messageReceiverName() && m_waitingForMessage->messageName == message->messageName() && m_waitingForMessage->destinationID == message->destinationID()) {
687 m_waitingForMessage->decoder = WTF::move(message);
688 ASSERT(m_waitingForMessage->decoder);
689 m_waitForMessageCondition.notify_one();
693 if (m_waitingForMessage && (m_waitingForMessage->waitForMessageFlags & InterruptWaitingIfSyncMessageArrives) && message->isSyncMessage()) {
694 m_waitingForMessage->messageWaitingInterrupted = true;
695 m_waitForMessageCondition.notify_one();
699 enqueueIncomingMessage(WTF::move(message));
702 void Connection::postConnectionDidCloseOnConnectionWorkQueue()
704 RefPtr<Connection> connection(this);
705 m_connectionQueue->dispatch([connection] {
706 connection->connectionDidClose();
710 void Connection::connectionDidClose()
712 // The connection is now invalid.
713 platformInvalidate();
716 MutexLocker locker(m_syncReplyStateMutex);
718 ASSERT(m_shouldWaitForSyncReplies);
719 m_shouldWaitForSyncReplies = false;
721 if (!m_pendingSyncReplies.isEmpty())
722 m_syncMessageState->wakeUpClientRunLoop();
724 for (SecondaryThreadPendingSyncReplyMap::iterator iter = m_secondaryThreadPendingSyncReplyMap.begin(); iter != m_secondaryThreadPendingSyncReplyMap.end(); ++iter)
725 iter->value->semaphore.signal();
729 std::lock_guard<std::mutex> lock(m_waitForMessageMutex);
730 if (m_waitingForMessage)
731 m_waitingForMessage->messageWaitingInterrupted = true;
733 m_waitForMessageCondition.notify_all();
735 if (m_didCloseOnConnectionWorkQueueCallback)
736 m_didCloseOnConnectionWorkQueueCallback(this);
738 RefPtr<Connection> connection(this);
739 m_clientRunLoop.dispatch([connection] {
740 // If the connection has been explicitly invalidated before dispatchConnectionDidClose was called,
741 // then the client will be null here.
742 if (!connection->m_client)
745 // Because we define a connection as being "valid" based on wheter it has a null client, we null out
746 // the client before calling didClose here. Otherwise, sendSync will try to send a message to the connection and
747 // will then wait indefinitely for a reply.
748 Client* client = connection->m_client;
749 connection->m_client = nullptr;
751 client->didClose(*connection);
755 bool Connection::canSendOutgoingMessages() const
757 return m_isConnected && platformCanSendOutgoingMessages();
760 void Connection::sendOutgoingMessages()
762 if (!canSendOutgoingMessages())
766 std::unique_ptr<MessageEncoder> message;
769 std::lock_guard<std::mutex> lock(m_outgoingMessagesMutex);
770 if (m_outgoingMessages.isEmpty())
772 message = m_outgoingMessages.takeFirst();
775 if (!sendOutgoingMessage(WTF::move(message)))
780 void Connection::dispatchSyncMessage(MessageDecoder& decoder)
782 ASSERT(decoder.isSyncMessage());
784 uint64_t syncRequestID = 0;
785 if (!decoder.decode(syncRequestID) || !syncRequestID) {
786 // We received an invalid sync message.
787 decoder.markInvalid();
792 auto replyEncoder = std::make_unique<MessageEncoder>("IPC", "SyncMessageReply", syncRequestID, decoder.UUID());
794 auto replyEncoder = std::make_unique<MessageEncoder>("IPC", "SyncMessageReply", syncRequestID);
797 // Hand off both the decoder and encoder to the client.
798 m_client->didReceiveSyncMessage(*this, decoder, replyEncoder);
800 // FIXME: If the message was invalid, we should send back a SyncMessageError.
801 ASSERT(!decoder.isInvalid());
804 sendSyncReply(WTF::move(replyEncoder));
807 void Connection::dispatchDidReceiveInvalidMessage(const CString& messageReceiverNameString, const CString& messageNameString)
809 ASSERT(&RunLoop::current() == &m_clientRunLoop);
814 m_client->didReceiveInvalidMessage(*this, StringReference(messageReceiverNameString.data(), messageReceiverNameString.length()), StringReference(messageNameString.data(), messageNameString.length()));
817 void Connection::didFailToSendSyncMessage()
819 if (!m_shouldExitOnSyncMessageSendFailure)
825 void Connection::enqueueIncomingMessage(std::unique_ptr<MessageDecoder> incomingMessage)
828 std::lock_guard<std::mutex> lock(m_incomingMessagesMutex);
829 m_incomingMessages.append(WTF::move(incomingMessage));
832 m_clientRunLoop.dispatch(WTF::bind(&Connection::dispatchOneMessage, this));
835 void Connection::dispatchMessage(MessageDecoder& decoder)
837 m_client->didReceiveMessage(*this, decoder);
840 void Connection::dispatchMessage(std::unique_ptr<MessageDecoder> message)
843 MessageRecorder::recordIncomingMessage(*this, *message);
849 m_inDispatchMessageCount++;
851 if (message->shouldDispatchMessageWhenWaitingForSyncReply())
852 m_inDispatchMessageMarkedDispatchWhenWaitingForSyncReplyCount++;
854 bool oldDidReceiveInvalidMessage = m_didReceiveInvalidMessage;
855 m_didReceiveInvalidMessage = false;
857 if (message->isSyncMessage())
858 dispatchSyncMessage(*message);
860 dispatchMessage(*message);
862 m_didReceiveInvalidMessage |= message->isInvalid();
863 m_inDispatchMessageCount--;
865 // FIXME: For Delayed synchronous messages, we should not decrement the counter until we send a response.
866 // Otherwise, we would deadlock if processing the message results in a sync message back after we exit this function.
867 if (message->shouldDispatchMessageWhenWaitingForSyncReply())
868 m_inDispatchMessageMarkedDispatchWhenWaitingForSyncReplyCount--;
870 if (m_didReceiveInvalidMessage && m_client)
871 m_client->didReceiveInvalidMessage(*this, message->messageReceiverName(), message->messageName());
873 m_didReceiveInvalidMessage = oldDidReceiveInvalidMessage;
876 void Connection::dispatchOneMessage()
878 std::unique_ptr<MessageDecoder> message;
881 std::lock_guard<std::mutex> lock(m_incomingMessagesMutex);
882 if (m_incomingMessages.isEmpty())
885 message = m_incomingMessages.takeFirst();
888 dispatchMessage(WTF::move(message));
891 void Connection::wakeUpRunLoop()
893 m_clientRunLoop.wakeUp();