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/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 "nsPrintfCString.h"
32 #include "nsTHashMap.h"
34 #include "nsISupports.h"
35 #include "nsTArrayForwardDeclare.h"
36 #include "nsTHashSet.h"
38 // XXX Things that could be moved to ProtocolUtils.cpp
39 #include "base/process_util.h" // for CloseProcessHandle
40 #include "prenv.h" // for PR_GetEnv
42 #if defined(ANDROID) && defined(DEBUG)
43 # include <android/log.h>
49 // WARNING: this takes into account the private, special-message-type
50 // enum in ipc_channel.h. They need to be kept in sync.
52 // XXX the max message ID is actually kuint32max now ... when this
53 // changed, the assumptions of the special message IDs changed in that
54 // they're not carving out messages from likely-unallocated space, but
55 // rather carving out messages from the end of space allocated to
56 // protocol 0. Oops! We can get away with this until protocol 0
57 // starts approaching its 65,536th message.
59 // Message types used by DataPipe
60 DATA_PIPE_CLOSED_MESSAGE_TYPE
= kuint16max
- 18,
61 DATA_PIPE_BYTES_CONSUMED_MESSAGE_TYPE
= kuint16max
- 17,
63 // Message types used by NodeChannel
64 ACCEPT_INVITE_MESSAGE_TYPE
= kuint16max
- 16,
65 REQUEST_INTRODUCTION_MESSAGE_TYPE
= kuint16max
- 15,
66 INTRODUCE_MESSAGE_TYPE
= kuint16max
- 14,
67 BROADCAST_MESSAGE_TYPE
= kuint16max
- 13,
68 EVENT_MESSAGE_TYPE
= kuint16max
- 12,
70 // Message types used by MessageChannel
71 MANAGED_ENDPOINT_DROPPED_MESSAGE_TYPE
= kuint16max
- 11,
72 MANAGED_ENDPOINT_BOUND_MESSAGE_TYPE
= kuint16max
- 10,
73 IMPENDING_SHUTDOWN_MESSAGE_TYPE
= kuint16max
- 9,
74 BUILD_IDS_MATCH_MESSAGE_TYPE
= kuint16max
- 8,
75 BUILD_ID_MESSAGE_TYPE
= kuint16max
- 7, // unused
76 CHANNEL_OPENED_MESSAGE_TYPE
= kuint16max
- 6,
77 SHMEM_DESTROYED_MESSAGE_TYPE
= kuint16max
- 5,
78 SHMEM_CREATED_MESSAGE_TYPE
= kuint16max
- 4,
79 GOODBYE_MESSAGE_TYPE
= kuint16max
- 3,
80 CANCEL_MESSAGE_TYPE
= kuint16max
- 2,
82 // kuint16max - 1 is used by ipc_channel.h.
89 class nsISerialEventTarget
;
104 // Scoped base::ProcessHandle to ensure base::CloseProcessHandle is called.
105 struct ScopedProcessHandleTraits
{
106 typedef base::ProcessHandle type
;
108 static type
empty() { return base::kInvalidProcessHandle
; }
110 static void release(type aProcessHandle
) {
111 if (aProcessHandle
&& aProcessHandle
!= base::kInvalidProcessHandle
) {
112 base::CloseProcessHandle(aProcessHandle
);
116 typedef mozilla::Scoped
<ScopedProcessHandleTraits
> ScopedProcessHandle
;
118 class ProtocolFdMapping
;
119 class ProtocolCloneContext
;
121 // Used to pass references to protocol actors across the wire.
122 // Actors created on the parent-side have a positive ID, and actors
123 // allocated on the child side have a negative ID.
128 // What happens if Interrupt calls race?
129 enum RacyInterruptPolicy
{ RIPError
, RIPChildWins
, RIPParentWins
};
131 enum class LinkStatus
: uint8_t {
132 // The actor has not established a link yet, or the actor is no longer in use
133 // by IPC, and its 'Dealloc' method has been called or is being called.
135 // NOTE: This state is used instead of an explicit `Freed` state when IPC no
136 // longer holds references to the current actor as we currently re-open
137 // existing actors. Once we fix these poorly behaved actors, this loopback
138 // state can be split to have the final state not be the same as the initial
142 // A live link is connected to the other side of this actor.
145 // The link has begun being destroyed. Messages may still be received, but
146 // cannot be sent. (exception: sync/intr replies may be sent while Doomed).
149 // The link has been destroyed, and messages will no longer be sent or
154 typedef IPCMessageStart ProtocolId
;
156 // Generated by IPDL compiler
157 const char* ProtocolIdToName(IPCMessageStart aId
);
159 class IToplevelProtocol
;
160 class ActorLifecycleProxy
;
161 class WeakActorLifecycleProxy
;
162 class IPDLResolverInner
;
163 class UntypedManagedEndpoint
;
165 class IProtocol
: public HasResultCodes
{
167 enum ActorDestroyReason
{
173 ManagedEndpointDropped
176 typedef base::ProcessId ProcessId
;
177 typedef IPC::Message Message
;
179 IProtocol(ProtocolId aProtoId
, Side aSide
)
181 mProtocolId(aProtoId
),
183 mLinkStatus(LinkStatus::Inactive
),
184 mLifecycleProxy(nullptr),
186 mToplevel(nullptr) {}
188 IToplevelProtocol
* ToplevelProtocol() { return mToplevel
; }
189 const IToplevelProtocol
* ToplevelProtocol() const { return mToplevel
; }
191 // The following methods either directly forward to the toplevel protocol, or
192 // almost directly do.
193 int32_t Register(IProtocol
* aRouted
);
194 int32_t RegisterID(IProtocol
* aRouted
, int32_t aId
);
195 IProtocol
* Lookup(int32_t aId
);
196 void Unregister(int32_t aId
);
198 Shmem::SharedMemory
* CreateSharedMemory(size_t aSize
, bool aUnsafe
,
200 Shmem::SharedMemory
* LookupSharedMemory(int32_t aId
);
201 bool IsTrackingSharedMemory(Shmem::SharedMemory
* aSegment
);
202 bool DestroySharedMemory(Shmem
& aShmem
);
204 MessageChannel
* GetIPCChannel();
205 const MessageChannel
* GetIPCChannel() const;
207 // Get the nsISerialEventTarget which all messages sent to this actor will be
208 // processed on. Unless stated otherwise, all operations on IProtocol which
209 // don't occur on this `nsISerialEventTarget` are unsafe.
210 nsISerialEventTarget
* GetActorEventTarget();
212 // Actor lifecycle and other properties.
213 ProtocolId
GetProtocolId() const { return mProtocolId
; }
214 const char* GetProtocolName() const { return ProtocolIdToName(mProtocolId
); }
216 int32_t Id() const { return mId
; }
217 IProtocol
* Manager() const { return mManager
; }
219 ActorLifecycleProxy
* GetLifecycleProxy() { return mLifecycleProxy
; }
220 WeakActorLifecycleProxy
* GetWeakLifecycleProxy();
222 Side
GetSide() const { return mSide
; }
223 bool CanSend() const { return mLinkStatus
== LinkStatus::Connected
; }
224 bool CanRecv() const {
225 return mLinkStatus
== LinkStatus::Connected
||
226 mLinkStatus
== LinkStatus::Doomed
;
229 // Remove or deallocate a managee given its type.
230 virtual void RemoveManagee(int32_t, IProtocol
*) = 0;
231 virtual void DeallocManagee(int32_t, IProtocol
*) = 0;
233 Maybe
<IProtocol
*> ReadActor(IPC::MessageReader
* aReader
, bool aNullable
,
234 const char* aActorDescription
,
235 int32_t aProtocolTypeId
);
237 virtual Result
OnMessageReceived(const Message
& aMessage
) = 0;
238 virtual Result
OnMessageReceived(const Message
& aMessage
,
239 UniquePtr
<Message
>& aReply
) = 0;
240 virtual Result
OnCallReceived(const Message
& aMessage
,
241 UniquePtr
<Message
>& aReply
) = 0;
242 bool AllocShmem(size_t aSize
, Shmem
* aOutMem
);
243 bool AllocUnsafeShmem(size_t aSize
, Shmem
* aOutMem
);
244 bool DeallocShmem(Shmem
& aMem
);
246 void FatalError(const char* const aErrorMsg
);
247 virtual void HandleFatalError(const char* aErrorMsg
);
250 virtual ~IProtocol();
252 friend class IToplevelProtocol
;
253 friend class ActorLifecycleProxy
;
254 friend class IPDLResolverInner
;
255 friend class UntypedManagedEndpoint
;
257 void SetId(int32_t aId
);
259 // We have separate functions because the accessibility code manually
261 void SetManager(IProtocol
* aManager
);
263 // Sets the manager for the protocol and registers the protocol with
264 // its manager, setting up channels for the protocol as well. Not
265 // for use outside of IPDL.
266 void SetManagerAndRegister(IProtocol
* aManager
);
267 void SetManagerAndRegister(IProtocol
* aManager
, int32_t aId
);
269 // Helpers for calling `Send` on our underlying IPC channel.
270 bool ChannelSend(UniquePtr
<IPC::Message
> aMsg
);
271 bool ChannelSend(UniquePtr
<IPC::Message
> aMsg
,
272 UniquePtr
<IPC::Message
>* aReply
);
273 template <typename Value
>
274 void ChannelSend(UniquePtr
<IPC::Message
> aMsg
,
275 IPC::Message::msgid_t aReplyMsgId
,
276 ResolveCallback
<Value
>&& aResolve
,
277 RejectCallback
&& aReject
) {
279 GetIPCChannel()->Send(std::move(aMsg
), Id(), aReplyMsgId
,
280 std::move(aResolve
), std::move(aReject
));
282 WarnMessageDiscarded(aMsg
.get());
283 aReject(ResponseRejectReason::SendError
);
287 // Collect all actors managed by this object in an array. To make this safer
288 // to iterate, `ActorLifecycleProxy` references are returned rather than raw
290 virtual void AllManagedActors(
291 nsTArray
<RefPtr
<ActorLifecycleProxy
>>& aActors
) const = 0;
293 // Internal method called when the actor becomes connected.
294 void ActorConnected();
296 // Called immediately before setting the actor state to doomed, and triggering
297 // async actor destruction. Messages may be sent from this callback, but no
299 // FIXME(nika): This is currently unused!
300 virtual void ActorDoom() {}
303 // Called when the actor has been destroyed due to an error, a __delete__
304 // message, or a __doom__ reply.
305 virtual void ActorDestroy(ActorDestroyReason aWhy
) {}
306 void DestroySubtree(ActorDestroyReason aWhy
);
308 // Called when IPC has acquired its first reference to the actor. This method
309 // may take references which will later be freed by `ActorDealloc`.
310 virtual void ActorAlloc() {}
312 // Called when IPC has released its final reference to the actor. It will call
313 // the dealloc method, causing the actor to be actually freed.
315 // The actor has been freed after this method returns.
316 virtual void ActorDealloc() {
318 Manager()->DeallocManagee(mProtocolId
, this);
322 static const int32_t kNullActorId
= 0;
323 static const int32_t kFreedActorId
= 1;
327 void WarnMessageDiscarded(IPC::Message
* aMsg
);
329 void WarnMessageDiscarded(IPC::Message
*) {}
333 ProtocolId mProtocolId
;
335 LinkStatus mLinkStatus
;
336 ActorLifecycleProxy
* mLifecycleProxy
;
338 IToplevelProtocol
* mToplevel
;
341 #define IPC_OK() mozilla::ipc::IPCResult::Ok()
342 #define IPC_FAIL(actor, why) \
343 mozilla::ipc::IPCResult::Fail(WrapNotNull(actor), __func__, (why))
344 #define IPC_FAIL_NO_REASON(actor) \
345 mozilla::ipc::IPCResult::Fail(WrapNotNull(actor), __func__)
348 * IPC_FAIL_UNSAFE_PRINTF(actor, format, ...)
350 * Create a failure IPCResult with a dynamic reason-string.
352 * @note This macro causes data collection because IPC failure reasons may be
353 * sent to crash-stats, where they are publicly visible. Firefox data stewards
354 * must do data review on usages of this macro.
356 #define IPC_FAIL_UNSAFE_PRINTF(actor, format, ...) \
357 mozilla::ipc::IPCResult::FailUnsafePrintfImpl( \
358 WrapNotNull(actor), __func__, nsPrintfCString(format, ##__VA_ARGS__))
361 * All message deserializers and message handlers should return this type via
362 * the above macros. We use a less generic name here to avoid conflict with
363 * `mozilla::Result` because we have quite a few `using namespace mozilla::ipc;`
366 * Note that merely constructing a failure-result, whether directly or via the
367 * IPC_FAIL macros, causes the associated error message to be processed
372 static IPCResult
Ok() { return IPCResult(true); }
374 // IPC failure messages can sometimes end up in telemetry. As such, to avoid
375 // accidentally exfiltrating sensitive information without a data review, we
376 // require that they be constant strings.
377 template <size_t N
, size_t M
>
378 static IPCResult
Fail(NotNull
<IProtocol
*> aActor
, const char (&aWhere
)[N
],
379 const char (&aWhy
)[M
]) {
380 return FailImpl(aActor
, aWhere
, aWhy
);
383 static IPCResult
Fail(NotNull
<IProtocol
*> aActor
, const char (&aWhere
)[N
]) {
384 return FailImpl(aActor
, aWhere
, "");
387 MOZ_IMPLICIT
operator bool() const { return mSuccess
; }
389 // Only used by IPC_FAIL_UNSAFE_PRINTF (q.v.). Do not call this directly. (Or
390 // at least get data-review's approval if you do.)
392 static IPCResult
FailUnsafePrintfImpl(NotNull
<IProtocol
*> aActor
,
393 const char (&aWhere
)[N
],
394 nsPrintfCString
const& aWhy
) {
395 return FailImpl(aActor
, aWhere
, aWhy
.get());
399 static IPCResult
FailImpl(NotNull
<IProtocol
*> aActor
, const char* aWhere
,
402 explicit IPCResult(bool aResult
) : mSuccess(aResult
) {}
406 class UntypedEndpoint
;
408 template <class PFooSide
>
411 template <class PFooSide
>
412 class ManagedEndpoint
;
415 * All top-level protocols should inherit this class.
417 * IToplevelProtocol tracks all top-level protocol actors created from
418 * this protocol actor.
420 class IToplevelProtocol
: public IProtocol
{
421 template <class PFooSide
>
422 friend class Endpoint
;
425 explicit IToplevelProtocol(const char* aName
, ProtocolId aProtoId
,
427 ~IToplevelProtocol() = default;
430 // All top-level protocols are refcounted.
431 NS_INLINE_DECL_PURE_VIRTUAL_REFCOUNTING
433 // Shadow methods on IProtocol which are implemented directly on toplevel
435 int32_t Register(IProtocol
* aRouted
);
436 int32_t RegisterID(IProtocol
* aRouted
, int32_t aId
);
437 IProtocol
* Lookup(int32_t aId
);
438 void Unregister(int32_t aId
);
440 Shmem::SharedMemory
* CreateSharedMemory(size_t aSize
, bool aUnsafe
,
442 Shmem::SharedMemory
* LookupSharedMemory(int32_t aId
);
443 bool IsTrackingSharedMemory(Shmem::SharedMemory
* aSegment
);
444 bool DestroySharedMemory(Shmem
& aShmem
);
446 MessageChannel
* GetIPCChannel() { return &mChannel
; }
447 const MessageChannel
* GetIPCChannel() const { return &mChannel
; }
449 void SetOtherProcessId(base::ProcessId aOtherPid
);
451 virtual void OnChannelClose() = 0;
452 virtual void OnChannelError() = 0;
453 virtual void ProcessingError(Result aError
, const char* aMsgName
) {}
455 bool Open(ScopedPort aPort
, const nsID
& aMessageChannelId
,
456 base::ProcessId aOtherPid
,
457 nsISerialEventTarget
* aEventTarget
= nullptr);
459 bool Open(IToplevelProtocol
* aTarget
, nsISerialEventTarget
* aEventTarget
,
460 mozilla::ipc::Side aSide
= mozilla::ipc::UnknownSide
);
462 // Open a toplevel actor such that both ends of the actor's channel are on
463 // the same thread. This method should be called on the thread to perform
466 // WARNING: Attempting to send a sync or intr message on the same thread
468 bool OpenOnSameThread(IToplevelProtocol
* aTarget
,
469 mozilla::ipc::Side aSide
= mozilla::ipc::UnknownSide
);
472 * This sends a special message that is processed on the IO thread, so that
473 * other actors can know that the process will soon shutdown.
475 void NotifyImpendingShutdown();
479 void SetReplyTimeoutMs(int32_t aTimeoutMs
);
481 void DeallocShmems();
482 bool ShmemCreated(const Message
& aMsg
);
483 bool ShmemDestroyed(const Message
& aMsg
);
485 virtual bool ShouldContinueFromReplyTimeout() { return false; }
487 // WARNING: This function is called with the MessageChannel monitor held.
488 virtual void IntentionalCrash() { MOZ_CRASH("Intentional IPDL crash"); }
490 // The code here is only useful for fuzzing. It should not be used for any
493 // Returns true if we should simulate a timeout.
494 // WARNING: This is a testing-only function that is called with the
495 // MessageChannel monitor held. Don't do anything fancy here or we could
497 virtual bool ArtificialTimeout() { return false; }
499 // Returns true if we want to cause the worker thread to sleep with the
501 virtual bool NeedArtificialSleep() { return false; }
503 // This function should be implemented to sleep for some amount of time on
504 // the worker thread. Will only be called if NeedArtificialSleep() returns
506 virtual void ArtificialSleep() {}
508 bool ArtificialTimeout() { return false; }
509 bool NeedArtificialSleep() { return false; }
510 void ArtificialSleep() {}
513 bool IsOnCxxStack() const;
515 virtual void ProcessRemoteNativeEventsInInterruptCall() {}
517 virtual void OnChannelReceivedMessage(const Message
& aMsg
) {}
519 void OnIPCChannelOpened() { ActorConnected(); }
521 base::ProcessId
OtherPidMaybeInvalid() const { return mOtherPid
; }
527 using IDMap
= nsTHashMap
<nsUint32HashKey
, T
>;
529 base::ProcessId mOtherPid
;
532 // Used to be on mState
533 int32_t mLastLocalId
;
534 IDMap
<IProtocol
*> mActorMap
;
535 IDMap
<Shmem::SharedMemory
*> mShmemMap
;
537 MessageChannel mChannel
;
540 class IShmemAllocator
{
542 virtual bool AllocShmem(size_t aSize
, mozilla::ipc::Shmem
* aShmem
) = 0;
543 virtual bool AllocUnsafeShmem(size_t aSize
, mozilla::ipc::Shmem
* aShmem
) = 0;
544 virtual bool DeallocShmem(mozilla::ipc::Shmem
& aShmem
) = 0;
547 #define FORWARD_SHMEM_ALLOCATOR_TO(aImplClass) \
548 virtual bool AllocShmem(size_t aSize, mozilla::ipc::Shmem* aShmem) \
550 return aImplClass::AllocShmem(aSize, aShmem); \
552 virtual bool AllocUnsafeShmem(size_t aSize, mozilla::ipc::Shmem* aShmem) \
554 return aImplClass::AllocUnsafeShmem(aSize, aShmem); \
556 virtual bool DeallocShmem(mozilla::ipc::Shmem& aShmem) override { \
557 return aImplClass::DeallocShmem(aShmem); \
560 inline bool LoggingEnabled() {
561 #if defined(DEBUG) || defined(FUZZING)
562 return !!PR_GetEnv("MOZ_IPC_MESSAGE_LOG");
568 #if defined(DEBUG) || defined(FUZZING)
569 bool LoggingEnabledFor(const char* aTopLevelProtocol
, mozilla::ipc::Side aSide
,
570 const char* aFilter
);
573 inline bool LoggingEnabledFor(const char* aTopLevelProtocol
,
574 mozilla::ipc::Side aSide
) {
575 #if defined(DEBUG) || defined(FUZZING)
576 return LoggingEnabledFor(aTopLevelProtocol
, aSide
,
577 PR_GetEnv("MOZ_IPC_MESSAGE_LOG"));
583 MOZ_NEVER_INLINE
void LogMessageForProtocol(const char* aTopLevelProtocol
,
584 base::ProcessId aOtherPid
,
585 const char* aContextDescription
,
587 MessageDirection aDirection
);
589 MOZ_NEVER_INLINE
void ProtocolErrorBreakpoint(const char* aMsg
);
591 // IPC::MessageReader and IPC::MessageWriter call this function for FatalError
592 // calls which come from serialization/deserialization.
593 MOZ_NEVER_INLINE
void PickleFatalError(const char* aMsg
, IProtocol
* aActor
);
595 // The code generator calls this function for errors which come from the
596 // methods of protocols. Doing this saves codesize by making the error
597 // cases significantly smaller.
598 MOZ_NEVER_INLINE
void FatalError(const char* aMsg
, bool aIsParent
);
600 // The code generator calls this function for errors which are not
601 // protocol-specific: errors in generated struct methods or errors in
602 // transition functions, for instance. Doing this saves codesize by
603 // by making the error cases significantly smaller.
604 MOZ_NEVER_INLINE
void LogicError(const char* aMsg
);
606 MOZ_NEVER_INLINE
void ActorIdReadError(const char* aActorDescription
);
608 MOZ_NEVER_INLINE
void BadActorIdError(const char* aActorDescription
);
610 MOZ_NEVER_INLINE
void ActorLookupError(const char* aActorDescription
);
612 MOZ_NEVER_INLINE
void MismatchedActorTypeError(const char* aActorDescription
);
614 MOZ_NEVER_INLINE
void UnionTypeReadError(const char* aUnionName
);
616 MOZ_NEVER_INLINE
void ArrayLengthReadError(const char* aElementName
);
618 MOZ_NEVER_INLINE
void SentinelReadError(const char* aElementName
);
621 * Annotate the crash reporter with the error code from the most recent system
622 * call. Returns the system error.
624 void AnnotateSystemError();
626 // The ActorLifecycleProxy is a helper type used internally by IPC to maintain a
627 // maybe-owning reference to an IProtocol object. For well-behaved actors
628 // which are not freed until after their `Dealloc` method is called, a
629 // reference to an actor's `ActorLifecycleProxy` object is an owning one, as the
630 // `Dealloc` method will only be called when all references to the
631 // `ActorLifecycleProxy` are released.
633 // Unfortunately, some actors may be destroyed before their `Dealloc` method
634 // is called. For these actors, `ActorLifecycleProxy` acts as a weak pointer,
635 // and will begin to return `nullptr` from its `Get()` method once the
636 // corresponding actor object has been destroyed.
638 // When calling a `Recv` method, IPC will hold a `ActorLifecycleProxy` reference
639 // to the target actor, meaning that well-behaved actors can behave as though a
640 // strong reference is being held.
642 // Generic IPC code MUST treat ActorLifecycleProxy references as weak
644 class ActorLifecycleProxy
{
646 NS_INLINE_DECL_REFCOUNTING_ONEVENTTARGET(ActorLifecycleProxy
)
648 IProtocol
* Get() { return mActor
; }
650 WeakActorLifecycleProxy
* GetWeakProxy();
653 friend class IProtocol
;
655 explicit ActorLifecycleProxy(IProtocol
* aActor
);
656 ~ActorLifecycleProxy();
658 ActorLifecycleProxy(const ActorLifecycleProxy
&) = delete;
659 ActorLifecycleProxy
& operator=(const ActorLifecycleProxy
&) = delete;
661 IProtocol
* MOZ_NON_OWNING_REF mActor
;
663 // Hold a reference to the actor's manager's ActorLifecycleProxy to help
664 // prevent it from dying while we're still alive!
665 RefPtr
<ActorLifecycleProxy
> mManager
;
667 // When requested, the current self-referencing weak reference for this
668 // ActorLifecycleProxy.
669 RefPtr
<WeakActorLifecycleProxy
> mWeakProxy
;
672 // Unlike ActorLifecycleProxy, WeakActorLifecycleProxy only holds a weak
673 // reference to both the proxy and the actual actor, meaning that holding this
674 // type will not attempt to keep the actor object alive.
676 // This type is safe to hold on threads other than the actor's thread, but is
677 // _NOT_ safe to access on other threads, as actors and ActorLifecycleProxy
678 // objects are not threadsafe.
679 class WeakActorLifecycleProxy final
{
681 NS_INLINE_DECL_THREADSAFE_REFCOUNTING(WeakActorLifecycleProxy
)
683 // May only be called on the actor's event target.
684 // Will return `nullptr` if the actor has already been destroyed from IPC's
686 IProtocol
* Get() const;
688 // Safe to call on any thread.
689 nsISerialEventTarget
* ActorEventTarget() const { return mActorEventTarget
; }
692 friend class ActorLifecycleProxy
;
694 explicit WeakActorLifecycleProxy(ActorLifecycleProxy
* aProxy
);
695 ~WeakActorLifecycleProxy();
697 WeakActorLifecycleProxy(const WeakActorLifecycleProxy
&) = delete;
698 WeakActorLifecycleProxy
& operator=(const WeakActorLifecycleProxy
&) = delete;
700 // This field may only be accessed on the actor's thread, and will be
701 // automatically cleared when the ActorLifecycleProxy is destroyed.
702 ActorLifecycleProxy
* MOZ_NON_OWNING_REF mProxy
;
704 // The serial event target which owns the actor, and is the only thread where
705 // it is OK to access the ActorLifecycleProxy.
706 const nsCOMPtr
<nsISerialEventTarget
> mActorEventTarget
;
709 class IPDLResolverInner final
{
711 NS_INLINE_DECL_THREADSAFE_REFCOUNTING_WITH_DESTROY(IPDLResolverInner
,
714 explicit IPDLResolverInner(UniquePtr
<IPC::Message
> aReply
, IProtocol
* aActor
);
716 template <typename F
>
717 void Resolve(F
&& aWrite
) {
718 ResolveOrReject(true, aWrite
);
722 void ResolveOrReject(bool aResolve
,
723 FunctionRef
<void(IPC::Message
*, IProtocol
*)> aWrite
);
726 ~IPDLResolverInner();
728 UniquePtr
<IPC::Message
> mReply
;
729 RefPtr
<WeakActorLifecycleProxy
> mWeakProxy
;
734 template <typename Protocol
>
735 class ManagedContainer
{
737 using iterator
= typename nsTArray
<Protocol
*>::const_iterator
;
739 iterator
begin() const { return mArray
.begin(); }
740 iterator
end() const { return mArray
.end(); }
741 iterator
cbegin() const { return begin(); }
742 iterator
cend() const { return end(); }
744 bool IsEmpty() const { return mArray
.IsEmpty(); }
745 uint32_t Count() const { return mArray
.Length(); }
747 void ToArray(nsTArray
<Protocol
*>& aArray
) const {
748 aArray
.AppendElements(mArray
);
751 bool EnsureRemoved(Protocol
* aElement
) {
752 return mArray
.RemoveElementSorted(aElement
);
755 void Insert(Protocol
* aElement
) {
756 // Equivalent to `InsertElementSorted`, avoiding inserting a duplicate
758 size_t index
= mArray
.IndexOfFirstElementGt(aElement
);
759 if (index
== 0 || mArray
[index
- 1] != aElement
) {
760 mArray
.InsertElementAt(index
, aElement
);
764 void Clear() { mArray
.Clear(); }
767 nsTArray
<Protocol
*> mArray
;
770 template <typename Protocol
>
771 Protocol
* LoneManagedOrNullAsserts(
772 const ManagedContainer
<Protocol
>& aManagees
) {
773 if (aManagees
.IsEmpty()) {
776 MOZ_ASSERT(aManagees
.Count() == 1);
777 return *aManagees
.cbegin();
780 template <typename Protocol
>
781 Protocol
* SingleManagedOrNull(const ManagedContainer
<Protocol
>& aManagees
) {
782 if (aManagees
.Count() != 1) {
785 return *aManagees
.cbegin();
788 } // namespace mozilla
790 #endif // mozilla_ipc_ProtocolUtils_h