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
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/UniquePtr.h"
26 #include "mozilla/ipc/MessageChannel.h"
27 #include "mozilla/ipc/MessageLink.h"
28 #include "mozilla/ipc/SharedMemory.h"
29 #include "mozilla/ipc/Shmem.h"
30 #include "nsPrintfCString.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
;
103 class ProtocolFdMapping
;
104 class ProtocolCloneContext
;
106 // Used to pass references to protocol actors across the wire.
107 // Actors created on the parent-side have a positive ID, and actors
108 // allocated on the child side have a negative ID.
113 enum class LinkStatus
: uint8_t {
114 // The actor has not established a link yet, or the actor is no longer in use
115 // by IPC, and its 'Dealloc' method has been called or is being called.
117 // NOTE: This state is used instead of an explicit `Freed` state when IPC no
118 // longer holds references to the current actor as we currently re-open
119 // existing actors. Once we fix these poorly behaved actors, this loopback
120 // state can be split to have the final state not be the same as the initial
124 // A live link is connected to the other side of this actor.
127 // The link has begun being destroyed. Messages may still be received, but
128 // cannot be sent. (exception: sync replies may be sent while Doomed).
131 // The link has been destroyed, and messages will no longer be sent or
136 typedef IPCMessageStart ProtocolId
;
138 // Generated by IPDL compiler
139 const char* ProtocolIdToName(IPCMessageStart aId
);
141 class IRefCountedProtocol
;
142 class IToplevelProtocol
;
143 class ActorLifecycleProxy
;
144 class WeakActorLifecycleProxy
;
145 class IPDLResolverInner
;
146 class UntypedManagedEndpoint
;
148 class IProtocol
: public HasResultCodes
{
150 enum ActorDestroyReason
{
156 ManagedEndpointDropped
159 typedef base::ProcessId ProcessId
;
160 typedef IPC::Message Message
;
162 IProtocol(ProtocolId aProtoId
, Side aSide
)
164 mProtocolId(aProtoId
),
166 mLinkStatus(LinkStatus::Inactive
),
167 mLifecycleProxy(nullptr),
169 mToplevel(nullptr) {}
171 IToplevelProtocol
* ToplevelProtocol() { return mToplevel
; }
172 const IToplevelProtocol
* ToplevelProtocol() const { return mToplevel
; }
174 // The following methods either directly forward to the toplevel protocol, or
175 // almost directly do.
176 int32_t Register(IProtocol
* aRouted
);
177 int32_t RegisterID(IProtocol
* aRouted
, int32_t aId
);
178 IProtocol
* Lookup(int32_t aId
);
179 void Unregister(int32_t aId
);
181 Shmem::SharedMemory
* CreateSharedMemory(size_t aSize
, bool aUnsafe
,
183 Shmem::SharedMemory
* LookupSharedMemory(int32_t aId
);
184 bool IsTrackingSharedMemory(Shmem::SharedMemory
* aSegment
);
185 bool DestroySharedMemory(Shmem
& aShmem
);
187 MessageChannel
* GetIPCChannel();
188 const MessageChannel
* GetIPCChannel() const;
190 // Get the nsISerialEventTarget which all messages sent to this actor will be
191 // processed on. Unless stated otherwise, all operations on IProtocol which
192 // don't occur on this `nsISerialEventTarget` are unsafe.
193 nsISerialEventTarget
* GetActorEventTarget();
195 // Actor lifecycle and other properties.
196 ProtocolId
GetProtocolId() const { return mProtocolId
; }
197 const char* GetProtocolName() const { return ProtocolIdToName(mProtocolId
); }
199 int32_t Id() const { return mId
; }
200 IProtocol
* Manager() const { return mManager
; }
202 ActorLifecycleProxy
* GetLifecycleProxy() { return mLifecycleProxy
; }
203 WeakActorLifecycleProxy
* GetWeakLifecycleProxy();
205 Side
GetSide() const { return mSide
; }
206 bool CanSend() const { return mLinkStatus
== LinkStatus::Connected
; }
207 bool CanRecv() const {
208 return mLinkStatus
== LinkStatus::Connected
||
209 mLinkStatus
== LinkStatus::Doomed
;
212 // Remove or deallocate a managee given its type.
213 virtual void RemoveManagee(int32_t, IProtocol
*) = 0;
214 virtual void DeallocManagee(int32_t, IProtocol
*) = 0;
216 Maybe
<IProtocol
*> ReadActor(IPC::MessageReader
* aReader
, bool aNullable
,
217 const char* aActorDescription
,
218 int32_t aProtocolTypeId
);
220 virtual Result
OnMessageReceived(const Message
& aMessage
) = 0;
221 virtual Result
OnMessageReceived(const Message
& aMessage
,
222 UniquePtr
<Message
>& aReply
) = 0;
223 bool AllocShmem(size_t aSize
, Shmem
* aOutMem
);
224 bool AllocUnsafeShmem(size_t aSize
, Shmem
* aOutMem
);
225 bool DeallocShmem(Shmem
& aMem
);
227 void FatalError(const char* const aErrorMsg
);
228 virtual void HandleFatalError(const char* aErrorMsg
);
231 virtual ~IProtocol();
233 friend class IToplevelProtocol
;
234 friend class ActorLifecycleProxy
;
235 friend class IPDLResolverInner
;
236 friend class UntypedManagedEndpoint
;
238 void SetId(int32_t aId
);
240 // We have separate functions because the accessibility code manually
242 void SetManager(IProtocol
* aManager
);
244 // Sets the manager for the protocol and registers the protocol with
245 // its manager, setting up channels for the protocol as well. Not
246 // for use outside of IPDL.
247 void SetManagerAndRegister(IProtocol
* aManager
);
248 void SetManagerAndRegister(IProtocol
* aManager
, int32_t aId
);
250 // Helpers for calling `Send` on our underlying IPC channel.
251 bool ChannelSend(UniquePtr
<IPC::Message
> aMsg
);
252 bool ChannelSend(UniquePtr
<IPC::Message
> aMsg
,
253 UniquePtr
<IPC::Message
>* aReply
);
254 template <typename Value
>
255 void ChannelSend(UniquePtr
<IPC::Message
> aMsg
,
256 IPC::Message::msgid_t aReplyMsgId
,
257 ResolveCallback
<Value
>&& aResolve
,
258 RejectCallback
&& aReject
) {
260 GetIPCChannel()->Send(std::move(aMsg
), Id(), aReplyMsgId
,
261 std::move(aResolve
), std::move(aReject
));
263 WarnMessageDiscarded(aMsg
.get());
264 aReject(ResponseRejectReason::SendError
);
268 // Collect all actors managed by this object in an array. To make this safer
269 // to iterate, `ActorLifecycleProxy` references are returned rather than raw
271 virtual void AllManagedActors(
272 nsTArray
<RefPtr
<ActorLifecycleProxy
>>& aActors
) const = 0;
274 virtual uint32_t AllManagedActorsCount() const = 0;
276 // Internal method called when the actor becomes connected.
277 void ActorConnected();
279 // Called immediately before setting the actor state to doomed, and triggering
280 // async actor destruction. Messages may be sent from this callback, but no
282 // FIXME(nika): This is currently unused!
283 virtual void ActorDoom() {}
286 // Called when the actor has been destroyed due to an error, a __delete__
287 // message, or a __doom__ reply.
288 virtual void ActorDestroy(ActorDestroyReason aWhy
) {}
289 void DestroySubtree(ActorDestroyReason aWhy
);
291 // Called when IPC has acquired its first reference to the actor. This method
292 // may take references which will later be freed by `ActorDealloc`.
293 virtual void ActorAlloc() = 0;
295 // Called when IPC has released its final reference to the actor. It will call
296 // the dealloc method, causing the actor to be actually freed.
298 // The actor has been freed after this method returns.
299 virtual void ActorDealloc() = 0;
301 static const int32_t kNullActorId
= 0;
302 static const int32_t kFreedActorId
= 1;
306 void WarnMessageDiscarded(IPC::Message
* aMsg
);
308 void WarnMessageDiscarded(IPC::Message
*) {}
312 ProtocolId mProtocolId
;
314 LinkStatus mLinkStatus
;
315 ActorLifecycleProxy
* mLifecycleProxy
;
317 IToplevelProtocol
* mToplevel
;
320 #define IPC_OK() mozilla::ipc::IPCResult::Ok()
321 #define IPC_FAIL(actor, why) \
322 mozilla::ipc::IPCResult::Fail(WrapNotNull(actor), __func__, (why))
323 #define IPC_FAIL_NO_REASON(actor) \
324 mozilla::ipc::IPCResult::Fail(WrapNotNull(actor), __func__)
327 * IPC_FAIL_UNSAFE_PRINTF(actor, format, ...)
329 * Create a failure IPCResult with a dynamic reason-string.
331 * @note This macro causes data collection because IPC failure reasons may be
332 * sent to crash-stats, where they are publicly visible. Firefox data stewards
333 * must do data review on usages of this macro.
335 #define IPC_FAIL_UNSAFE_PRINTF(actor, format, ...) \
336 mozilla::ipc::IPCResult::FailUnsafePrintfImpl( \
337 WrapNotNull(actor), __func__, nsPrintfCString(format, ##__VA_ARGS__))
339 #define IPC_TEST_FAIL(actor) \
340 mozilla::ipc::IPCResult::FailForTesting(WrapNotNull(actor), __func__, "")
343 * All message deserializers and message handlers should return this type via
344 * the above macros. We use a less generic name here to avoid conflict with
345 * `mozilla::Result` because we have quite a few `using namespace mozilla::ipc;`
348 * Note that merely constructing a failure-result, whether directly or via the
349 * IPC_FAIL macros, causes the associated error message to be processed
354 static IPCResult
Ok() { return IPCResult(true); }
356 // IPC failure messages can sometimes end up in telemetry. As such, to avoid
357 // accidentally exfiltrating sensitive information without a data review, we
358 // require that they be constant strings.
359 template <size_t N
, size_t M
>
360 static IPCResult
Fail(NotNull
<IProtocol
*> aActor
, const char (&aWhere
)[N
],
361 const char (&aWhy
)[M
]) {
362 return FailImpl(aActor
, aWhere
, aWhy
);
365 static IPCResult
Fail(NotNull
<IProtocol
*> aActor
, const char (&aWhere
)[N
]) {
366 return FailImpl(aActor
, aWhere
, "");
369 MOZ_IMPLICIT
operator bool() const { return mSuccess
; }
371 // Only used by IPC_FAIL_UNSAFE_PRINTF (q.v.). Do not call this directly. (Or
372 // at least get data-review's approval if you do.)
374 static IPCResult
FailUnsafePrintfImpl(NotNull
<IProtocol
*> aActor
,
375 const char (&aWhere
)[N
],
376 nsPrintfCString
const& aWhy
) {
377 return FailImpl(aActor
, aWhere
, aWhy
.get());
380 // Only used in testing.
381 static IPCResult
FailForTesting(NotNull
<IProtocol
*> aActor
,
382 const char* aWhere
, const char* aWhy
);
385 static IPCResult
FailImpl(NotNull
<IProtocol
*> aActor
, const char* aWhere
,
388 explicit IPCResult(bool aResult
) : mSuccess(aResult
) {}
392 class UntypedEndpoint
;
394 template <class PFooSide
>
397 template <class PFooSide
>
398 class ManagedEndpoint
;
401 * All refcounted protocols should inherit this class.
403 class IRefCountedProtocol
: public IProtocol
{
405 NS_INLINE_DECL_PURE_VIRTUAL_REFCOUNTING
407 using IProtocol::IProtocol
;
411 * All top-level protocols should inherit this class.
413 * IToplevelProtocol tracks all top-level protocol actors created from
414 * this protocol actor.
416 class IToplevelProtocol
: public IRefCountedProtocol
{
417 template <class PFooSide
>
418 friend class Endpoint
;
421 explicit IToplevelProtocol(const char* aName
, ProtocolId aProtoId
,
423 ~IToplevelProtocol() = default;
426 // Shadow methods on IProtocol which are implemented directly on toplevel
428 int32_t Register(IProtocol
* aRouted
);
429 int32_t RegisterID(IProtocol
* aRouted
, int32_t aId
);
430 IProtocol
* Lookup(int32_t aId
);
431 void Unregister(int32_t aId
);
433 Shmem::SharedMemory
* CreateSharedMemory(size_t aSize
, bool aUnsafe
,
435 Shmem::SharedMemory
* LookupSharedMemory(int32_t aId
);
436 bool IsTrackingSharedMemory(Shmem::SharedMemory
* aSegment
);
437 bool DestroySharedMemory(Shmem
& aShmem
);
439 MessageChannel
* GetIPCChannel() { return &mChannel
; }
440 const MessageChannel
* GetIPCChannel() const { return &mChannel
; }
442 void SetOtherProcessId(base::ProcessId aOtherPid
);
444 virtual void OnChannelClose() = 0;
445 virtual void OnChannelError() = 0;
446 virtual void ProcessingError(Result aError
, const char* aMsgName
) {}
448 bool Open(ScopedPort aPort
, const nsID
& aMessageChannelId
,
449 base::ProcessId aOtherPid
,
450 nsISerialEventTarget
* aEventTarget
= nullptr);
452 bool Open(IToplevelProtocol
* aTarget
, nsISerialEventTarget
* aEventTarget
,
453 mozilla::ipc::Side aSide
= mozilla::ipc::UnknownSide
);
455 // Open a toplevel actor such that both ends of the actor's channel are on
456 // the same thread. This method should be called on the thread to perform
459 // WARNING: Attempting to send a sync message on the same thread will crash.
460 bool OpenOnSameThread(IToplevelProtocol
* aTarget
,
461 mozilla::ipc::Side aSide
= mozilla::ipc::UnknownSide
);
464 * This sends a special message that is processed on the IO thread, so that
465 * other actors can know that the process will soon shutdown.
467 void NotifyImpendingShutdown();
471 void SetReplyTimeoutMs(int32_t aTimeoutMs
);
473 void DeallocShmems();
474 bool ShmemCreated(const Message
& aMsg
);
475 bool ShmemDestroyed(const Message
& aMsg
);
477 virtual bool ShouldContinueFromReplyTimeout() { return false; }
479 // WARNING: This function is called with the MessageChannel monitor held.
480 virtual void IntentionalCrash() { MOZ_CRASH("Intentional IPDL crash"); }
482 // The code here is only useful for fuzzing. It should not be used for any
485 // Returns true if we should simulate a timeout.
486 // WARNING: This is a testing-only function that is called with the
487 // MessageChannel monitor held. Don't do anything fancy here or we could
489 virtual bool ArtificialTimeout() { return false; }
491 // Returns true if we want to cause the worker thread to sleep with the
493 virtual bool NeedArtificialSleep() { return false; }
495 // This function should be implemented to sleep for some amount of time on
496 // the worker thread. Will only be called if NeedArtificialSleep() returns
498 virtual void ArtificialSleep() {}
500 bool ArtificialTimeout() { return false; }
501 bool NeedArtificialSleep() { return false; }
502 void ArtificialSleep() {}
505 bool IsOnCxxStack() const;
507 virtual void ProcessRemoteNativeEventsInInterruptCall() {}
509 virtual void OnChannelReceivedMessage(const Message
& aMsg
) {}
511 void OnIPCChannelOpened() { ActorConnected(); }
513 base::ProcessId
OtherPidMaybeInvalid() const { return mOtherPid
; }
519 using IDMap
= nsTHashMap
<nsUint32HashKey
, T
>;
521 base::ProcessId mOtherPid
;
524 // Used to be on mState
525 int32_t mLastLocalId
;
526 IDMap
<IProtocol
*> mActorMap
;
527 IDMap
<RefPtr
<Shmem::SharedMemory
>> mShmemMap
;
529 MessageChannel mChannel
;
532 class IShmemAllocator
{
534 virtual bool AllocShmem(size_t aSize
, mozilla::ipc::Shmem
* aShmem
) = 0;
535 virtual bool AllocUnsafeShmem(size_t aSize
, mozilla::ipc::Shmem
* aShmem
) = 0;
536 virtual bool DeallocShmem(mozilla::ipc::Shmem
& aShmem
) = 0;
539 #define FORWARD_SHMEM_ALLOCATOR_TO(aImplClass) \
540 virtual bool AllocShmem(size_t aSize, mozilla::ipc::Shmem* aShmem) \
542 return aImplClass::AllocShmem(aSize, aShmem); \
544 virtual bool AllocUnsafeShmem(size_t aSize, mozilla::ipc::Shmem* aShmem) \
546 return aImplClass::AllocUnsafeShmem(aSize, aShmem); \
548 virtual bool DeallocShmem(mozilla::ipc::Shmem& aShmem) override { \
549 return aImplClass::DeallocShmem(aShmem); \
552 inline bool LoggingEnabled() {
553 #if defined(DEBUG) || defined(FUZZING)
554 return !!PR_GetEnv("MOZ_IPC_MESSAGE_LOG");
560 #if defined(DEBUG) || defined(FUZZING)
561 bool LoggingEnabledFor(const char* aTopLevelProtocol
, mozilla::ipc::Side aSide
,
562 const char* aFilter
);
565 inline bool LoggingEnabledFor(const char* aTopLevelProtocol
,
566 mozilla::ipc::Side aSide
) {
567 #if defined(DEBUG) || defined(FUZZING)
568 return LoggingEnabledFor(aTopLevelProtocol
, aSide
,
569 PR_GetEnv("MOZ_IPC_MESSAGE_LOG"));
575 MOZ_NEVER_INLINE
void LogMessageForProtocol(const char* aTopLevelProtocol
,
576 base::ProcessId aOtherPid
,
577 const char* aContextDescription
,
579 MessageDirection aDirection
);
581 MOZ_NEVER_INLINE
void ProtocolErrorBreakpoint(const char* aMsg
);
583 // IPC::MessageReader and IPC::MessageWriter call this function for FatalError
584 // calls which come from serialization/deserialization.
585 MOZ_NEVER_INLINE
void PickleFatalError(const char* aMsg
, IProtocol
* aActor
);
587 // The code generator calls this function for errors which come from the
588 // methods of protocols. Doing this saves codesize by making the error
589 // cases significantly smaller.
590 MOZ_NEVER_INLINE
void FatalError(const char* aMsg
, bool aIsParent
);
592 // The code generator calls this function for errors which are not
593 // protocol-specific: errors in generated struct methods or errors in
594 // transition functions, for instance. Doing this saves codesize by
595 // by making the error cases significantly smaller.
596 MOZ_NEVER_INLINE
void LogicError(const char* aMsg
);
598 MOZ_NEVER_INLINE
void ActorIdReadError(const char* aActorDescription
);
600 MOZ_NEVER_INLINE
void BadActorIdError(const char* aActorDescription
);
602 MOZ_NEVER_INLINE
void ActorLookupError(const char* aActorDescription
);
604 MOZ_NEVER_INLINE
void MismatchedActorTypeError(const char* aActorDescription
);
606 MOZ_NEVER_INLINE
void UnionTypeReadError(const char* aUnionName
);
608 MOZ_NEVER_INLINE
void ArrayLengthReadError(const char* aElementName
);
610 MOZ_NEVER_INLINE
void SentinelReadError(const char* aElementName
);
613 * Annotate the crash reporter with the error code from the most recent system
614 * call. Returns the system error.
616 void AnnotateSystemError();
618 // The ActorLifecycleProxy is a helper type used internally by IPC to maintain a
619 // maybe-owning reference to an IProtocol object. For well-behaved actors
620 // which are not freed until after their `Dealloc` method is called, a
621 // reference to an actor's `ActorLifecycleProxy` object is an owning one, as the
622 // `Dealloc` method will only be called when all references to the
623 // `ActorLifecycleProxy` are released.
625 // Unfortunately, some actors may be destroyed before their `Dealloc` method
626 // is called. For these actors, `ActorLifecycleProxy` acts as a weak pointer,
627 // and will begin to return `nullptr` from its `Get()` method once the
628 // corresponding actor object has been destroyed.
630 // When calling a `Recv` method, IPC will hold a `ActorLifecycleProxy` reference
631 // to the target actor, meaning that well-behaved actors can behave as though a
632 // strong reference is being held.
634 // Generic IPC code MUST treat ActorLifecycleProxy references as weak
636 class ActorLifecycleProxy
{
638 NS_INLINE_DECL_REFCOUNTING_ONEVENTTARGET(ActorLifecycleProxy
)
640 IProtocol
* Get() { return mActor
; }
642 WeakActorLifecycleProxy
* GetWeakProxy();
645 friend class IProtocol
;
647 explicit ActorLifecycleProxy(IProtocol
* aActor
);
648 ~ActorLifecycleProxy();
650 ActorLifecycleProxy(const ActorLifecycleProxy
&) = delete;
651 ActorLifecycleProxy
& operator=(const ActorLifecycleProxy
&) = delete;
653 IProtocol
* MOZ_NON_OWNING_REF mActor
;
655 // Hold a reference to the actor's manager's ActorLifecycleProxy to help
656 // prevent it from dying while we're still alive!
657 RefPtr
<ActorLifecycleProxy
> mManager
;
659 // When requested, the current self-referencing weak reference for this
660 // ActorLifecycleProxy.
661 RefPtr
<WeakActorLifecycleProxy
> mWeakProxy
;
664 // Unlike ActorLifecycleProxy, WeakActorLifecycleProxy only holds a weak
665 // reference to both the proxy and the actual actor, meaning that holding this
666 // type will not attempt to keep the actor object alive.
668 // This type is safe to hold on threads other than the actor's thread, but is
669 // _NOT_ safe to access on other threads, as actors and ActorLifecycleProxy
670 // objects are not threadsafe.
671 class WeakActorLifecycleProxy final
{
673 NS_INLINE_DECL_THREADSAFE_REFCOUNTING(WeakActorLifecycleProxy
)
675 // May only be called on the actor's event target.
676 // Will return `nullptr` if the actor has already been destroyed from IPC's
678 IProtocol
* Get() const;
680 // Safe to call on any thread.
681 nsISerialEventTarget
* ActorEventTarget() const { return mActorEventTarget
; }
684 friend class ActorLifecycleProxy
;
686 explicit WeakActorLifecycleProxy(ActorLifecycleProxy
* aProxy
);
687 ~WeakActorLifecycleProxy();
689 WeakActorLifecycleProxy(const WeakActorLifecycleProxy
&) = delete;
690 WeakActorLifecycleProxy
& operator=(const WeakActorLifecycleProxy
&) = delete;
692 // This field may only be accessed on the actor's thread, and will be
693 // automatically cleared when the ActorLifecycleProxy is destroyed.
694 ActorLifecycleProxy
* MOZ_NON_OWNING_REF mProxy
;
696 // The serial event target which owns the actor, and is the only thread where
697 // it is OK to access the ActorLifecycleProxy.
698 const nsCOMPtr
<nsISerialEventTarget
> mActorEventTarget
;
701 class IPDLResolverInner final
{
703 NS_INLINE_DECL_THREADSAFE_REFCOUNTING_WITH_DESTROY(IPDLResolverInner
,
706 explicit IPDLResolverInner(UniquePtr
<IPC::Message
> aReply
, IProtocol
* aActor
);
708 template <typename F
>
709 void Resolve(F
&& aWrite
) {
710 ResolveOrReject(true, std::forward
<F
>(aWrite
));
714 void ResolveOrReject(bool aResolve
,
715 FunctionRef
<void(IPC::Message
*, IProtocol
*)> aWrite
);
718 ~IPDLResolverInner();
720 UniquePtr
<IPC::Message
> mReply
;
721 RefPtr
<WeakActorLifecycleProxy
> mWeakProxy
;
726 template <typename Protocol
>
727 class ManagedContainer
{
729 using iterator
= typename nsTArray
<Protocol
*>::const_iterator
;
731 iterator
begin() const { return mArray
.begin(); }
732 iterator
end() const { return mArray
.end(); }
733 iterator
cbegin() const { return begin(); }
734 iterator
cend() const { return end(); }
736 bool IsEmpty() const { return mArray
.IsEmpty(); }
737 uint32_t Count() const { return mArray
.Length(); }
739 void ToArray(nsTArray
<Protocol
*>& aArray
) const {
740 aArray
.AppendElements(mArray
);
743 bool EnsureRemoved(Protocol
* aElement
) {
744 return mArray
.RemoveElementSorted(aElement
);
747 void Insert(Protocol
* aElement
) {
748 // Equivalent to `InsertElementSorted`, avoiding inserting a duplicate
750 size_t index
= mArray
.IndexOfFirstElementGt(aElement
);
751 if (index
== 0 || mArray
[index
- 1] != aElement
) {
752 mArray
.InsertElementAt(index
, aElement
);
756 void Clear() { mArray
.Clear(); }
759 nsTArray
<Protocol
*> mArray
;
762 template <typename Protocol
>
763 Protocol
* LoneManagedOrNullAsserts(
764 const ManagedContainer
<Protocol
>& aManagees
) {
765 if (aManagees
.IsEmpty()) {
768 MOZ_ASSERT(aManagees
.Count() == 1);
769 return *aManagees
.cbegin();
772 template <typename Protocol
>
773 Protocol
* SingleManagedOrNull(const ManagedContainer
<Protocol
>& aManagees
) {
774 if (aManagees
.Count() != 1) {
777 return *aManagees
.cbegin();
780 } // namespace mozilla
782 #endif // mozilla_ipc_ProtocolUtils_h