Bug 1858509 add thread-safety annotations around MediaSourceDemuxer::mMonitor r=alwu
[gecko.git] / ipc / glue / MessageLink.cpp
blob5505322a2fd2ef5f28786674c9f6bbe699e8200c
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: sw=2 ts=4 et :
3 */
4 /* This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
8 #include "mozilla/ipc/MessageLink.h"
9 #include "mojo/core/ports/event.h"
10 #include "mojo/core/ports/node.h"
11 #include "mozilla/ipc/MessageChannel.h"
12 #include "mozilla/ipc/BrowserProcessSubThread.h"
13 #include "mozilla/ipc/ProtocolUtils.h"
14 #include "mozilla/ipc/NodeController.h"
15 #include "chrome/common/ipc_channel.h"
16 #include "base/task.h"
18 #include "mozilla/Assertions.h"
19 #include "mozilla/DebugOnly.h"
20 #include "nsDebug.h"
21 #include "nsExceptionHandler.h"
22 #include "nsISupportsImpl.h"
23 #include "nsPrintfCString.h"
24 #include "nsXULAppAPI.h"
26 using namespace mozilla;
28 namespace mozilla {
29 namespace ipc {
31 const char* StringFromIPCSide(Side side) {
32 switch (side) {
33 case ChildSide:
34 return "Child";
35 case ParentSide:
36 return "Parent";
37 default:
38 return "Unknown";
42 MessageLink::MessageLink(MessageChannel* aChan) : mChan(aChan) {}
44 MessageLink::~MessageLink() {
45 #ifdef DEBUG
46 mChan = nullptr;
47 #endif
50 class PortLink::PortObserverThunk : public NodeController::PortObserver {
51 public:
52 PortObserverThunk(RefCountedMonitor* aMonitor, PortLink* aLink)
53 : mMonitor(aMonitor), mLink(aLink) {}
55 void OnPortStatusChanged() override {
56 MonitorAutoLock lock(*mMonitor);
57 if (mLink) {
58 mLink->OnPortStatusChanged();
62 private:
63 friend class PortLink;
65 // The monitor from our PortLink's MessageChannel. Guards access to `mLink`.
66 RefPtr<RefCountedMonitor> mMonitor;
68 // Cleared by `PortLink` in `PortLink::Clear()`.
69 PortLink* MOZ_NON_OWNING_REF mLink;
72 PortLink::PortLink(MessageChannel* aChan, ScopedPort aPort)
73 : MessageLink(aChan), mNode(aPort.Controller()), mPort(aPort.Release()) {
74 mChan->mMonitor->AssertCurrentThreadOwns();
76 mObserver = new PortObserverThunk(mChan->mMonitor, this);
77 mNode->SetPortObserver(mPort, mObserver);
79 // Dispatch an event to the IO loop to trigger an initial
80 // `OnPortStatusChanged` to deliver any pending messages. This needs to be run
81 // asynchronously from a different thread (or in the case of a same-thread
82 // channel, from the current thread), for now due to assertions in
83 // `MessageChannel`.
84 nsCOMPtr<nsIRunnable> openRunnable = NewRunnableMethod(
85 "PortLink::Open", mObserver, &PortObserverThunk::OnPortStatusChanged);
86 if (aChan->mIsSameThreadChannel) {
87 aChan->mWorkerThread->Dispatch(openRunnable.forget());
88 } else {
89 XRE_GetIOMessageLoop()->PostTask(openRunnable.forget());
93 PortLink::~PortLink() {
94 MOZ_RELEASE_ASSERT(!mObserver, "PortLink destroyed without being closed!");
97 void PortLink::SendMessage(UniquePtr<Message> aMessage) {
98 mChan->mMonitor->AssertCurrentThreadOwns();
100 if (aMessage->size() > IPC::Channel::kMaximumMessageSize) {
101 CrashReporter::AnnotateCrashReport(
102 CrashReporter::Annotation::IPCMessageName,
103 nsDependentCString(aMessage->name()));
104 CrashReporter::AnnotateCrashReport(
105 CrashReporter::Annotation::IPCMessageSize,
106 static_cast<unsigned int>(aMessage->size()));
107 MOZ_CRASH("IPC message size is too large");
109 aMessage->AssertAsLargeAsHeader();
111 RefPtr<PortObserverThunk> observer = mObserver;
112 if (!observer) {
113 NS_WARNING("Ignoring message to closed PortLink");
114 return;
117 // Make local copies of relevant member variables, so we can unlock the
118 // monitor for the rest of this function. This protects us in case `this` is
119 // deleted during the call (although that shouldn't happen in practice).
121 // We don't want the monitor to be held when calling into ports, as we may be
122 // re-entrantly called by our `PortObserverThunk` which will attempt to
123 // acquire the monitor.
124 RefPtr<RefCountedMonitor> monitor = mChan->mMonitor;
125 RefPtr<NodeController> node = mNode;
126 PortRef port = mPort;
128 bool ok = false;
129 monitor->AssertCurrentThreadOwns();
131 MonitorAutoUnlock guard(*monitor);
132 ok = node->SendUserMessage(port, std::move(aMessage));
134 if (!ok) {
135 // The send failed, but double-check that we weren't closed racily while
136 // sending, which could lead to an invalid state error.
137 if (observer->mLink) {
138 MOZ_CRASH("Invalid argument to SendUserMessage");
140 NS_WARNING("Message dropped as PortLink was closed");
144 void PortLink::Close() {
145 mChan->mMonitor->AssertCurrentThreadOwns();
147 if (!mObserver) {
148 // We're already being closed.
149 return;
152 Clear();
155 void PortLink::Clear() {
156 mChan->mMonitor->AssertCurrentThreadOwns();
158 // NOTE: We're calling into `ports` with our monitor held! Usually, this could
159 // lead to deadlocks due to the PortObserverThunk acquiring the lock
160 // re-entrantly, but is OK here as we're immediately clearing the port's
161 // observer. We shouldn't have issues with any re-entrant calls on this thread
162 // acquiring this MessageChannel's monitor.
164 // We also clear out the reference in `mObserver` back to this type so that
165 // notifications from other threads won't try to call us again once we release
166 // the monitor.
167 mNode->SetPortObserver(mPort, nullptr);
168 mObserver->mLink = nullptr;
169 mObserver = nullptr;
170 mNode->ClosePort(mPort);
173 void PortLink::OnPortStatusChanged() {
174 mChan->mMonitor->AssertCurrentThreadOwns();
176 // Check if the port's remoteness status has updated, and tell our channel if
177 // it has.
178 if (Maybe<PortStatus> status = mNode->GetStatus(mPort);
179 status && status->peer_remote != mChan->IsCrossProcess()) {
180 mChan->SetIsCrossProcess(status->peer_remote);
183 while (mObserver) {
184 UniquePtr<IPC::Message> message;
185 if (!mNode->GetMessage(mPort, &message)) {
186 Clear();
187 mChan->OnChannelErrorFromLink();
188 return;
190 if (!message) {
191 return;
194 mChan->OnMessageReceivedFromLink(std::move(message));
198 bool PortLink::IsClosed() const {
199 if (Maybe<PortStatus> status = mNode->GetStatus(mPort)) {
200 return !(status->has_messages || status->receiving_messages);
202 return true;
205 } // namespace ipc
206 } // namespace mozilla