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 virtual uint32_t AllManagedActorsCount() const = 0;
295 // Internal method called when the actor becomes connected.
296 void ActorConnected();
298 // Called immediately before setting the actor state to doomed, and triggering
299 // async actor destruction. Messages may be sent from this callback, but no
301 // FIXME(nika): This is currently unused!
302 virtual void ActorDoom() {}
305 // Called when the actor has been destroyed due to an error, a __delete__
306 // message, or a __doom__ reply.
307 virtual void ActorDestroy(ActorDestroyReason aWhy
) {}
308 void DestroySubtree(ActorDestroyReason aWhy
);
310 // Called when IPC has acquired its first reference to the actor. This method
311 // may take references which will later be freed by `ActorDealloc`.
312 virtual void ActorAlloc() {}
314 // Called when IPC has released its final reference to the actor. It will call
315 // the dealloc method, causing the actor to be actually freed.
317 // The actor has been freed after this method returns.
318 virtual void ActorDealloc() {
320 Manager()->DeallocManagee(mProtocolId
, this);
324 static const int32_t kNullActorId
= 0;
325 static const int32_t kFreedActorId
= 1;
329 void WarnMessageDiscarded(IPC::Message
* aMsg
);
331 void WarnMessageDiscarded(IPC::Message
*) {}
335 ProtocolId mProtocolId
;
337 LinkStatus mLinkStatus
;
338 ActorLifecycleProxy
* mLifecycleProxy
;
340 IToplevelProtocol
* mToplevel
;
343 #define IPC_OK() mozilla::ipc::IPCResult::Ok()
344 #define IPC_FAIL(actor, why) \
345 mozilla::ipc::IPCResult::Fail(WrapNotNull(actor), __func__, (why))
346 #define IPC_FAIL_NO_REASON(actor) \
347 mozilla::ipc::IPCResult::Fail(WrapNotNull(actor), __func__)
350 * IPC_FAIL_UNSAFE_PRINTF(actor, format, ...)
352 * Create a failure IPCResult with a dynamic reason-string.
354 * @note This macro causes data collection because IPC failure reasons may be
355 * sent to crash-stats, where they are publicly visible. Firefox data stewards
356 * must do data review on usages of this macro.
358 #define IPC_FAIL_UNSAFE_PRINTF(actor, format, ...) \
359 mozilla::ipc::IPCResult::FailUnsafePrintfImpl( \
360 WrapNotNull(actor), __func__, nsPrintfCString(format, ##__VA_ARGS__))
363 * All message deserializers and message handlers should return this type via
364 * the above macros. We use a less generic name here to avoid conflict with
365 * `mozilla::Result` because we have quite a few `using namespace mozilla::ipc;`
368 * Note that merely constructing a failure-result, whether directly or via the
369 * IPC_FAIL macros, causes the associated error message to be processed
374 static IPCResult
Ok() { return IPCResult(true); }
376 // IPC failure messages can sometimes end up in telemetry. As such, to avoid
377 // accidentally exfiltrating sensitive information without a data review, we
378 // require that they be constant strings.
379 template <size_t N
, size_t M
>
380 static IPCResult
Fail(NotNull
<IProtocol
*> aActor
, const char (&aWhere
)[N
],
381 const char (&aWhy
)[M
]) {
382 return FailImpl(aActor
, aWhere
, aWhy
);
385 static IPCResult
Fail(NotNull
<IProtocol
*> aActor
, const char (&aWhere
)[N
]) {
386 return FailImpl(aActor
, aWhere
, "");
389 MOZ_IMPLICIT
operator bool() const { return mSuccess
; }
391 // Only used by IPC_FAIL_UNSAFE_PRINTF (q.v.). Do not call this directly. (Or
392 // at least get data-review's approval if you do.)
394 static IPCResult
FailUnsafePrintfImpl(NotNull
<IProtocol
*> aActor
,
395 const char (&aWhere
)[N
],
396 nsPrintfCString
const& aWhy
) {
397 return FailImpl(aActor
, aWhere
, aWhy
.get());
401 static IPCResult
FailImpl(NotNull
<IProtocol
*> aActor
, const char* aWhere
,
404 explicit IPCResult(bool aResult
) : mSuccess(aResult
) {}
408 class UntypedEndpoint
;
410 template <class PFooSide
>
413 template <class PFooSide
>
414 class ManagedEndpoint
;
417 * All top-level protocols should inherit this class.
419 * IToplevelProtocol tracks all top-level protocol actors created from
420 * this protocol actor.
422 class IToplevelProtocol
: public IProtocol
{
423 template <class PFooSide
>
424 friend class Endpoint
;
427 explicit IToplevelProtocol(const char* aName
, ProtocolId aProtoId
,
429 ~IToplevelProtocol() = default;
432 // All top-level protocols are refcounted.
433 NS_INLINE_DECL_PURE_VIRTUAL_REFCOUNTING
435 // Shadow methods on IProtocol which are implemented directly on toplevel
437 int32_t Register(IProtocol
* aRouted
);
438 int32_t RegisterID(IProtocol
* aRouted
, int32_t aId
);
439 IProtocol
* Lookup(int32_t aId
);
440 void Unregister(int32_t aId
);
442 Shmem::SharedMemory
* CreateSharedMemory(size_t aSize
, bool aUnsafe
,
444 Shmem::SharedMemory
* LookupSharedMemory(int32_t aId
);
445 bool IsTrackingSharedMemory(Shmem::SharedMemory
* aSegment
);
446 bool DestroySharedMemory(Shmem
& aShmem
);
448 MessageChannel
* GetIPCChannel() { return &mChannel
; }
449 const MessageChannel
* GetIPCChannel() const { return &mChannel
; }
451 void SetOtherProcessId(base::ProcessId aOtherPid
);
453 virtual void OnChannelClose() = 0;
454 virtual void OnChannelError() = 0;
455 virtual void ProcessingError(Result aError
, const char* aMsgName
) {}
457 bool Open(ScopedPort aPort
, const nsID
& aMessageChannelId
,
458 base::ProcessId aOtherPid
,
459 nsISerialEventTarget
* aEventTarget
= nullptr);
461 bool Open(IToplevelProtocol
* aTarget
, nsISerialEventTarget
* aEventTarget
,
462 mozilla::ipc::Side aSide
= mozilla::ipc::UnknownSide
);
464 // Open a toplevel actor such that both ends of the actor's channel are on
465 // the same thread. This method should be called on the thread to perform
468 // WARNING: Attempting to send a sync or intr message on the same thread
470 bool OpenOnSameThread(IToplevelProtocol
* aTarget
,
471 mozilla::ipc::Side aSide
= mozilla::ipc::UnknownSide
);
474 * This sends a special message that is processed on the IO thread, so that
475 * other actors can know that the process will soon shutdown.
477 void NotifyImpendingShutdown();
481 void SetReplyTimeoutMs(int32_t aTimeoutMs
);
483 void DeallocShmems();
484 bool ShmemCreated(const Message
& aMsg
);
485 bool ShmemDestroyed(const Message
& aMsg
);
487 virtual bool ShouldContinueFromReplyTimeout() { return false; }
489 // WARNING: This function is called with the MessageChannel monitor held.
490 virtual void IntentionalCrash() { MOZ_CRASH("Intentional IPDL crash"); }
492 // The code here is only useful for fuzzing. It should not be used for any
495 // Returns true if we should simulate a timeout.
496 // WARNING: This is a testing-only function that is called with the
497 // MessageChannel monitor held. Don't do anything fancy here or we could
499 virtual bool ArtificialTimeout() { return false; }
501 // Returns true if we want to cause the worker thread to sleep with the
503 virtual bool NeedArtificialSleep() { return false; }
505 // This function should be implemented to sleep for some amount of time on
506 // the worker thread. Will only be called if NeedArtificialSleep() returns
508 virtual void ArtificialSleep() {}
510 bool ArtificialTimeout() { return false; }
511 bool NeedArtificialSleep() { return false; }
512 void ArtificialSleep() {}
515 bool IsOnCxxStack() const;
517 virtual void ProcessRemoteNativeEventsInInterruptCall() {}
519 virtual void OnChannelReceivedMessage(const Message
& aMsg
) {}
521 void OnIPCChannelOpened() { ActorConnected(); }
523 base::ProcessId
OtherPidMaybeInvalid() const { return mOtherPid
; }
529 using IDMap
= nsTHashMap
<nsUint32HashKey
, T
>;
531 base::ProcessId mOtherPid
;
534 // Used to be on mState
535 int32_t mLastLocalId
;
536 IDMap
<IProtocol
*> mActorMap
;
537 IDMap
<Shmem::SharedMemory
*> mShmemMap
;
539 MessageChannel mChannel
;
542 class IShmemAllocator
{
544 virtual bool AllocShmem(size_t aSize
, mozilla::ipc::Shmem
* aShmem
) = 0;
545 virtual bool AllocUnsafeShmem(size_t aSize
, mozilla::ipc::Shmem
* aShmem
) = 0;
546 virtual bool DeallocShmem(mozilla::ipc::Shmem
& aShmem
) = 0;
549 #define FORWARD_SHMEM_ALLOCATOR_TO(aImplClass) \
550 virtual bool AllocShmem(size_t aSize, mozilla::ipc::Shmem* aShmem) \
552 return aImplClass::AllocShmem(aSize, aShmem); \
554 virtual bool AllocUnsafeShmem(size_t aSize, mozilla::ipc::Shmem* aShmem) \
556 return aImplClass::AllocUnsafeShmem(aSize, aShmem); \
558 virtual bool DeallocShmem(mozilla::ipc::Shmem& aShmem) override { \
559 return aImplClass::DeallocShmem(aShmem); \
562 inline bool LoggingEnabled() {
563 #if defined(DEBUG) || defined(FUZZING)
564 return !!PR_GetEnv("MOZ_IPC_MESSAGE_LOG");
570 #if defined(DEBUG) || defined(FUZZING)
571 bool LoggingEnabledFor(const char* aTopLevelProtocol
, mozilla::ipc::Side aSide
,
572 const char* aFilter
);
575 inline bool LoggingEnabledFor(const char* aTopLevelProtocol
,
576 mozilla::ipc::Side aSide
) {
577 #if defined(DEBUG) || defined(FUZZING)
578 return LoggingEnabledFor(aTopLevelProtocol
, aSide
,
579 PR_GetEnv("MOZ_IPC_MESSAGE_LOG"));
585 MOZ_NEVER_INLINE
void LogMessageForProtocol(const char* aTopLevelProtocol
,
586 base::ProcessId aOtherPid
,
587 const char* aContextDescription
,
589 MessageDirection aDirection
);
591 MOZ_NEVER_INLINE
void ProtocolErrorBreakpoint(const char* aMsg
);
593 // IPC::MessageReader and IPC::MessageWriter call this function for FatalError
594 // calls which come from serialization/deserialization.
595 MOZ_NEVER_INLINE
void PickleFatalError(const char* aMsg
, IProtocol
* aActor
);
597 // The code generator calls this function for errors which come from the
598 // methods of protocols. Doing this saves codesize by making the error
599 // cases significantly smaller.
600 MOZ_NEVER_INLINE
void FatalError(const char* aMsg
, bool aIsParent
);
602 // The code generator calls this function for errors which are not
603 // protocol-specific: errors in generated struct methods or errors in
604 // transition functions, for instance. Doing this saves codesize by
605 // by making the error cases significantly smaller.
606 MOZ_NEVER_INLINE
void LogicError(const char* aMsg
);
608 MOZ_NEVER_INLINE
void ActorIdReadError(const char* aActorDescription
);
610 MOZ_NEVER_INLINE
void BadActorIdError(const char* aActorDescription
);
612 MOZ_NEVER_INLINE
void ActorLookupError(const char* aActorDescription
);
614 MOZ_NEVER_INLINE
void MismatchedActorTypeError(const char* aActorDescription
);
616 MOZ_NEVER_INLINE
void UnionTypeReadError(const char* aUnionName
);
618 MOZ_NEVER_INLINE
void ArrayLengthReadError(const char* aElementName
);
620 MOZ_NEVER_INLINE
void SentinelReadError(const char* aElementName
);
623 * Annotate the crash reporter with the error code from the most recent system
624 * call. Returns the system error.
626 void AnnotateSystemError();
628 // The ActorLifecycleProxy is a helper type used internally by IPC to maintain a
629 // maybe-owning reference to an IProtocol object. For well-behaved actors
630 // which are not freed until after their `Dealloc` method is called, a
631 // reference to an actor's `ActorLifecycleProxy` object is an owning one, as the
632 // `Dealloc` method will only be called when all references to the
633 // `ActorLifecycleProxy` are released.
635 // Unfortunately, some actors may be destroyed before their `Dealloc` method
636 // is called. For these actors, `ActorLifecycleProxy` acts as a weak pointer,
637 // and will begin to return `nullptr` from its `Get()` method once the
638 // corresponding actor object has been destroyed.
640 // When calling a `Recv` method, IPC will hold a `ActorLifecycleProxy` reference
641 // to the target actor, meaning that well-behaved actors can behave as though a
642 // strong reference is being held.
644 // Generic IPC code MUST treat ActorLifecycleProxy references as weak
646 class ActorLifecycleProxy
{
648 NS_INLINE_DECL_REFCOUNTING_ONEVENTTARGET(ActorLifecycleProxy
)
650 IProtocol
* Get() { return mActor
; }
652 WeakActorLifecycleProxy
* GetWeakProxy();
655 friend class IProtocol
;
657 explicit ActorLifecycleProxy(IProtocol
* aActor
);
658 ~ActorLifecycleProxy();
660 ActorLifecycleProxy(const ActorLifecycleProxy
&) = delete;
661 ActorLifecycleProxy
& operator=(const ActorLifecycleProxy
&) = delete;
663 IProtocol
* MOZ_NON_OWNING_REF mActor
;
665 // Hold a reference to the actor's manager's ActorLifecycleProxy to help
666 // prevent it from dying while we're still alive!
667 RefPtr
<ActorLifecycleProxy
> mManager
;
669 // When requested, the current self-referencing weak reference for this
670 // ActorLifecycleProxy.
671 RefPtr
<WeakActorLifecycleProxy
> mWeakProxy
;
674 // Unlike ActorLifecycleProxy, WeakActorLifecycleProxy only holds a weak
675 // reference to both the proxy and the actual actor, meaning that holding this
676 // type will not attempt to keep the actor object alive.
678 // This type is safe to hold on threads other than the actor's thread, but is
679 // _NOT_ safe to access on other threads, as actors and ActorLifecycleProxy
680 // objects are not threadsafe.
681 class WeakActorLifecycleProxy final
{
683 NS_INLINE_DECL_THREADSAFE_REFCOUNTING(WeakActorLifecycleProxy
)
685 // May only be called on the actor's event target.
686 // Will return `nullptr` if the actor has already been destroyed from IPC's
688 IProtocol
* Get() const;
690 // Safe to call on any thread.
691 nsISerialEventTarget
* ActorEventTarget() const { return mActorEventTarget
; }
694 friend class ActorLifecycleProxy
;
696 explicit WeakActorLifecycleProxy(ActorLifecycleProxy
* aProxy
);
697 ~WeakActorLifecycleProxy();
699 WeakActorLifecycleProxy(const WeakActorLifecycleProxy
&) = delete;
700 WeakActorLifecycleProxy
& operator=(const WeakActorLifecycleProxy
&) = delete;
702 // This field may only be accessed on the actor's thread, and will be
703 // automatically cleared when the ActorLifecycleProxy is destroyed.
704 ActorLifecycleProxy
* MOZ_NON_OWNING_REF mProxy
;
706 // The serial event target which owns the actor, and is the only thread where
707 // it is OK to access the ActorLifecycleProxy.
708 const nsCOMPtr
<nsISerialEventTarget
> mActorEventTarget
;
711 class IPDLResolverInner final
{
713 NS_INLINE_DECL_THREADSAFE_REFCOUNTING_WITH_DESTROY(IPDLResolverInner
,
716 explicit IPDLResolverInner(UniquePtr
<IPC::Message
> aReply
, IProtocol
* aActor
);
718 template <typename F
>
719 void Resolve(F
&& aWrite
) {
720 ResolveOrReject(true, aWrite
);
724 void ResolveOrReject(bool aResolve
,
725 FunctionRef
<void(IPC::Message
*, IProtocol
*)> aWrite
);
728 ~IPDLResolverInner();
730 UniquePtr
<IPC::Message
> mReply
;
731 RefPtr
<WeakActorLifecycleProxy
> mWeakProxy
;
736 template <typename Protocol
>
737 class ManagedContainer
{
739 using iterator
= typename nsTArray
<Protocol
*>::const_iterator
;
741 iterator
begin() const { return mArray
.begin(); }
742 iterator
end() const { return mArray
.end(); }
743 iterator
cbegin() const { return begin(); }
744 iterator
cend() const { return end(); }
746 bool IsEmpty() const { return mArray
.IsEmpty(); }
747 uint32_t Count() const { return mArray
.Length(); }
749 void ToArray(nsTArray
<Protocol
*>& aArray
) const {
750 aArray
.AppendElements(mArray
);
753 bool EnsureRemoved(Protocol
* aElement
) {
754 return mArray
.RemoveElementSorted(aElement
);
757 void Insert(Protocol
* aElement
) {
758 // Equivalent to `InsertElementSorted`, avoiding inserting a duplicate
760 size_t index
= mArray
.IndexOfFirstElementGt(aElement
);
761 if (index
== 0 || mArray
[index
- 1] != aElement
) {
762 mArray
.InsertElementAt(index
, aElement
);
766 void Clear() { mArray
.Clear(); }
769 nsTArray
<Protocol
*> mArray
;
772 template <typename Protocol
>
773 Protocol
* LoneManagedOrNullAsserts(
774 const ManagedContainer
<Protocol
>& aManagees
) {
775 if (aManagees
.IsEmpty()) {
778 MOZ_ASSERT(aManagees
.Count() == 1);
779 return *aManagees
.cbegin();
782 template <typename Protocol
>
783 Protocol
* SingleManagedOrNull(const ManagedContainer
<Protocol
>& aManagees
) {
784 if (aManagees
.Count() != 1) {
787 return *aManagees
.cbegin();
790 } // namespace mozilla
792 #endif // mozilla_ipc_ProtocolUtils_h