no bug - Bumping Firefox l10n changesets r=release a=l10n-bump DONTBUILD CLOSED TREE
[gecko.git] / ipc / glue / ProtocolUtils.h
blob2a0c64de20dda4a43ffbf9a1d895bfc95b0092fe
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
10 #include <cstddef>
11 #include <cstdint>
12 #include <utility>
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"
32 #include "nsDebug.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>
43 #endif
45 template <typename T>
46 class nsPtrHashKey;
48 // WARNING: this takes into account the private, special-message-type
49 // enum in ipc_channel.h. They need to be kept in sync.
50 namespace {
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.
57 enum {
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.
84 } // namespace
86 class MessageLoop;
87 class PickleIterator;
88 class nsISerialEventTarget;
90 namespace mozilla {
91 class SchedulerGroup;
93 namespace dom {
94 class ContentParent;
95 } // namespace dom
97 namespace net {
98 class NeckoParent;
99 } // namespace net
101 namespace ipc {
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.
109 struct ActorHandle {
110 int mId;
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
124 // state.
125 Inactive,
127 // A live link is connected to the other side of this actor.
128 Connected,
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).
132 Doomed,
134 // The link has been destroyed, and messages will no longer be sent or
135 // received.
136 Destroyed,
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 {
152 public:
153 enum ActorDestroyReason {
154 FailedConstructor,
155 Deletion,
156 AncestorDeletion,
157 NormalShutdown,
158 AbnormalShutdown,
159 ManagedEndpointDropped
162 typedef base::ProcessId ProcessId;
163 typedef IPC::Message Message;
165 IProtocol(ProtocolId aProtoId, Side aSide)
166 : mId(0),
167 mProtocolId(aProtoId),
168 mSide(aSide),
169 mLinkStatus(LinkStatus::Inactive),
170 mLifecycleProxy(nullptr),
171 mManager(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,
185 int32_t* aId);
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);
235 protected:
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
246 // calls SetManager.
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) {
264 if (CanSend()) {
265 GetIPCChannel()->Send(std::move(aMsg), Id(), aReplyMsgId,
266 std::move(aResolve), std::move(aReject));
267 } else {
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
275 // actor pointers.
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
286 // later.
287 // FIXME(nika): This is currently unused!
288 virtual void ActorDoom() {}
289 void DoomSubtree();
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;
309 private:
310 #ifdef DEBUG
311 void WarnMessageDiscarded(IPC::Message* aMsg);
312 #else
313 void WarnMessageDiscarded(IPC::Message*) {}
314 #endif
316 int32_t mId;
317 ProtocolId mProtocolId;
318 Side mSide;
319 LinkStatus mLinkStatus;
320 ActorLifecycleProxy* mLifecycleProxy;
321 IProtocol* mManager;
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;`
348 * in the code base.
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
352 * immediately.
354 class IPCResult {
355 public:
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);
366 template <size_t N>
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.)
375 template <size_t N>
376 static IPCResult FailUnsafePrintfImpl(NotNull<IProtocol*> aActor,
377 const char (&aWhere)[N],
378 nsPrintfCString const& aWhy) {
379 return FailImpl(aActor, aWhere, aWhy.get());
382 private:
383 static IPCResult FailImpl(NotNull<IProtocol*> aActor, const char* aWhere,
384 const char* aWhy);
386 explicit IPCResult(bool aResult) : mSuccess(aResult) {}
387 bool mSuccess;
390 class UntypedEndpoint;
392 template <class PFooSide>
393 class Endpoint;
395 template <class PFooSide>
396 class ManagedEndpoint;
399 * All refcounted protocols should inherit this class.
401 class IRefCountedProtocol : public IProtocol {
402 public:
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;
418 protected:
419 explicit IToplevelProtocol(const char* aName, ProtocolId aProtoId,
420 Side aSide);
421 ~IToplevelProtocol() = default;
423 public:
424 // Shadow methods on IProtocol which are implemented directly on toplevel
425 // actors.
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,
432 int32_t* aId);
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
455 // the link.
457 // WARNING: Attempting to send a sync or intr message on the same thread
458 // will crash.
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();
468 void Close();
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
482 // other purpose.
483 #ifdef DEBUG
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
487 // deadlock.
488 virtual bool ArtificialTimeout() { return false; }
490 // Returns true if we want to cause the worker thread to sleep with the
491 // monitor unlocked.
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
496 // true.
497 virtual void ArtificialSleep() {}
498 #else
499 bool ArtificialTimeout() { return false; }
500 bool NeedArtificialSleep() { return false; }
501 void ArtificialSleep() {}
502 #endif
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; }
514 private:
515 int32_t NextId();
517 template <class T>
518 using IDMap = nsTHashMap<nsUint32HashKey, T>;
520 base::ProcessId mOtherPid;
522 // NOTE NOTE NOTE
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 {
532 public:
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) \
540 override { \
541 return aImplClass::AllocShmem(aSize, aShmem); \
543 virtual bool AllocUnsafeShmem(size_t aSize, mozilla::ipc::Shmem* aShmem) \
544 override { \
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");
554 #else
555 return false;
556 #endif
559 #if defined(DEBUG) || defined(FUZZING)
560 bool LoggingEnabledFor(const char* aTopLevelProtocol, mozilla::ipc::Side aSide,
561 const char* aFilter);
562 #endif
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"));
569 #else
570 return false;
571 #endif
574 MOZ_NEVER_INLINE void LogMessageForProtocol(const char* aTopLevelProtocol,
575 base::ProcessId aOtherPid,
576 const char* aContextDescription,
577 uint32_t aMessageId,
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
634 // references!
635 class ActorLifecycleProxy {
636 public:
637 NS_INLINE_DECL_REFCOUNTING_ONEVENTTARGET(ActorLifecycleProxy)
639 IProtocol* Get() { return mActor; }
641 WeakActorLifecycleProxy* GetWeakProxy();
643 private:
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 {
671 public:
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
676 // point of view.
677 IProtocol* Get() const;
679 // Safe to call on any thread.
680 nsISerialEventTarget* ActorEventTarget() const { return mActorEventTarget; }
682 private:
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 {
701 public:
702 NS_INLINE_DECL_THREADSAFE_REFCOUNTING_WITH_DESTROY(IPDLResolverInner,
703 Destroy())
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));
712 private:
713 void ResolveOrReject(bool aResolve,
714 FunctionRef<void(IPC::Message*, IProtocol*)> aWrite);
716 void Destroy();
717 ~IPDLResolverInner();
719 UniquePtr<IPC::Message> mReply;
720 RefPtr<WeakActorLifecycleProxy> mWeakProxy;
723 } // namespace ipc
725 template <typename Protocol>
726 class ManagedContainer {
727 public:
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
748 // element.
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(); }
757 private:
758 nsTArray<Protocol*> mArray;
761 template <typename Protocol>
762 Protocol* LoneManagedOrNullAsserts(
763 const ManagedContainer<Protocol>& aManagees) {
764 if (aManagees.IsEmpty()) {
765 return nullptr;
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) {
774 return nullptr;
776 return *aManagees.cbegin();
779 } // namespace mozilla
781 #endif // mozilla_ipc_ProtocolUtils_h