Bug 1758813 [wpt PR 33142] - Implement RP sign out, a=testonly
[gecko.git] / ipc / glue / ProtocolUtils.h
blob3f98f2e0b7f4c838e15747af250a4a0586925334
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
7 #ifndef mozilla_ipc_ProtocolUtils_h
8 #define mozilla_ipc_ProtocolUtils_h 1
10 #include <cstddef>
11 #include <cstdint>
12 #include <utility>
13 #include "IPCMessageStart.h"
14 #include "base/basictypes.h"
15 #include "base/process.h"
16 #include "chrome/common/ipc_message.h"
17 #include "mojo/core/ports/port_ref.h"
18 #include "mozilla/AlreadyAddRefed.h"
19 #include "mozilla/Assertions.h"
20 #include "mozilla/Attributes.h"
21 #include "mozilla/FunctionRef.h"
22 #include "mozilla/Maybe.h"
23 #include "mozilla/Mutex.h"
24 #include "mozilla/RefPtr.h"
25 #include "mozilla/Scoped.h"
26 #include "mozilla/UniquePtr.h"
27 #include "mozilla/ipc/MessageChannel.h"
28 #include "mozilla/ipc/MessageLink.h"
29 #include "mozilla/ipc/SharedMemory.h"
30 #include "mozilla/ipc/Shmem.h"
31 #include "nsTHashMap.h"
32 #include "nsDebug.h"
33 #include "nsISupports.h"
34 #include "nsTArrayForwardDeclare.h"
35 #include "nsTHashSet.h"
37 // XXX Things that could be moved to ProtocolUtils.cpp
38 #include "base/process_util.h" // for CloseProcessHandle
39 #include "prenv.h" // for PR_GetEnv
41 #if defined(ANDROID) && defined(DEBUG)
42 # include <android/log.h>
43 #endif
45 template <typename T>
46 class nsPtrHashKey;
48 // WARNING: this takes into account the private, special-message-type
49 // enum in ipc_channel.h. They need to be kept in sync.
50 namespace {
51 // XXX the max message ID is actually kuint32max now ... when this
52 // changed, the assumptions of the special message IDs changed in that
53 // they're not carving out messages from likely-unallocated space, but
54 // rather carving out messages from the end of space allocated to
55 // protocol 0. Oops! We can get away with this until protocol 0
56 // starts approaching its 65,536th message.
57 enum {
58 // Message types used by DataPipe
59 DATA_PIPE_CLOSED_MESSAGE_TYPE = kuint16max - 18,
60 DATA_PIPE_BYTES_CONSUMED_MESSAGE_TYPE = kuint16max - 17,
62 // Message types used by NodeChannel
63 ACCEPT_INVITE_MESSAGE_TYPE = kuint16max - 16,
64 REQUEST_INTRODUCTION_MESSAGE_TYPE = kuint16max - 15,
65 INTRODUCE_MESSAGE_TYPE = kuint16max - 14,
66 BROADCAST_MESSAGE_TYPE = kuint16max - 13,
67 EVENT_MESSAGE_TYPE = kuint16max - 12,
69 // Message types used by MessageChannel
70 MANAGED_ENDPOINT_DROPPED_MESSAGE_TYPE = kuint16max - 11,
71 MANAGED_ENDPOINT_BOUND_MESSAGE_TYPE = kuint16max - 10,
72 IMPENDING_SHUTDOWN_MESSAGE_TYPE = kuint16max - 9,
73 BUILD_IDS_MATCH_MESSAGE_TYPE = kuint16max - 8,
74 BUILD_ID_MESSAGE_TYPE = kuint16max - 7, // unused
75 CHANNEL_OPENED_MESSAGE_TYPE = kuint16max - 6,
76 SHMEM_DESTROYED_MESSAGE_TYPE = kuint16max - 5,
77 SHMEM_CREATED_MESSAGE_TYPE = kuint16max - 4,
78 GOODBYE_MESSAGE_TYPE = kuint16max - 3,
79 CANCEL_MESSAGE_TYPE = kuint16max - 2,
81 // kuint16max - 1 is used by ipc_channel.h.
84 } // namespace
86 class MessageLoop;
87 class PickleIterator;
88 class nsISerialEventTarget;
90 namespace mozilla {
91 class SchedulerGroup;
93 namespace dom {
94 class ContentParent;
95 } // namespace dom
97 namespace net {
98 class NeckoParent;
99 } // namespace net
101 namespace ipc {
103 #ifdef FUZZING
104 class ProtocolFuzzerHelper;
105 #endif
107 // Scoped base::ProcessHandle to ensure base::CloseProcessHandle is called.
108 struct ScopedProcessHandleTraits {
109 typedef base::ProcessHandle type;
111 static type empty() { return base::kInvalidProcessHandle; }
113 static void release(type aProcessHandle) {
114 if (aProcessHandle && aProcessHandle != base::kInvalidProcessHandle) {
115 base::CloseProcessHandle(aProcessHandle);
119 typedef mozilla::Scoped<ScopedProcessHandleTraits> ScopedProcessHandle;
121 class ProtocolFdMapping;
122 class ProtocolCloneContext;
124 // Used to pass references to protocol actors across the wire.
125 // Actors created on the parent-side have a positive ID, and actors
126 // allocated on the child side have a negative ID.
127 struct ActorHandle {
128 int mId;
131 // What happens if Interrupt calls race?
132 enum RacyInterruptPolicy { RIPError, RIPChildWins, RIPParentWins };
134 enum class LinkStatus : uint8_t {
135 // The actor has not established a link yet, or the actor is no longer in use
136 // by IPC, and its 'Dealloc' method has been called or is being called.
138 // NOTE: This state is used instead of an explicit `Freed` state when IPC no
139 // longer holds references to the current actor as we currently re-open
140 // existing actors. Once we fix these poorly behaved actors, this loopback
141 // state can be split to have the final state not be the same as the initial
142 // state.
143 Inactive,
145 // A live link is connected to the other side of this actor.
146 Connected,
148 // The link has begun being destroyed. Messages may still be received, but
149 // cannot be sent. (exception: sync/intr replies may be sent while Doomed).
150 Doomed,
152 // The link has been destroyed, and messages will no longer be sent or
153 // received.
154 Destroyed,
157 typedef IPCMessageStart ProtocolId;
159 // Generated by IPDL compiler
160 const char* ProtocolIdToName(IPCMessageStart aId);
162 class IToplevelProtocol;
163 class ActorLifecycleProxy;
164 class WeakActorLifecycleProxy;
165 class IPDLResolverInner;
166 class UntypedManagedEndpoint;
168 class IProtocol : public HasResultCodes {
169 public:
170 enum ActorDestroyReason {
171 FailedConstructor,
172 Deletion,
173 AncestorDeletion,
174 NormalShutdown,
175 AbnormalShutdown,
176 ManagedEndpointDropped
179 typedef base::ProcessId ProcessId;
180 typedef IPC::Message Message;
182 IProtocol(ProtocolId aProtoId, Side aSide)
183 : mId(0),
184 mProtocolId(aProtoId),
185 mSide(aSide),
186 mLinkStatus(LinkStatus::Inactive),
187 mLifecycleProxy(nullptr),
188 mManager(nullptr),
189 mToplevel(nullptr) {}
191 IToplevelProtocol* ToplevelProtocol() { return mToplevel; }
192 const IToplevelProtocol* ToplevelProtocol() const { return mToplevel; }
194 // The following methods either directly forward to the toplevel protocol, or
195 // almost directly do.
196 int32_t Register(IProtocol* aRouted);
197 int32_t RegisterID(IProtocol* aRouted, int32_t aId);
198 IProtocol* Lookup(int32_t aId);
199 void Unregister(int32_t aId);
201 Shmem::SharedMemory* CreateSharedMemory(size_t aSize,
202 SharedMemory::SharedMemoryType aType,
203 bool aUnsafe, int32_t* aId);
204 Shmem::SharedMemory* LookupSharedMemory(int32_t aId);
205 bool IsTrackingSharedMemory(Shmem::SharedMemory* aSegment);
206 bool DestroySharedMemory(Shmem& aShmem);
208 MessageChannel* GetIPCChannel();
209 const MessageChannel* GetIPCChannel() const;
211 // Get the nsISerialEventTarget which all messages sent to this actor will be
212 // processed on. Unless stated otherwise, all operations on IProtocol which
213 // don't occur on this `nsISerialEventTarget` are unsafe.
214 nsISerialEventTarget* GetActorEventTarget();
216 // Actor lifecycle and other properties.
217 ProtocolId GetProtocolId() const { return mProtocolId; }
218 const char* GetProtocolName() const { return ProtocolIdToName(mProtocolId); }
220 int32_t Id() const { return mId; }
221 IProtocol* Manager() const { return mManager; }
223 ActorLifecycleProxy* GetLifecycleProxy() { return mLifecycleProxy; }
224 WeakActorLifecycleProxy* GetWeakLifecycleProxy();
226 Side GetSide() const { return mSide; }
227 bool CanSend() const { return mLinkStatus == LinkStatus::Connected; }
228 bool CanRecv() const {
229 return mLinkStatus == LinkStatus::Connected ||
230 mLinkStatus == LinkStatus::Doomed;
233 // Remove or deallocate a managee given its type.
234 virtual void RemoveManagee(int32_t, IProtocol*) = 0;
235 virtual void DeallocManagee(int32_t, IProtocol*) = 0;
237 Maybe<IProtocol*> ReadActor(IPC::MessageReader* aReader, bool aNullable,
238 const char* aActorDescription,
239 int32_t aProtocolTypeId);
241 virtual Result OnMessageReceived(const Message& aMessage) = 0;
242 virtual Result OnMessageReceived(const Message& aMessage,
243 Message*& aReply) = 0;
244 virtual Result OnCallReceived(const Message& aMessage, Message*& aReply) = 0;
245 bool AllocShmem(size_t aSize, Shmem::SharedMemory::SharedMemoryType aType,
246 Shmem* aOutMem);
247 bool AllocUnsafeShmem(size_t aSize,
248 Shmem::SharedMemory::SharedMemoryType aType,
249 Shmem* aOutMem);
250 bool DeallocShmem(Shmem& aMem);
252 void FatalError(const char* const aErrorMsg) const;
253 virtual void HandleFatalError(const char* aErrorMsg) const;
255 protected:
256 virtual ~IProtocol();
258 friend class IToplevelProtocol;
259 friend class ActorLifecycleProxy;
260 friend class IPDLResolverInner;
261 friend class UntypedManagedEndpoint;
263 void SetId(int32_t aId);
265 // We have separate functions because the accessibility code manually
266 // calls SetManager.
267 void SetManager(IProtocol* aManager);
269 // Sets the manager for the protocol and registers the protocol with
270 // its manager, setting up channels for the protocol as well. Not
271 // for use outside of IPDL.
272 void SetManagerAndRegister(IProtocol* aManager);
273 void SetManagerAndRegister(IProtocol* aManager, int32_t aId);
275 // Helpers for calling `Send` on our underlying IPC channel.
276 bool ChannelSend(IPC::Message* aMsg);
277 bool ChannelSend(IPC::Message* aMsg, IPC::Message* aReply);
278 template <typename Value>
279 void ChannelSend(IPC::Message* aMsg, ResolveCallback<Value>&& aResolve,
280 RejectCallback&& aReject) {
281 UniquePtr<IPC::Message> msg(aMsg);
282 if (CanSend()) {
283 GetIPCChannel()->Send(std::move(msg), this, std::move(aResolve),
284 std::move(aReject));
285 } else {
286 WarnMessageDiscarded(msg.get());
287 aReject(ResponseRejectReason::SendError);
291 // Collect all actors managed by this object in an array. To make this safer
292 // to iterate, `ActorLifecycleProxy` references are returned rather than raw
293 // actor pointers.
294 virtual void AllManagedActors(
295 nsTArray<RefPtr<ActorLifecycleProxy>>& aActors) const = 0;
297 // Internal method called when the actor becomes connected.
298 void ActorConnected();
300 // Called immediately before setting the actor state to doomed, and triggering
301 // async actor destruction. Messages may be sent from this callback, but no
302 // later.
303 // FIXME(nika): This is currently unused!
304 virtual void ActorDoom() {}
305 void DoomSubtree();
307 // Called when the actor has been destroyed due to an error, a __delete__
308 // message, or a __doom__ reply.
309 virtual void ActorDestroy(ActorDestroyReason aWhy) {}
310 void DestroySubtree(ActorDestroyReason aWhy);
312 // Called when IPC has acquired its first reference to the actor. This method
313 // may take references which will later be freed by `ActorDealloc`.
314 virtual void ActorAlloc() {}
316 // Called when IPC has released its final reference to the actor. It will call
317 // the dealloc method, causing the actor to be actually freed.
319 // The actor has been freed after this method returns.
320 virtual void ActorDealloc() {
321 if (Manager()) {
322 Manager()->DeallocManagee(mProtocolId, this);
326 static const int32_t kNullActorId = 0;
327 static const int32_t kFreedActorId = 1;
329 private:
330 #ifdef DEBUG
331 void WarnMessageDiscarded(IPC::Message* aMsg);
332 #else
333 void WarnMessageDiscarded(IPC::Message*) {}
334 #endif
336 int32_t mId;
337 ProtocolId mProtocolId;
338 Side mSide;
339 LinkStatus mLinkStatus;
340 ActorLifecycleProxy* mLifecycleProxy;
341 IProtocol* mManager;
342 IToplevelProtocol* mToplevel;
345 #define IPC_OK() mozilla::ipc::IPCResult::Ok()
346 #define IPC_FAIL(actor, why) \
347 mozilla::ipc::IPCResult::Fail(WrapNotNull(actor), __func__, (why))
348 #define IPC_FAIL_NO_REASON(actor) \
349 mozilla::ipc::IPCResult::Fail(WrapNotNull(actor), __func__)
352 * All message deserializer and message handler should return this
353 * type via above macros. We use a less generic name here to avoid
354 * conflict with mozilla::Result because we have quite a few using
355 * namespace mozilla::ipc; in the code base.
357 class IPCResult {
358 public:
359 static IPCResult Ok() { return IPCResult(true); }
360 static IPCResult Fail(NotNull<IProtocol*> aActor, const char* aWhere,
361 const char* aWhy = "");
362 MOZ_IMPLICIT operator bool() const { return mSuccess; }
364 private:
365 explicit IPCResult(bool aResult) : mSuccess(aResult) {}
366 bool mSuccess;
369 template <class PFooSide>
370 class Endpoint;
372 template <class PFooSide>
373 class ManagedEndpoint;
376 * All top-level protocols should inherit this class.
378 * IToplevelProtocol tracks all top-level protocol actors created from
379 * this protocol actor.
381 class IToplevelProtocol : public IProtocol {
382 #ifdef FUZZING
383 friend class mozilla::ipc::ProtocolFuzzerHelper;
384 #endif
386 template <class PFooSide>
387 friend class Endpoint;
389 protected:
390 explicit IToplevelProtocol(const char* aName, ProtocolId aProtoId,
391 Side aSide);
392 ~IToplevelProtocol() = default;
394 public:
395 // Shadow methods on IProtocol which are implemented directly on toplevel
396 // actors.
397 int32_t Register(IProtocol* aRouted);
398 int32_t RegisterID(IProtocol* aRouted, int32_t aId);
399 IProtocol* Lookup(int32_t aId);
400 void Unregister(int32_t aId);
402 Shmem::SharedMemory* CreateSharedMemory(size_t aSize,
403 SharedMemory::SharedMemoryType aType,
404 bool aUnsafe, int32_t* aId);
405 Shmem::SharedMemory* LookupSharedMemory(int32_t aId);
406 bool IsTrackingSharedMemory(Shmem::SharedMemory* aSegment);
407 bool DestroySharedMemory(Shmem& aShmem);
409 MessageChannel* GetIPCChannel() { return &mChannel; }
410 const MessageChannel* GetIPCChannel() const { return &mChannel; }
412 void SetOtherProcessId(base::ProcessId aOtherPid);
414 virtual void OnChannelClose() = 0;
415 virtual void OnChannelError() = 0;
416 virtual void ProcessingError(Result aError, const char* aMsgName) {}
418 bool Open(ScopedPort aPort, base::ProcessId aOtherPid);
420 bool Open(IToplevelProtocol* aTarget, nsISerialEventTarget* aEventTarget,
421 mozilla::ipc::Side aSide = mozilla::ipc::UnknownSide);
423 // Open a toplevel actor such that both ends of the actor's channel are on
424 // the same thread. This method should be called on the thread to perform
425 // the link.
427 // WARNING: Attempting to send a sync or intr message on the same thread
428 // will crash.
429 bool OpenOnSameThread(IToplevelProtocol* aTarget,
430 mozilla::ipc::Side aSide = mozilla::ipc::UnknownSide);
433 * This sends a special message that is processed on the IO thread, so that
434 * other actors can know that the process will soon shutdown.
436 void NotifyImpendingShutdown();
438 void Close();
440 void SetReplyTimeoutMs(int32_t aTimeoutMs);
442 void DeallocShmems();
443 bool ShmemCreated(const Message& aMsg);
444 bool ShmemDestroyed(const Message& aMsg);
446 virtual bool ShouldContinueFromReplyTimeout() { return false; }
448 // WARNING: This function is called with the MessageChannel monitor held.
449 virtual void IntentionalCrash() { MOZ_CRASH("Intentional IPDL crash"); }
451 // The code here is only useful for fuzzing. It should not be used for any
452 // other purpose.
453 #ifdef DEBUG
454 // Returns true if we should simulate a timeout.
455 // WARNING: This is a testing-only function that is called with the
456 // MessageChannel monitor held. Don't do anything fancy here or we could
457 // deadlock.
458 virtual bool ArtificialTimeout() { return false; }
460 // Returns true if we want to cause the worker thread to sleep with the
461 // monitor unlocked.
462 virtual bool NeedArtificialSleep() { return false; }
464 // This function should be implemented to sleep for some amount of time on
465 // the worker thread. Will only be called if NeedArtificialSleep() returns
466 // true.
467 virtual void ArtificialSleep() {}
468 #else
469 bool ArtificialTimeout() { return false; }
470 bool NeedArtificialSleep() { return false; }
471 void ArtificialSleep() {}
472 #endif
474 bool IsOnCxxStack() const;
477 * Return true if windows messages can be handled while waiting for a reply
478 * to a sync IPDL message.
480 virtual bool HandleWindowsMessages(const Message& aMsg) const { return true; }
482 virtual void ProcessRemoteNativeEventsInInterruptCall() {}
484 virtual void OnChannelReceivedMessage(const Message& aMsg) {}
486 void OnIPCChannelOpened() { ActorConnected(); }
488 base::ProcessId OtherPidMaybeInvalid() const { return mOtherPid; }
490 private:
491 int32_t NextId();
493 template <class T>
494 using IDMap = nsTHashMap<nsUint32HashKey, T>;
496 base::ProcessId mOtherPid;
498 // NOTE NOTE NOTE
499 // Used to be on mState
500 int32_t mLastLocalId;
501 IDMap<IProtocol*> mActorMap;
502 IDMap<Shmem::SharedMemory*> mShmemMap;
504 MessageChannel mChannel;
507 class IShmemAllocator {
508 public:
509 virtual bool AllocShmem(size_t aSize,
510 mozilla::ipc::SharedMemory::SharedMemoryType aShmType,
511 mozilla::ipc::Shmem* aShmem) = 0;
512 virtual bool AllocUnsafeShmem(
513 size_t aSize, mozilla::ipc::SharedMemory::SharedMemoryType aShmType,
514 mozilla::ipc::Shmem* aShmem) = 0;
515 virtual bool DeallocShmem(mozilla::ipc::Shmem& aShmem) = 0;
518 #define FORWARD_SHMEM_ALLOCATOR_TO(aImplClass) \
519 virtual bool AllocShmem( \
520 size_t aSize, mozilla::ipc::SharedMemory::SharedMemoryType aShmType, \
521 mozilla::ipc::Shmem* aShmem) override { \
522 return aImplClass::AllocShmem(aSize, aShmType, aShmem); \
524 virtual bool AllocUnsafeShmem( \
525 size_t aSize, mozilla::ipc::SharedMemory::SharedMemoryType aShmType, \
526 mozilla::ipc::Shmem* aShmem) override { \
527 return aImplClass::AllocUnsafeShmem(aSize, aShmType, aShmem); \
529 virtual bool DeallocShmem(mozilla::ipc::Shmem& aShmem) override { \
530 return aImplClass::DeallocShmem(aShmem); \
533 inline bool LoggingEnabled() {
534 #if defined(DEBUG) || defined(FUZZING)
535 return !!PR_GetEnv("MOZ_IPC_MESSAGE_LOG");
536 #else
537 return false;
538 #endif
541 #if defined(DEBUG) || defined(FUZZING)
542 bool LoggingEnabledFor(const char* aTopLevelProtocol, const char* aFilter);
543 #endif
545 inline bool LoggingEnabledFor(const char* aTopLevelProtocol) {
546 #if defined(DEBUG) || defined(FUZZING)
547 return LoggingEnabledFor(aTopLevelProtocol, PR_GetEnv("MOZ_IPC_MESSAGE_LOG"));
548 #else
549 return false;
550 #endif
553 MOZ_NEVER_INLINE void LogMessageForProtocol(const char* aTopLevelProtocol,
554 base::ProcessId aOtherPid,
555 const char* aContextDescription,
556 uint32_t aMessageId,
557 MessageDirection aDirection);
559 MOZ_NEVER_INLINE void ProtocolErrorBreakpoint(const char* aMsg);
561 // IPC::MessageReader and IPC::MessageWriter call this function for FatalError
562 // calls which come from serialization/deserialization.
563 MOZ_NEVER_INLINE void PickleFatalError(const char* aMsg, IProtocol* aActor);
565 // The code generator calls this function for errors which come from the
566 // methods of protocols. Doing this saves codesize by making the error
567 // cases significantly smaller.
568 MOZ_NEVER_INLINE void FatalError(const char* aMsg, bool aIsParent);
570 // The code generator calls this function for errors which are not
571 // protocol-specific: errors in generated struct methods or errors in
572 // transition functions, for instance. Doing this saves codesize by
573 // by making the error cases significantly smaller.
574 MOZ_NEVER_INLINE void LogicError(const char* aMsg);
576 MOZ_NEVER_INLINE void ActorIdReadError(const char* aActorDescription);
578 MOZ_NEVER_INLINE void BadActorIdError(const char* aActorDescription);
580 MOZ_NEVER_INLINE void ActorLookupError(const char* aActorDescription);
582 MOZ_NEVER_INLINE void MismatchedActorTypeError(const char* aActorDescription);
584 MOZ_NEVER_INLINE void UnionTypeReadError(const char* aUnionName);
586 MOZ_NEVER_INLINE void ArrayLengthReadError(const char* aElementName);
588 MOZ_NEVER_INLINE void SentinelReadError(const char* aElementName);
591 * Annotate the crash reporter with the error code from the most recent system
592 * call. Returns the system error.
594 void AnnotateSystemError();
596 // The ActorLifecycleProxy is a helper type used internally by IPC to maintain a
597 // maybe-owning reference to an IProtocol object. For well-behaved actors
598 // which are not freed until after their `Dealloc` method is called, a
599 // reference to an actor's `ActorLifecycleProxy` object is an owning one, as the
600 // `Dealloc` method will only be called when all references to the
601 // `ActorLifecycleProxy` are released.
603 // Unfortunately, some actors may be destroyed before their `Dealloc` method
604 // is called. For these actors, `ActorLifecycleProxy` acts as a weak pointer,
605 // and will begin to return `nullptr` from its `Get()` method once the
606 // corresponding actor object has been destroyed.
608 // When calling a `Recv` method, IPC will hold a `ActorLifecycleProxy` reference
609 // to the target actor, meaning that well-behaved actors can behave as though a
610 // strong reference is being held.
612 // Generic IPC code MUST treat ActorLifecycleProxy references as weak
613 // references!
614 class ActorLifecycleProxy {
615 public:
616 NS_INLINE_DECL_REFCOUNTING_ONEVENTTARGET(ActorLifecycleProxy)
618 IProtocol* Get() { return mActor; }
620 WeakActorLifecycleProxy* GetWeakProxy();
622 private:
623 friend class IProtocol;
625 explicit ActorLifecycleProxy(IProtocol* aActor);
626 ~ActorLifecycleProxy();
628 ActorLifecycleProxy(const ActorLifecycleProxy&) = delete;
629 ActorLifecycleProxy& operator=(const ActorLifecycleProxy&) = delete;
631 IProtocol* MOZ_NON_OWNING_REF mActor;
633 // Hold a reference to the actor's manager's ActorLifecycleProxy to help
634 // prevent it from dying while we're still alive!
635 RefPtr<ActorLifecycleProxy> mManager;
637 // When requested, the current self-referencing weak reference for this
638 // ActorLifecycleProxy.
639 RefPtr<WeakActorLifecycleProxy> mWeakProxy;
642 // Unlike ActorLifecycleProxy, WeakActorLifecycleProxy only holds a weak
643 // reference to both the proxy and the actual actor, meaning that holding this
644 // type will not attempt to keep the actor object alive.
646 // This type is safe to hold on threads other than the actor's thread, but is
647 // _NOT_ safe to access on other threads, as actors and ActorLifecycleProxy
648 // objects are not threadsafe.
649 class WeakActorLifecycleProxy final {
650 public:
651 NS_INLINE_DECL_THREADSAFE_REFCOUNTING(WeakActorLifecycleProxy)
653 // May only be called on the actor's event target.
654 // Will return `nullptr` if the actor has already been destroyed from IPC's
655 // point of view.
656 IProtocol* Get() const;
658 // Safe to call on any thread.
659 nsISerialEventTarget* ActorEventTarget() const { return mActorEventTarget; }
661 private:
662 friend class ActorLifecycleProxy;
664 explicit WeakActorLifecycleProxy(ActorLifecycleProxy* aProxy);
665 ~WeakActorLifecycleProxy();
667 WeakActorLifecycleProxy(const WeakActorLifecycleProxy&) = delete;
668 WeakActorLifecycleProxy& operator=(const WeakActorLifecycleProxy&) = delete;
670 // This field may only be accessed on the actor's thread, and will be
671 // automatically cleared when the ActorLifecycleProxy is destroyed.
672 ActorLifecycleProxy* MOZ_NON_OWNING_REF mProxy;
674 // The serial event target which owns the actor, and is the only thread where
675 // it is OK to access the ActorLifecycleProxy.
676 const nsCOMPtr<nsISerialEventTarget> mActorEventTarget;
679 class IPDLResolverInner final {
680 public:
681 NS_INLINE_DECL_THREADSAFE_REFCOUNTING_WITH_DESTROY(IPDLResolverInner,
682 Destroy())
684 explicit IPDLResolverInner(UniquePtr<IPC::Message> aReply, IProtocol* aActor);
686 template <typename F>
687 void Resolve(F&& aWrite) {
688 ResolveOrReject(true, aWrite);
691 private:
692 void ResolveOrReject(bool aResolve,
693 FunctionRef<void(IPC::Message*, IProtocol*)> aWrite);
695 void Destroy();
696 ~IPDLResolverInner();
698 UniquePtr<IPC::Message> mReply;
699 RefPtr<WeakActorLifecycleProxy> mWeakProxy;
702 } // namespace ipc
704 template <typename Protocol>
705 class ManagedContainer {
706 public:
707 using iterator = typename nsTArray<Protocol*>::const_iterator;
709 iterator begin() const { return mArray.begin(); }
710 iterator end() const { return mArray.end(); }
711 iterator cbegin() const { return begin(); }
712 iterator cend() const { return end(); }
714 bool IsEmpty() const { return mArray.IsEmpty(); }
715 uint32_t Count() const { return mArray.Length(); }
717 void ToArray(nsTArray<Protocol*>& aArray) const {
718 aArray.AppendElements(mArray);
721 bool EnsureRemoved(Protocol* aElement) {
722 return mArray.RemoveElementSorted(aElement);
725 void Insert(Protocol* aElement) {
726 // Equivalent to `InsertElementSorted`, avoiding inserting a duplicate
727 // element.
728 size_t index = mArray.IndexOfFirstElementGt(aElement);
729 if (index == 0 || mArray[index - 1] != aElement) {
730 mArray.InsertElementAt(index, aElement);
734 void Clear() { mArray.Clear(); }
736 private:
737 nsTArray<Protocol*> mArray;
740 template <typename Protocol>
741 Protocol* LoneManagedOrNullAsserts(
742 const ManagedContainer<Protocol>& aManagees) {
743 if (aManagees.IsEmpty()) {
744 return nullptr;
746 MOZ_ASSERT(aManagees.Count() == 1);
747 return *aManagees.cbegin();
750 template <typename Protocol>
751 Protocol* SingleManagedOrNull(const ManagedContainer<Protocol>& aManagees) {
752 if (aManagees.Count() != 1) {
753 return nullptr;
755 return *aManagees.cbegin();
758 } // namespace mozilla
760 #endif // mozilla_ipc_ProtocolUtils_h