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
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"
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>
48 // WARNING: this takes into account the private, special-message-type
49 // enum in ipc_channel.h. They need to be kept in sync.
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.
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.
88 class nsISerialEventTarget
;
104 class ProtocolFuzzerHelper
;
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.
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
145 // A live link is connected to the other side of this actor.
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).
152 // The link has been destroyed, and messages will no longer be sent or
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
{
170 enum ActorDestroyReason
{
176 ManagedEndpointDropped
179 typedef base::ProcessId ProcessId
;
180 typedef IPC::Message Message
;
182 IProtocol(ProtocolId aProtoId
, Side aSide
)
184 mProtocolId(aProtoId
),
186 mLinkStatus(LinkStatus::Inactive
),
187 mLifecycleProxy(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
, bool aUnsafe
,
203 Shmem::SharedMemory
* LookupSharedMemory(int32_t aId
);
204 bool IsTrackingSharedMemory(Shmem::SharedMemory
* aSegment
);
205 bool DestroySharedMemory(Shmem
& aShmem
);
207 MessageChannel
* GetIPCChannel();
208 const MessageChannel
* GetIPCChannel() const;
210 // Get the nsISerialEventTarget which all messages sent to this actor will be
211 // processed on. Unless stated otherwise, all operations on IProtocol which
212 // don't occur on this `nsISerialEventTarget` are unsafe.
213 nsISerialEventTarget
* GetActorEventTarget();
215 // Actor lifecycle and other properties.
216 ProtocolId
GetProtocolId() const { return mProtocolId
; }
217 const char* GetProtocolName() const { return ProtocolIdToName(mProtocolId
); }
219 int32_t Id() const { return mId
; }
220 IProtocol
* Manager() const { return mManager
; }
222 ActorLifecycleProxy
* GetLifecycleProxy() { return mLifecycleProxy
; }
223 WeakActorLifecycleProxy
* GetWeakLifecycleProxy();
225 Side
GetSide() const { return mSide
; }
226 bool CanSend() const { return mLinkStatus
== LinkStatus::Connected
; }
227 bool CanRecv() const {
228 return mLinkStatus
== LinkStatus::Connected
||
229 mLinkStatus
== LinkStatus::Doomed
;
232 // Remove or deallocate a managee given its type.
233 virtual void RemoveManagee(int32_t, IProtocol
*) = 0;
234 virtual void DeallocManagee(int32_t, IProtocol
*) = 0;
236 Maybe
<IProtocol
*> ReadActor(IPC::MessageReader
* aReader
, bool aNullable
,
237 const char* aActorDescription
,
238 int32_t aProtocolTypeId
);
240 virtual Result
OnMessageReceived(const Message
& aMessage
) = 0;
241 virtual Result
OnMessageReceived(const Message
& aMessage
,
242 UniquePtr
<Message
>& aReply
) = 0;
243 virtual Result
OnCallReceived(const Message
& aMessage
,
244 UniquePtr
<Message
>& aReply
) = 0;
245 bool AllocShmem(size_t aSize
, Shmem
* aOutMem
);
246 bool AllocUnsafeShmem(size_t aSize
, Shmem
* aOutMem
);
247 bool DeallocShmem(Shmem
& aMem
);
249 void FatalError(const char* const aErrorMsg
) const;
250 virtual void HandleFatalError(const char* aErrorMsg
) const;
253 virtual ~IProtocol();
255 friend class IToplevelProtocol
;
256 friend class ActorLifecycleProxy
;
257 friend class IPDLResolverInner
;
258 friend class UntypedManagedEndpoint
;
260 void SetId(int32_t aId
);
262 // We have separate functions because the accessibility code manually
264 void SetManager(IProtocol
* aManager
);
266 // Sets the manager for the protocol and registers the protocol with
267 // its manager, setting up channels for the protocol as well. Not
268 // for use outside of IPDL.
269 void SetManagerAndRegister(IProtocol
* aManager
);
270 void SetManagerAndRegister(IProtocol
* aManager
, int32_t aId
);
272 // Helpers for calling `Send` on our underlying IPC channel.
273 bool ChannelSend(UniquePtr
<IPC::Message
> aMsg
);
274 bool ChannelSend(UniquePtr
<IPC::Message
> aMsg
,
275 UniquePtr
<IPC::Message
>* aReply
);
276 template <typename Value
>
277 void ChannelSend(UniquePtr
<IPC::Message
> aMsg
,
278 IPC::Message::msgid_t aReplyMsgId
,
279 ResolveCallback
<Value
>&& aResolve
,
280 RejectCallback
&& aReject
) {
282 GetIPCChannel()->Send(std::move(aMsg
), Id(), aReplyMsgId
,
283 std::move(aResolve
), std::move(aReject
));
285 WarnMessageDiscarded(aMsg
.get());
286 aReject(ResponseRejectReason::SendError
);
290 // Collect all actors managed by this object in an array. To make this safer
291 // to iterate, `ActorLifecycleProxy` references are returned rather than raw
293 virtual void AllManagedActors(
294 nsTArray
<RefPtr
<ActorLifecycleProxy
>>& aActors
) const = 0;
296 // Internal method called when the actor becomes connected.
297 void ActorConnected();
299 // Called immediately before setting the actor state to doomed, and triggering
300 // async actor destruction. Messages may be sent from this callback, but no
302 // FIXME(nika): This is currently unused!
303 virtual void ActorDoom() {}
306 // Called when the actor has been destroyed due to an error, a __delete__
307 // message, or a __doom__ reply.
308 virtual void ActorDestroy(ActorDestroyReason aWhy
) {}
309 void DestroySubtree(ActorDestroyReason aWhy
);
311 // Called when IPC has acquired its first reference to the actor. This method
312 // may take references which will later be freed by `ActorDealloc`.
313 virtual void ActorAlloc() {}
315 // Called when IPC has released its final reference to the actor. It will call
316 // the dealloc method, causing the actor to be actually freed.
318 // The actor has been freed after this method returns.
319 virtual void ActorDealloc() {
321 Manager()->DeallocManagee(mProtocolId
, this);
325 static const int32_t kNullActorId
= 0;
326 static const int32_t kFreedActorId
= 1;
330 void WarnMessageDiscarded(IPC::Message
* aMsg
);
332 void WarnMessageDiscarded(IPC::Message
*) {}
336 ProtocolId mProtocolId
;
338 LinkStatus mLinkStatus
;
339 ActorLifecycleProxy
* mLifecycleProxy
;
341 IToplevelProtocol
* mToplevel
;
344 #define IPC_OK() mozilla::ipc::IPCResult::Ok()
345 #define IPC_FAIL(actor, why) \
346 mozilla::ipc::IPCResult::Fail(WrapNotNull(actor), __func__, (why))
347 #define IPC_FAIL_NO_REASON(actor) \
348 mozilla::ipc::IPCResult::Fail(WrapNotNull(actor), __func__)
351 * All message deserializer and message handler should return this
352 * type via above macros. We use a less generic name here to avoid
353 * conflict with mozilla::Result because we have quite a few using
354 * namespace mozilla::ipc; in the code base.
358 static IPCResult
Ok() { return IPCResult(true); }
359 static IPCResult
Fail(NotNull
<IProtocol
*> aActor
, const char* aWhere
,
360 const char* aWhy
= "");
361 MOZ_IMPLICIT
operator bool() const { return mSuccess
; }
364 explicit IPCResult(bool aResult
) : mSuccess(aResult
) {}
368 class UntypedEndpoint
;
370 template <class PFooSide
>
373 template <class PFooSide
>
374 class ManagedEndpoint
;
377 * All top-level protocols should inherit this class.
379 * IToplevelProtocol tracks all top-level protocol actors created from
380 * this protocol actor.
382 class IToplevelProtocol
: public IProtocol
{
384 friend class mozilla::ipc::ProtocolFuzzerHelper
;
387 template <class PFooSide
>
388 friend class Endpoint
;
391 explicit IToplevelProtocol(const char* aName
, ProtocolId aProtoId
,
393 ~IToplevelProtocol() = default;
396 // Shadow methods on IProtocol which are implemented directly on toplevel
398 int32_t Register(IProtocol
* aRouted
);
399 int32_t RegisterID(IProtocol
* aRouted
, int32_t aId
);
400 IProtocol
* Lookup(int32_t aId
);
401 void Unregister(int32_t aId
);
403 Shmem::SharedMemory
* CreateSharedMemory(size_t aSize
, bool aUnsafe
,
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
, const nsID
& aMessageChannelId
,
419 base::ProcessId aOtherPid
,
420 nsISerialEventTarget
* aEventTarget
= nullptr);
422 bool Open(IToplevelProtocol
* aTarget
, nsISerialEventTarget
* aEventTarget
,
423 mozilla::ipc::Side aSide
= mozilla::ipc::UnknownSide
);
425 // Open a toplevel actor such that both ends of the actor's channel are on
426 // the same thread. This method should be called on the thread to perform
429 // WARNING: Attempting to send a sync or intr message on the same thread
431 bool OpenOnSameThread(IToplevelProtocol
* aTarget
,
432 mozilla::ipc::Side aSide
= mozilla::ipc::UnknownSide
);
435 * This sends a special message that is processed on the IO thread, so that
436 * other actors can know that the process will soon shutdown.
438 void NotifyImpendingShutdown();
442 void SetReplyTimeoutMs(int32_t aTimeoutMs
);
444 void DeallocShmems();
445 bool ShmemCreated(const Message
& aMsg
);
446 bool ShmemDestroyed(const Message
& aMsg
);
448 virtual bool ShouldContinueFromReplyTimeout() { return false; }
450 // WARNING: This function is called with the MessageChannel monitor held.
451 virtual void IntentionalCrash() { MOZ_CRASH("Intentional IPDL crash"); }
453 // The code here is only useful for fuzzing. It should not be used for any
456 // Returns true if we should simulate a timeout.
457 // WARNING: This is a testing-only function that is called with the
458 // MessageChannel monitor held. Don't do anything fancy here or we could
460 virtual bool ArtificialTimeout() { return false; }
462 // Returns true if we want to cause the worker thread to sleep with the
464 virtual bool NeedArtificialSleep() { return false; }
466 // This function should be implemented to sleep for some amount of time on
467 // the worker thread. Will only be called if NeedArtificialSleep() returns
469 virtual void ArtificialSleep() {}
471 bool ArtificialTimeout() { return false; }
472 bool NeedArtificialSleep() { return false; }
473 void ArtificialSleep() {}
476 bool IsOnCxxStack() const;
479 * Return true if windows messages can be handled while waiting for a reply
480 * to a sync IPDL message.
482 virtual bool HandleWindowsMessages(const Message
& aMsg
) const { return true; }
484 virtual void ProcessRemoteNativeEventsInInterruptCall() {}
486 virtual void OnChannelReceivedMessage(const Message
& aMsg
) {}
488 void OnIPCChannelOpened() { ActorConnected(); }
490 base::ProcessId
OtherPidMaybeInvalid() const { return mOtherPid
; }
496 using IDMap
= nsTHashMap
<nsUint32HashKey
, T
>;
498 base::ProcessId mOtherPid
;
501 // Used to be on mState
502 int32_t mLastLocalId
;
503 IDMap
<IProtocol
*> mActorMap
;
504 IDMap
<Shmem::SharedMemory
*> mShmemMap
;
506 MessageChannel mChannel
;
509 class IShmemAllocator
{
511 virtual bool AllocShmem(size_t aSize
, mozilla::ipc::Shmem
* aShmem
) = 0;
512 virtual bool AllocUnsafeShmem(size_t aSize
, mozilla::ipc::Shmem
* aShmem
) = 0;
513 virtual bool DeallocShmem(mozilla::ipc::Shmem
& aShmem
) = 0;
516 #define FORWARD_SHMEM_ALLOCATOR_TO(aImplClass) \
517 virtual bool AllocShmem(size_t aSize, mozilla::ipc::Shmem* aShmem) \
519 return aImplClass::AllocShmem(aSize, aShmem); \
521 virtual bool AllocUnsafeShmem(size_t aSize, mozilla::ipc::Shmem* aShmem) \
523 return aImplClass::AllocUnsafeShmem(aSize, aShmem); \
525 virtual bool DeallocShmem(mozilla::ipc::Shmem& aShmem) override { \
526 return aImplClass::DeallocShmem(aShmem); \
529 inline bool LoggingEnabled() {
530 #if defined(DEBUG) || defined(FUZZING)
531 return !!PR_GetEnv("MOZ_IPC_MESSAGE_LOG");
537 #if defined(DEBUG) || defined(FUZZING)
538 bool LoggingEnabledFor(const char* aTopLevelProtocol
, const char* aFilter
);
541 inline bool LoggingEnabledFor(const char* aTopLevelProtocol
) {
542 #if defined(DEBUG) || defined(FUZZING)
543 return LoggingEnabledFor(aTopLevelProtocol
, PR_GetEnv("MOZ_IPC_MESSAGE_LOG"));
549 MOZ_NEVER_INLINE
void LogMessageForProtocol(const char* aTopLevelProtocol
,
550 base::ProcessId aOtherPid
,
551 const char* aContextDescription
,
553 MessageDirection aDirection
);
555 MOZ_NEVER_INLINE
void ProtocolErrorBreakpoint(const char* aMsg
);
557 // IPC::MessageReader and IPC::MessageWriter call this function for FatalError
558 // calls which come from serialization/deserialization.
559 MOZ_NEVER_INLINE
void PickleFatalError(const char* aMsg
, IProtocol
* aActor
);
561 // The code generator calls this function for errors which come from the
562 // methods of protocols. Doing this saves codesize by making the error
563 // cases significantly smaller.
564 MOZ_NEVER_INLINE
void FatalError(const char* aMsg
, bool aIsParent
);
566 // The code generator calls this function for errors which are not
567 // protocol-specific: errors in generated struct methods or errors in
568 // transition functions, for instance. Doing this saves codesize by
569 // by making the error cases significantly smaller.
570 MOZ_NEVER_INLINE
void LogicError(const char* aMsg
);
572 MOZ_NEVER_INLINE
void ActorIdReadError(const char* aActorDescription
);
574 MOZ_NEVER_INLINE
void BadActorIdError(const char* aActorDescription
);
576 MOZ_NEVER_INLINE
void ActorLookupError(const char* aActorDescription
);
578 MOZ_NEVER_INLINE
void MismatchedActorTypeError(const char* aActorDescription
);
580 MOZ_NEVER_INLINE
void UnionTypeReadError(const char* aUnionName
);
582 MOZ_NEVER_INLINE
void ArrayLengthReadError(const char* aElementName
);
584 MOZ_NEVER_INLINE
void SentinelReadError(const char* aElementName
);
587 * Annotate the crash reporter with the error code from the most recent system
588 * call. Returns the system error.
590 void AnnotateSystemError();
592 // The ActorLifecycleProxy is a helper type used internally by IPC to maintain a
593 // maybe-owning reference to an IProtocol object. For well-behaved actors
594 // which are not freed until after their `Dealloc` method is called, a
595 // reference to an actor's `ActorLifecycleProxy` object is an owning one, as the
596 // `Dealloc` method will only be called when all references to the
597 // `ActorLifecycleProxy` are released.
599 // Unfortunately, some actors may be destroyed before their `Dealloc` method
600 // is called. For these actors, `ActorLifecycleProxy` acts as a weak pointer,
601 // and will begin to return `nullptr` from its `Get()` method once the
602 // corresponding actor object has been destroyed.
604 // When calling a `Recv` method, IPC will hold a `ActorLifecycleProxy` reference
605 // to the target actor, meaning that well-behaved actors can behave as though a
606 // strong reference is being held.
608 // Generic IPC code MUST treat ActorLifecycleProxy references as weak
610 class ActorLifecycleProxy
{
612 NS_INLINE_DECL_REFCOUNTING_ONEVENTTARGET(ActorLifecycleProxy
)
614 IProtocol
* Get() { return mActor
; }
616 WeakActorLifecycleProxy
* GetWeakProxy();
619 friend class IProtocol
;
621 explicit ActorLifecycleProxy(IProtocol
* aActor
);
622 ~ActorLifecycleProxy();
624 ActorLifecycleProxy(const ActorLifecycleProxy
&) = delete;
625 ActorLifecycleProxy
& operator=(const ActorLifecycleProxy
&) = delete;
627 IProtocol
* MOZ_NON_OWNING_REF mActor
;
629 // Hold a reference to the actor's manager's ActorLifecycleProxy to help
630 // prevent it from dying while we're still alive!
631 RefPtr
<ActorLifecycleProxy
> mManager
;
633 // When requested, the current self-referencing weak reference for this
634 // ActorLifecycleProxy.
635 RefPtr
<WeakActorLifecycleProxy
> mWeakProxy
;
638 // Unlike ActorLifecycleProxy, WeakActorLifecycleProxy only holds a weak
639 // reference to both the proxy and the actual actor, meaning that holding this
640 // type will not attempt to keep the actor object alive.
642 // This type is safe to hold on threads other than the actor's thread, but is
643 // _NOT_ safe to access on other threads, as actors and ActorLifecycleProxy
644 // objects are not threadsafe.
645 class WeakActorLifecycleProxy final
{
647 NS_INLINE_DECL_THREADSAFE_REFCOUNTING(WeakActorLifecycleProxy
)
649 // May only be called on the actor's event target.
650 // Will return `nullptr` if the actor has already been destroyed from IPC's
652 IProtocol
* Get() const;
654 // Safe to call on any thread.
655 nsISerialEventTarget
* ActorEventTarget() const { return mActorEventTarget
; }
658 friend class ActorLifecycleProxy
;
660 explicit WeakActorLifecycleProxy(ActorLifecycleProxy
* aProxy
);
661 ~WeakActorLifecycleProxy();
663 WeakActorLifecycleProxy(const WeakActorLifecycleProxy
&) = delete;
664 WeakActorLifecycleProxy
& operator=(const WeakActorLifecycleProxy
&) = delete;
666 // This field may only be accessed on the actor's thread, and will be
667 // automatically cleared when the ActorLifecycleProxy is destroyed.
668 ActorLifecycleProxy
* MOZ_NON_OWNING_REF mProxy
;
670 // The serial event target which owns the actor, and is the only thread where
671 // it is OK to access the ActorLifecycleProxy.
672 const nsCOMPtr
<nsISerialEventTarget
> mActorEventTarget
;
675 class IPDLResolverInner final
{
677 NS_INLINE_DECL_THREADSAFE_REFCOUNTING_WITH_DESTROY(IPDLResolverInner
,
680 explicit IPDLResolverInner(UniquePtr
<IPC::Message
> aReply
, IProtocol
* aActor
);
682 template <typename F
>
683 void Resolve(F
&& aWrite
) {
684 ResolveOrReject(true, aWrite
);
688 void ResolveOrReject(bool aResolve
,
689 FunctionRef
<void(IPC::Message
*, IProtocol
*)> aWrite
);
692 ~IPDLResolverInner();
694 UniquePtr
<IPC::Message
> mReply
;
695 RefPtr
<WeakActorLifecycleProxy
> mWeakProxy
;
700 template <typename Protocol
>
701 class ManagedContainer
{
703 using iterator
= typename nsTArray
<Protocol
*>::const_iterator
;
705 iterator
begin() const { return mArray
.begin(); }
706 iterator
end() const { return mArray
.end(); }
707 iterator
cbegin() const { return begin(); }
708 iterator
cend() const { return end(); }
710 bool IsEmpty() const { return mArray
.IsEmpty(); }
711 uint32_t Count() const { return mArray
.Length(); }
713 void ToArray(nsTArray
<Protocol
*>& aArray
) const {
714 aArray
.AppendElements(mArray
);
717 bool EnsureRemoved(Protocol
* aElement
) {
718 return mArray
.RemoveElementSorted(aElement
);
721 void Insert(Protocol
* aElement
) {
722 // Equivalent to `InsertElementSorted`, avoiding inserting a duplicate
724 size_t index
= mArray
.IndexOfFirstElementGt(aElement
);
725 if (index
== 0 || mArray
[index
- 1] != aElement
) {
726 mArray
.InsertElementAt(index
, aElement
);
730 void Clear() { mArray
.Clear(); }
733 nsTArray
<Protocol
*> mArray
;
736 template <typename Protocol
>
737 Protocol
* LoneManagedOrNullAsserts(
738 const ManagedContainer
<Protocol
>& aManagees
) {
739 if (aManagees
.IsEmpty()) {
742 MOZ_ASSERT(aManagees
.Count() == 1);
743 return *aManagees
.cbegin();
746 template <typename Protocol
>
747 Protocol
* SingleManagedOrNull(const ManagedContainer
<Protocol
>& aManagees
) {
748 if (aManagees
.Count() != 1) {
751 return *aManagees
.cbegin();
754 } // namespace mozilla
756 #endif // mozilla_ipc_ProtocolUtils_h