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 // What happens if Interrupt calls race?
114 enum RacyInterruptPolicy
{ RIPError
, RIPChildWins
, RIPParentWins
};
116 enum class LinkStatus
: uint8_t {
117 // The actor has not established a link yet, or the actor is no longer in use
118 // by IPC, and its 'Dealloc' method has been called or is being called.
120 // NOTE: This state is used instead of an explicit `Freed` state when IPC no
121 // longer holds references to the current actor as we currently re-open
122 // existing actors. Once we fix these poorly behaved actors, this loopback
123 // state can be split to have the final state not be the same as the initial
127 // A live link is connected to the other side of this actor.
130 // The link has begun being destroyed. Messages may still be received, but
131 // cannot be sent. (exception: sync/intr replies may be sent while Doomed).
134 // The link has been destroyed, and messages will no longer be sent or
139 typedef IPCMessageStart ProtocolId
;
141 // Generated by IPDL compiler
142 const char* ProtocolIdToName(IPCMessageStart aId
);
144 class IRefCountedProtocol
;
145 class IToplevelProtocol
;
146 class ActorLifecycleProxy
;
147 class WeakActorLifecycleProxy
;
148 class IPDLResolverInner
;
149 class UntypedManagedEndpoint
;
151 class IProtocol
: public HasResultCodes
{
153 enum ActorDestroyReason
{
159 ManagedEndpointDropped
162 typedef base::ProcessId ProcessId
;
163 typedef IPC::Message Message
;
165 IProtocol(ProtocolId aProtoId
, Side aSide
)
167 mProtocolId(aProtoId
),
169 mLinkStatus(LinkStatus::Inactive
),
170 mLifecycleProxy(nullptr),
172 mToplevel(nullptr) {}
174 IToplevelProtocol
* ToplevelProtocol() { return mToplevel
; }
175 const IToplevelProtocol
* ToplevelProtocol() const { return mToplevel
; }
177 // The following methods either directly forward to the toplevel protocol, or
178 // almost directly do.
179 int32_t Register(IProtocol
* aRouted
);
180 int32_t RegisterID(IProtocol
* aRouted
, int32_t aId
);
181 IProtocol
* Lookup(int32_t aId
);
182 void Unregister(int32_t aId
);
184 Shmem::SharedMemory
* CreateSharedMemory(size_t aSize
, bool aUnsafe
,
186 Shmem::SharedMemory
* LookupSharedMemory(int32_t aId
);
187 bool IsTrackingSharedMemory(Shmem::SharedMemory
* aSegment
);
188 bool DestroySharedMemory(Shmem
& aShmem
);
190 MessageChannel
* GetIPCChannel();
191 const MessageChannel
* GetIPCChannel() const;
193 // Get the nsISerialEventTarget which all messages sent to this actor will be
194 // processed on. Unless stated otherwise, all operations on IProtocol which
195 // don't occur on this `nsISerialEventTarget` are unsafe.
196 nsISerialEventTarget
* GetActorEventTarget();
198 // Actor lifecycle and other properties.
199 ProtocolId
GetProtocolId() const { return mProtocolId
; }
200 const char* GetProtocolName() const { return ProtocolIdToName(mProtocolId
); }
202 int32_t Id() const { return mId
; }
203 IProtocol
* Manager() const { return mManager
; }
205 ActorLifecycleProxy
* GetLifecycleProxy() { return mLifecycleProxy
; }
206 WeakActorLifecycleProxy
* GetWeakLifecycleProxy();
208 Side
GetSide() const { return mSide
; }
209 bool CanSend() const { return mLinkStatus
== LinkStatus::Connected
; }
210 bool CanRecv() const {
211 return mLinkStatus
== LinkStatus::Connected
||
212 mLinkStatus
== LinkStatus::Doomed
;
215 // Remove or deallocate a managee given its type.
216 virtual void RemoveManagee(int32_t, IProtocol
*) = 0;
217 virtual void DeallocManagee(int32_t, IProtocol
*) = 0;
219 Maybe
<IProtocol
*> ReadActor(IPC::MessageReader
* aReader
, bool aNullable
,
220 const char* aActorDescription
,
221 int32_t aProtocolTypeId
);
223 virtual Result
OnMessageReceived(const Message
& aMessage
) = 0;
224 virtual Result
OnMessageReceived(const Message
& aMessage
,
225 UniquePtr
<Message
>& aReply
) = 0;
226 virtual Result
OnCallReceived(const Message
& aMessage
,
227 UniquePtr
<Message
>& aReply
) = 0;
228 bool AllocShmem(size_t aSize
, Shmem
* aOutMem
);
229 bool AllocUnsafeShmem(size_t aSize
, Shmem
* aOutMem
);
230 bool DeallocShmem(Shmem
& aMem
);
232 void FatalError(const char* const aErrorMsg
);
233 virtual void HandleFatalError(const char* aErrorMsg
);
236 virtual ~IProtocol();
238 friend class IToplevelProtocol
;
239 friend class ActorLifecycleProxy
;
240 friend class IPDLResolverInner
;
241 friend class UntypedManagedEndpoint
;
243 void SetId(int32_t aId
);
245 // We have separate functions because the accessibility code manually
247 void SetManager(IProtocol
* aManager
);
249 // Sets the manager for the protocol and registers the protocol with
250 // its manager, setting up channels for the protocol as well. Not
251 // for use outside of IPDL.
252 void SetManagerAndRegister(IProtocol
* aManager
);
253 void SetManagerAndRegister(IProtocol
* aManager
, int32_t aId
);
255 // Helpers for calling `Send` on our underlying IPC channel.
256 bool ChannelSend(UniquePtr
<IPC::Message
> aMsg
);
257 bool ChannelSend(UniquePtr
<IPC::Message
> aMsg
,
258 UniquePtr
<IPC::Message
>* aReply
);
259 template <typename Value
>
260 void ChannelSend(UniquePtr
<IPC::Message
> aMsg
,
261 IPC::Message::msgid_t aReplyMsgId
,
262 ResolveCallback
<Value
>&& aResolve
,
263 RejectCallback
&& aReject
) {
265 GetIPCChannel()->Send(std::move(aMsg
), Id(), aReplyMsgId
,
266 std::move(aResolve
), std::move(aReject
));
268 WarnMessageDiscarded(aMsg
.get());
269 aReject(ResponseRejectReason::SendError
);
273 // Collect all actors managed by this object in an array. To make this safer
274 // to iterate, `ActorLifecycleProxy` references are returned rather than raw
276 virtual void AllManagedActors(
277 nsTArray
<RefPtr
<ActorLifecycleProxy
>>& aActors
) const = 0;
279 virtual uint32_t AllManagedActorsCount() const = 0;
281 // Internal method called when the actor becomes connected.
282 void ActorConnected();
284 // Called immediately before setting the actor state to doomed, and triggering
285 // async actor destruction. Messages may be sent from this callback, but no
287 // FIXME(nika): This is currently unused!
288 virtual void ActorDoom() {}
291 // Called when the actor has been destroyed due to an error, a __delete__
292 // message, or a __doom__ reply.
293 virtual void ActorDestroy(ActorDestroyReason aWhy
) {}
294 void DestroySubtree(ActorDestroyReason aWhy
);
296 // Called when IPC has acquired its first reference to the actor. This method
297 // may take references which will later be freed by `ActorDealloc`.
298 virtual void ActorAlloc() = 0;
300 // Called when IPC has released its final reference to the actor. It will call
301 // the dealloc method, causing the actor to be actually freed.
303 // The actor has been freed after this method returns.
304 virtual void ActorDealloc() = 0;
306 static const int32_t kNullActorId
= 0;
307 static const int32_t kFreedActorId
= 1;
311 void WarnMessageDiscarded(IPC::Message
* aMsg
);
313 void WarnMessageDiscarded(IPC::Message
*) {}
317 ProtocolId mProtocolId
;
319 LinkStatus mLinkStatus
;
320 ActorLifecycleProxy
* mLifecycleProxy
;
322 IToplevelProtocol
* mToplevel
;
325 #define IPC_OK() mozilla::ipc::IPCResult::Ok()
326 #define IPC_FAIL(actor, why) \
327 mozilla::ipc::IPCResult::Fail(WrapNotNull(actor), __func__, (why))
328 #define IPC_FAIL_NO_REASON(actor) \
329 mozilla::ipc::IPCResult::Fail(WrapNotNull(actor), __func__)
332 * IPC_FAIL_UNSAFE_PRINTF(actor, format, ...)
334 * Create a failure IPCResult with a dynamic reason-string.
336 * @note This macro causes data collection because IPC failure reasons may be
337 * sent to crash-stats, where they are publicly visible. Firefox data stewards
338 * must do data review on usages of this macro.
340 #define IPC_FAIL_UNSAFE_PRINTF(actor, format, ...) \
341 mozilla::ipc::IPCResult::FailUnsafePrintfImpl( \
342 WrapNotNull(actor), __func__, nsPrintfCString(format, ##__VA_ARGS__))
345 * All message deserializers and message handlers should return this type via
346 * the above macros. We use a less generic name here to avoid conflict with
347 * `mozilla::Result` because we have quite a few `using namespace mozilla::ipc;`
350 * Note that merely constructing a failure-result, whether directly or via the
351 * IPC_FAIL macros, causes the associated error message to be processed
356 static IPCResult
Ok() { return IPCResult(true); }
358 // IPC failure messages can sometimes end up in telemetry. As such, to avoid
359 // accidentally exfiltrating sensitive information without a data review, we
360 // require that they be constant strings.
361 template <size_t N
, size_t M
>
362 static IPCResult
Fail(NotNull
<IProtocol
*> aActor
, const char (&aWhere
)[N
],
363 const char (&aWhy
)[M
]) {
364 return FailImpl(aActor
, aWhere
, aWhy
);
367 static IPCResult
Fail(NotNull
<IProtocol
*> aActor
, const char (&aWhere
)[N
]) {
368 return FailImpl(aActor
, aWhere
, "");
371 MOZ_IMPLICIT
operator bool() const { return mSuccess
; }
373 // Only used by IPC_FAIL_UNSAFE_PRINTF (q.v.). Do not call this directly. (Or
374 // at least get data-review's approval if you do.)
376 static IPCResult
FailUnsafePrintfImpl(NotNull
<IProtocol
*> aActor
,
377 const char (&aWhere
)[N
],
378 nsPrintfCString
const& aWhy
) {
379 return FailImpl(aActor
, aWhere
, aWhy
.get());
383 static IPCResult
FailImpl(NotNull
<IProtocol
*> aActor
, const char* aWhere
,
386 explicit IPCResult(bool aResult
) : mSuccess(aResult
) {}
390 class UntypedEndpoint
;
392 template <class PFooSide
>
395 template <class PFooSide
>
396 class ManagedEndpoint
;
399 * All refcounted protocols should inherit this class.
401 class IRefCountedProtocol
: public IProtocol
{
403 NS_INLINE_DECL_PURE_VIRTUAL_REFCOUNTING
405 using IProtocol::IProtocol
;
409 * All top-level protocols should inherit this class.
411 * IToplevelProtocol tracks all top-level protocol actors created from
412 * this protocol actor.
414 class IToplevelProtocol
: public IRefCountedProtocol
{
415 template <class PFooSide
>
416 friend class Endpoint
;
419 explicit IToplevelProtocol(const char* aName
, ProtocolId aProtoId
,
421 ~IToplevelProtocol() = default;
424 // Shadow methods on IProtocol which are implemented directly on toplevel
426 int32_t Register(IProtocol
* aRouted
);
427 int32_t RegisterID(IProtocol
* aRouted
, int32_t aId
);
428 IProtocol
* Lookup(int32_t aId
);
429 void Unregister(int32_t aId
);
431 Shmem::SharedMemory
* CreateSharedMemory(size_t aSize
, bool aUnsafe
,
433 Shmem::SharedMemory
* LookupSharedMemory(int32_t aId
);
434 bool IsTrackingSharedMemory(Shmem::SharedMemory
* aSegment
);
435 bool DestroySharedMemory(Shmem
& aShmem
);
437 MessageChannel
* GetIPCChannel() { return &mChannel
; }
438 const MessageChannel
* GetIPCChannel() const { return &mChannel
; }
440 void SetOtherProcessId(base::ProcessId aOtherPid
);
442 virtual void OnChannelClose() = 0;
443 virtual void OnChannelError() = 0;
444 virtual void ProcessingError(Result aError
, const char* aMsgName
) {}
446 bool Open(ScopedPort aPort
, const nsID
& aMessageChannelId
,
447 base::ProcessId aOtherPid
,
448 nsISerialEventTarget
* aEventTarget
= nullptr);
450 bool Open(IToplevelProtocol
* aTarget
, nsISerialEventTarget
* aEventTarget
,
451 mozilla::ipc::Side aSide
= mozilla::ipc::UnknownSide
);
453 // Open a toplevel actor such that both ends of the actor's channel are on
454 // the same thread. This method should be called on the thread to perform
457 // WARNING: Attempting to send a sync or intr message on the same thread
459 bool OpenOnSameThread(IToplevelProtocol
* aTarget
,
460 mozilla::ipc::Side aSide
= mozilla::ipc::UnknownSide
);
463 * This sends a special message that is processed on the IO thread, so that
464 * other actors can know that the process will soon shutdown.
466 void NotifyImpendingShutdown();
470 void SetReplyTimeoutMs(int32_t aTimeoutMs
);
472 void DeallocShmems();
473 bool ShmemCreated(const Message
& aMsg
);
474 bool ShmemDestroyed(const Message
& aMsg
);
476 virtual bool ShouldContinueFromReplyTimeout() { return false; }
478 // WARNING: This function is called with the MessageChannel monitor held.
479 virtual void IntentionalCrash() { MOZ_CRASH("Intentional IPDL crash"); }
481 // The code here is only useful for fuzzing. It should not be used for any
484 // Returns true if we should simulate a timeout.
485 // WARNING: This is a testing-only function that is called with the
486 // MessageChannel monitor held. Don't do anything fancy here or we could
488 virtual bool ArtificialTimeout() { return false; }
490 // Returns true if we want to cause the worker thread to sleep with the
492 virtual bool NeedArtificialSleep() { return false; }
494 // This function should be implemented to sleep for some amount of time on
495 // the worker thread. Will only be called if NeedArtificialSleep() returns
497 virtual void ArtificialSleep() {}
499 bool ArtificialTimeout() { return false; }
500 bool NeedArtificialSleep() { return false; }
501 void ArtificialSleep() {}
504 bool IsOnCxxStack() const;
506 virtual void ProcessRemoteNativeEventsInInterruptCall() {}
508 virtual void OnChannelReceivedMessage(const Message
& aMsg
) {}
510 void OnIPCChannelOpened() { ActorConnected(); }
512 base::ProcessId
OtherPidMaybeInvalid() const { return mOtherPid
; }
518 using IDMap
= nsTHashMap
<nsUint32HashKey
, T
>;
520 base::ProcessId mOtherPid
;
523 // Used to be on mState
524 int32_t mLastLocalId
;
525 IDMap
<IProtocol
*> mActorMap
;
526 IDMap
<RefPtr
<Shmem::SharedMemory
>> mShmemMap
;
528 MessageChannel mChannel
;
531 class IShmemAllocator
{
533 virtual bool AllocShmem(size_t aSize
, mozilla::ipc::Shmem
* aShmem
) = 0;
534 virtual bool AllocUnsafeShmem(size_t aSize
, mozilla::ipc::Shmem
* aShmem
) = 0;
535 virtual bool DeallocShmem(mozilla::ipc::Shmem
& aShmem
) = 0;
538 #define FORWARD_SHMEM_ALLOCATOR_TO(aImplClass) \
539 virtual bool AllocShmem(size_t aSize, mozilla::ipc::Shmem* aShmem) \
541 return aImplClass::AllocShmem(aSize, aShmem); \
543 virtual bool AllocUnsafeShmem(size_t aSize, mozilla::ipc::Shmem* aShmem) \
545 return aImplClass::AllocUnsafeShmem(aSize, aShmem); \
547 virtual bool DeallocShmem(mozilla::ipc::Shmem& aShmem) override { \
548 return aImplClass::DeallocShmem(aShmem); \
551 inline bool LoggingEnabled() {
552 #if defined(DEBUG) || defined(FUZZING)
553 return !!PR_GetEnv("MOZ_IPC_MESSAGE_LOG");
559 #if defined(DEBUG) || defined(FUZZING)
560 bool LoggingEnabledFor(const char* aTopLevelProtocol
, mozilla::ipc::Side aSide
,
561 const char* aFilter
);
564 inline bool LoggingEnabledFor(const char* aTopLevelProtocol
,
565 mozilla::ipc::Side aSide
) {
566 #if defined(DEBUG) || defined(FUZZING)
567 return LoggingEnabledFor(aTopLevelProtocol
, aSide
,
568 PR_GetEnv("MOZ_IPC_MESSAGE_LOG"));
574 MOZ_NEVER_INLINE
void LogMessageForProtocol(const char* aTopLevelProtocol
,
575 base::ProcessId aOtherPid
,
576 const char* aContextDescription
,
578 MessageDirection aDirection
);
580 MOZ_NEVER_INLINE
void ProtocolErrorBreakpoint(const char* aMsg
);
582 // IPC::MessageReader and IPC::MessageWriter call this function for FatalError
583 // calls which come from serialization/deserialization.
584 MOZ_NEVER_INLINE
void PickleFatalError(const char* aMsg
, IProtocol
* aActor
);
586 // The code generator calls this function for errors which come from the
587 // methods of protocols. Doing this saves codesize by making the error
588 // cases significantly smaller.
589 MOZ_NEVER_INLINE
void FatalError(const char* aMsg
, bool aIsParent
);
591 // The code generator calls this function for errors which are not
592 // protocol-specific: errors in generated struct methods or errors in
593 // transition functions, for instance. Doing this saves codesize by
594 // by making the error cases significantly smaller.
595 MOZ_NEVER_INLINE
void LogicError(const char* aMsg
);
597 MOZ_NEVER_INLINE
void ActorIdReadError(const char* aActorDescription
);
599 MOZ_NEVER_INLINE
void BadActorIdError(const char* aActorDescription
);
601 MOZ_NEVER_INLINE
void ActorLookupError(const char* aActorDescription
);
603 MOZ_NEVER_INLINE
void MismatchedActorTypeError(const char* aActorDescription
);
605 MOZ_NEVER_INLINE
void UnionTypeReadError(const char* aUnionName
);
607 MOZ_NEVER_INLINE
void ArrayLengthReadError(const char* aElementName
);
609 MOZ_NEVER_INLINE
void SentinelReadError(const char* aElementName
);
612 * Annotate the crash reporter with the error code from the most recent system
613 * call. Returns the system error.
615 void AnnotateSystemError();
617 // The ActorLifecycleProxy is a helper type used internally by IPC to maintain a
618 // maybe-owning reference to an IProtocol object. For well-behaved actors
619 // which are not freed until after their `Dealloc` method is called, a
620 // reference to an actor's `ActorLifecycleProxy` object is an owning one, as the
621 // `Dealloc` method will only be called when all references to the
622 // `ActorLifecycleProxy` are released.
624 // Unfortunately, some actors may be destroyed before their `Dealloc` method
625 // is called. For these actors, `ActorLifecycleProxy` acts as a weak pointer,
626 // and will begin to return `nullptr` from its `Get()` method once the
627 // corresponding actor object has been destroyed.
629 // When calling a `Recv` method, IPC will hold a `ActorLifecycleProxy` reference
630 // to the target actor, meaning that well-behaved actors can behave as though a
631 // strong reference is being held.
633 // Generic IPC code MUST treat ActorLifecycleProxy references as weak
635 class ActorLifecycleProxy
{
637 NS_INLINE_DECL_REFCOUNTING_ONEVENTTARGET(ActorLifecycleProxy
)
639 IProtocol
* Get() { return mActor
; }
641 WeakActorLifecycleProxy
* GetWeakProxy();
644 friend class IProtocol
;
646 explicit ActorLifecycleProxy(IProtocol
* aActor
);
647 ~ActorLifecycleProxy();
649 ActorLifecycleProxy(const ActorLifecycleProxy
&) = delete;
650 ActorLifecycleProxy
& operator=(const ActorLifecycleProxy
&) = delete;
652 IProtocol
* MOZ_NON_OWNING_REF mActor
;
654 // Hold a reference to the actor's manager's ActorLifecycleProxy to help
655 // prevent it from dying while we're still alive!
656 RefPtr
<ActorLifecycleProxy
> mManager
;
658 // When requested, the current self-referencing weak reference for this
659 // ActorLifecycleProxy.
660 RefPtr
<WeakActorLifecycleProxy
> mWeakProxy
;
663 // Unlike ActorLifecycleProxy, WeakActorLifecycleProxy only holds a weak
664 // reference to both the proxy and the actual actor, meaning that holding this
665 // type will not attempt to keep the actor object alive.
667 // This type is safe to hold on threads other than the actor's thread, but is
668 // _NOT_ safe to access on other threads, as actors and ActorLifecycleProxy
669 // objects are not threadsafe.
670 class WeakActorLifecycleProxy final
{
672 NS_INLINE_DECL_THREADSAFE_REFCOUNTING(WeakActorLifecycleProxy
)
674 // May only be called on the actor's event target.
675 // Will return `nullptr` if the actor has already been destroyed from IPC's
677 IProtocol
* Get() const;
679 // Safe to call on any thread.
680 nsISerialEventTarget
* ActorEventTarget() const { return mActorEventTarget
; }
683 friend class ActorLifecycleProxy
;
685 explicit WeakActorLifecycleProxy(ActorLifecycleProxy
* aProxy
);
686 ~WeakActorLifecycleProxy();
688 WeakActorLifecycleProxy(const WeakActorLifecycleProxy
&) = delete;
689 WeakActorLifecycleProxy
& operator=(const WeakActorLifecycleProxy
&) = delete;
691 // This field may only be accessed on the actor's thread, and will be
692 // automatically cleared when the ActorLifecycleProxy is destroyed.
693 ActorLifecycleProxy
* MOZ_NON_OWNING_REF mProxy
;
695 // The serial event target which owns the actor, and is the only thread where
696 // it is OK to access the ActorLifecycleProxy.
697 const nsCOMPtr
<nsISerialEventTarget
> mActorEventTarget
;
700 class IPDLResolverInner final
{
702 NS_INLINE_DECL_THREADSAFE_REFCOUNTING_WITH_DESTROY(IPDLResolverInner
,
705 explicit IPDLResolverInner(UniquePtr
<IPC::Message
> aReply
, IProtocol
* aActor
);
707 template <typename F
>
708 void Resolve(F
&& aWrite
) {
709 ResolveOrReject(true, std::forward
<F
>(aWrite
));
713 void ResolveOrReject(bool aResolve
,
714 FunctionRef
<void(IPC::Message
*, IProtocol
*)> aWrite
);
717 ~IPDLResolverInner();
719 UniquePtr
<IPC::Message
> mReply
;
720 RefPtr
<WeakActorLifecycleProxy
> mWeakProxy
;
725 template <typename Protocol
>
726 class ManagedContainer
{
728 using iterator
= typename nsTArray
<Protocol
*>::const_iterator
;
730 iterator
begin() const { return mArray
.begin(); }
731 iterator
end() const { return mArray
.end(); }
732 iterator
cbegin() const { return begin(); }
733 iterator
cend() const { return end(); }
735 bool IsEmpty() const { return mArray
.IsEmpty(); }
736 uint32_t Count() const { return mArray
.Length(); }
738 void ToArray(nsTArray
<Protocol
*>& aArray
) const {
739 aArray
.AppendElements(mArray
);
742 bool EnsureRemoved(Protocol
* aElement
) {
743 return mArray
.RemoveElementSorted(aElement
);
746 void Insert(Protocol
* aElement
) {
747 // Equivalent to `InsertElementSorted`, avoiding inserting a duplicate
749 size_t index
= mArray
.IndexOfFirstElementGt(aElement
);
750 if (index
== 0 || mArray
[index
- 1] != aElement
) {
751 mArray
.InsertElementAt(index
, aElement
);
755 void Clear() { mArray
.Clear(); }
758 nsTArray
<Protocol
*> mArray
;
761 template <typename Protocol
>
762 Protocol
* LoneManagedOrNullAsserts(
763 const ManagedContainer
<Protocol
>& aManagees
) {
764 if (aManagees
.IsEmpty()) {
767 MOZ_ASSERT(aManagees
.Count() == 1);
768 return *aManagees
.cbegin();
771 template <typename Protocol
>
772 Protocol
* SingleManagedOrNull(const ManagedContainer
<Protocol
>& aManagees
) {
773 if (aManagees
.Count() != 1) {
776 return *aManagees
.cbegin();
779 } // namespace mozilla
781 #endif // mozilla_ipc_ProtocolUtils_h