Backed out 8 changesets (bug 1873776) for causing vendor failures. CLOSED TREE
[gecko.git] / ipc / glue / ProtocolUtils.h
blob842bc229867d2f44c2a1df2ec19e8b665e65c845
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/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"
33 #include "nsDebug.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>
44 #endif
46 template <typename T>
47 class nsPtrHashKey;
49 // WARNING: this takes into account the private, special-message-type
50 // enum in ipc_channel.h. They need to be kept in sync.
51 namespace {
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.
58 enum {
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.
85 } // namespace
87 class MessageLoop;
88 class PickleIterator;
89 class nsISerialEventTarget;
91 namespace mozilla {
92 class SchedulerGroup;
94 namespace dom {
95 class ContentParent;
96 } // namespace dom
98 namespace net {
99 class NeckoParent;
100 } // namespace net
102 namespace ipc {
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.
124 struct ActorHandle {
125 int mId;
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
139 // state.
140 Inactive,
142 // A live link is connected to the other side of this actor.
143 Connected,
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).
147 Doomed,
149 // The link has been destroyed, and messages will no longer be sent or
150 // received.
151 Destroyed,
154 typedef IPCMessageStart ProtocolId;
156 // Generated by IPDL compiler
157 const char* ProtocolIdToName(IPCMessageStart aId);
159 class IRefCountedProtocol;
160 class IToplevelProtocol;
161 class ActorLifecycleProxy;
162 class WeakActorLifecycleProxy;
163 class IPDLResolverInner;
164 class UntypedManagedEndpoint;
166 class IProtocol : public HasResultCodes {
167 public:
168 enum ActorDestroyReason {
169 FailedConstructor,
170 Deletion,
171 AncestorDeletion,
172 NormalShutdown,
173 AbnormalShutdown,
174 ManagedEndpointDropped
177 typedef base::ProcessId ProcessId;
178 typedef IPC::Message Message;
180 IProtocol(ProtocolId aProtoId, Side aSide)
181 : mId(0),
182 mProtocolId(aProtoId),
183 mSide(aSide),
184 mLinkStatus(LinkStatus::Inactive),
185 mLifecycleProxy(nullptr),
186 mManager(nullptr),
187 mToplevel(nullptr) {}
189 IToplevelProtocol* ToplevelProtocol() { return mToplevel; }
190 const IToplevelProtocol* ToplevelProtocol() const { return mToplevel; }
192 // The following methods either directly forward to the toplevel protocol, or
193 // almost directly do.
194 int32_t Register(IProtocol* aRouted);
195 int32_t RegisterID(IProtocol* aRouted, int32_t aId);
196 IProtocol* Lookup(int32_t aId);
197 void Unregister(int32_t aId);
199 Shmem::SharedMemory* CreateSharedMemory(size_t aSize, bool aUnsafe,
200 int32_t* aId);
201 Shmem::SharedMemory* LookupSharedMemory(int32_t aId);
202 bool IsTrackingSharedMemory(Shmem::SharedMemory* aSegment);
203 bool DestroySharedMemory(Shmem& aShmem);
205 MessageChannel* GetIPCChannel();
206 const MessageChannel* GetIPCChannel() const;
208 // Get the nsISerialEventTarget which all messages sent to this actor will be
209 // processed on. Unless stated otherwise, all operations on IProtocol which
210 // don't occur on this `nsISerialEventTarget` are unsafe.
211 nsISerialEventTarget* GetActorEventTarget();
213 // Actor lifecycle and other properties.
214 ProtocolId GetProtocolId() const { return mProtocolId; }
215 const char* GetProtocolName() const { return ProtocolIdToName(mProtocolId); }
217 int32_t Id() const { return mId; }
218 IProtocol* Manager() const { return mManager; }
220 ActorLifecycleProxy* GetLifecycleProxy() { return mLifecycleProxy; }
221 WeakActorLifecycleProxy* GetWeakLifecycleProxy();
223 Side GetSide() const { return mSide; }
224 bool CanSend() const { return mLinkStatus == LinkStatus::Connected; }
225 bool CanRecv() const {
226 return mLinkStatus == LinkStatus::Connected ||
227 mLinkStatus == LinkStatus::Doomed;
230 // Remove or deallocate a managee given its type.
231 virtual void RemoveManagee(int32_t, IProtocol*) = 0;
232 virtual void DeallocManagee(int32_t, IProtocol*) = 0;
234 Maybe<IProtocol*> ReadActor(IPC::MessageReader* aReader, bool aNullable,
235 const char* aActorDescription,
236 int32_t aProtocolTypeId);
238 virtual Result OnMessageReceived(const Message& aMessage) = 0;
239 virtual Result OnMessageReceived(const Message& aMessage,
240 UniquePtr<Message>& aReply) = 0;
241 virtual Result OnCallReceived(const Message& aMessage,
242 UniquePtr<Message>& aReply) = 0;
243 bool AllocShmem(size_t aSize, Shmem* aOutMem);
244 bool AllocUnsafeShmem(size_t aSize, Shmem* aOutMem);
245 bool DeallocShmem(Shmem& aMem);
247 void FatalError(const char* const aErrorMsg);
248 virtual void HandleFatalError(const char* aErrorMsg);
250 protected:
251 virtual ~IProtocol();
253 friend class IToplevelProtocol;
254 friend class ActorLifecycleProxy;
255 friend class IPDLResolverInner;
256 friend class UntypedManagedEndpoint;
258 void SetId(int32_t aId);
260 // We have separate functions because the accessibility code manually
261 // calls SetManager.
262 void SetManager(IProtocol* aManager);
264 // Sets the manager for the protocol and registers the protocol with
265 // its manager, setting up channels for the protocol as well. Not
266 // for use outside of IPDL.
267 void SetManagerAndRegister(IProtocol* aManager);
268 void SetManagerAndRegister(IProtocol* aManager, int32_t aId);
270 // Helpers for calling `Send` on our underlying IPC channel.
271 bool ChannelSend(UniquePtr<IPC::Message> aMsg);
272 bool ChannelSend(UniquePtr<IPC::Message> aMsg,
273 UniquePtr<IPC::Message>* aReply);
274 template <typename Value>
275 void ChannelSend(UniquePtr<IPC::Message> aMsg,
276 IPC::Message::msgid_t aReplyMsgId,
277 ResolveCallback<Value>&& aResolve,
278 RejectCallback&& aReject) {
279 if (CanSend()) {
280 GetIPCChannel()->Send(std::move(aMsg), Id(), aReplyMsgId,
281 std::move(aResolve), std::move(aReject));
282 } else {
283 WarnMessageDiscarded(aMsg.get());
284 aReject(ResponseRejectReason::SendError);
288 // Collect all actors managed by this object in an array. To make this safer
289 // to iterate, `ActorLifecycleProxy` references are returned rather than raw
290 // actor pointers.
291 virtual void AllManagedActors(
292 nsTArray<RefPtr<ActorLifecycleProxy>>& aActors) const = 0;
294 virtual uint32_t AllManagedActorsCount() const = 0;
296 // Internal method called when the actor becomes connected.
297 void ActorConnected();
299 // Called immediately before setting the actor state to doomed, and triggering
300 // async actor destruction. Messages may be sent from this callback, but no
301 // later.
302 // FIXME(nika): This is currently unused!
303 virtual void ActorDoom() {}
304 void DoomSubtree();
306 // Called when the actor has been destroyed due to an error, a __delete__
307 // message, or a __doom__ reply.
308 virtual void ActorDestroy(ActorDestroyReason aWhy) {}
309 void DestroySubtree(ActorDestroyReason aWhy);
311 // Called when IPC has acquired its first reference to the actor. This method
312 // may take references which will later be freed by `ActorDealloc`.
313 virtual void ActorAlloc() = 0;
315 // Called when IPC has released its final reference to the actor. It will call
316 // the dealloc method, causing the actor to be actually freed.
318 // The actor has been freed after this method returns.
319 virtual void ActorDealloc() = 0;
321 static const int32_t kNullActorId = 0;
322 static const int32_t kFreedActorId = 1;
324 private:
325 #ifdef DEBUG
326 void WarnMessageDiscarded(IPC::Message* aMsg);
327 #else
328 void WarnMessageDiscarded(IPC::Message*) {}
329 #endif
331 int32_t mId;
332 ProtocolId mProtocolId;
333 Side mSide;
334 LinkStatus mLinkStatus;
335 ActorLifecycleProxy* mLifecycleProxy;
336 IProtocol* mManager;
337 IToplevelProtocol* mToplevel;
340 #define IPC_OK() mozilla::ipc::IPCResult::Ok()
341 #define IPC_FAIL(actor, why) \
342 mozilla::ipc::IPCResult::Fail(WrapNotNull(actor), __func__, (why))
343 #define IPC_FAIL_NO_REASON(actor) \
344 mozilla::ipc::IPCResult::Fail(WrapNotNull(actor), __func__)
347 * IPC_FAIL_UNSAFE_PRINTF(actor, format, ...)
349 * Create a failure IPCResult with a dynamic reason-string.
351 * @note This macro causes data collection because IPC failure reasons may be
352 * sent to crash-stats, where they are publicly visible. Firefox data stewards
353 * must do data review on usages of this macro.
355 #define IPC_FAIL_UNSAFE_PRINTF(actor, format, ...) \
356 mozilla::ipc::IPCResult::FailUnsafePrintfImpl( \
357 WrapNotNull(actor), __func__, nsPrintfCString(format, ##__VA_ARGS__))
360 * All message deserializers and message handlers should return this type via
361 * the above macros. We use a less generic name here to avoid conflict with
362 * `mozilla::Result` because we have quite a few `using namespace mozilla::ipc;`
363 * in the code base.
365 * Note that merely constructing a failure-result, whether directly or via the
366 * IPC_FAIL macros, causes the associated error message to be processed
367 * immediately.
369 class IPCResult {
370 public:
371 static IPCResult Ok() { return IPCResult(true); }
373 // IPC failure messages can sometimes end up in telemetry. As such, to avoid
374 // accidentally exfiltrating sensitive information without a data review, we
375 // require that they be constant strings.
376 template <size_t N, size_t M>
377 static IPCResult Fail(NotNull<IProtocol*> aActor, const char (&aWhere)[N],
378 const char (&aWhy)[M]) {
379 return FailImpl(aActor, aWhere, aWhy);
381 template <size_t N>
382 static IPCResult Fail(NotNull<IProtocol*> aActor, const char (&aWhere)[N]) {
383 return FailImpl(aActor, aWhere, "");
386 MOZ_IMPLICIT operator bool() const { return mSuccess; }
388 // Only used by IPC_FAIL_UNSAFE_PRINTF (q.v.). Do not call this directly. (Or
389 // at least get data-review's approval if you do.)
390 template <size_t N>
391 static IPCResult FailUnsafePrintfImpl(NotNull<IProtocol*> aActor,
392 const char (&aWhere)[N],
393 nsPrintfCString const& aWhy) {
394 return FailImpl(aActor, aWhere, aWhy.get());
397 private:
398 static IPCResult FailImpl(NotNull<IProtocol*> aActor, const char* aWhere,
399 const char* aWhy);
401 explicit IPCResult(bool aResult) : mSuccess(aResult) {}
402 bool mSuccess;
405 class UntypedEndpoint;
407 template <class PFooSide>
408 class Endpoint;
410 template <class PFooSide>
411 class ManagedEndpoint;
414 * All refcounted protocols should inherit this class.
416 class IRefCountedProtocol : public IProtocol {
417 public:
418 NS_INLINE_DECL_PURE_VIRTUAL_REFCOUNTING
420 using IProtocol::IProtocol;
424 * All top-level protocols should inherit this class.
426 * IToplevelProtocol tracks all top-level protocol actors created from
427 * this protocol actor.
429 class IToplevelProtocol : public IRefCountedProtocol {
430 template <class PFooSide>
431 friend class Endpoint;
433 protected:
434 explicit IToplevelProtocol(const char* aName, ProtocolId aProtoId,
435 Side aSide);
436 ~IToplevelProtocol() = default;
438 public:
439 // Shadow methods on IProtocol which are implemented directly on toplevel
440 // actors.
441 int32_t Register(IProtocol* aRouted);
442 int32_t RegisterID(IProtocol* aRouted, int32_t aId);
443 IProtocol* Lookup(int32_t aId);
444 void Unregister(int32_t aId);
446 Shmem::SharedMemory* CreateSharedMemory(size_t aSize, bool aUnsafe,
447 int32_t* aId);
448 Shmem::SharedMemory* LookupSharedMemory(int32_t aId);
449 bool IsTrackingSharedMemory(Shmem::SharedMemory* aSegment);
450 bool DestroySharedMemory(Shmem& aShmem);
452 MessageChannel* GetIPCChannel() { return &mChannel; }
453 const MessageChannel* GetIPCChannel() const { return &mChannel; }
455 void SetOtherProcessId(base::ProcessId aOtherPid);
457 virtual void OnChannelClose() = 0;
458 virtual void OnChannelError() = 0;
459 virtual void ProcessingError(Result aError, const char* aMsgName) {}
461 bool Open(ScopedPort aPort, const nsID& aMessageChannelId,
462 base::ProcessId aOtherPid,
463 nsISerialEventTarget* aEventTarget = nullptr);
465 bool Open(IToplevelProtocol* aTarget, nsISerialEventTarget* aEventTarget,
466 mozilla::ipc::Side aSide = mozilla::ipc::UnknownSide);
468 // Open a toplevel actor such that both ends of the actor's channel are on
469 // the same thread. This method should be called on the thread to perform
470 // the link.
472 // WARNING: Attempting to send a sync or intr message on the same thread
473 // will crash.
474 bool OpenOnSameThread(IToplevelProtocol* aTarget,
475 mozilla::ipc::Side aSide = mozilla::ipc::UnknownSide);
478 * This sends a special message that is processed on the IO thread, so that
479 * other actors can know that the process will soon shutdown.
481 void NotifyImpendingShutdown();
483 void Close();
485 void SetReplyTimeoutMs(int32_t aTimeoutMs);
487 void DeallocShmems();
488 bool ShmemCreated(const Message& aMsg);
489 bool ShmemDestroyed(const Message& aMsg);
491 virtual bool ShouldContinueFromReplyTimeout() { return false; }
493 // WARNING: This function is called with the MessageChannel monitor held.
494 virtual void IntentionalCrash() { MOZ_CRASH("Intentional IPDL crash"); }
496 // The code here is only useful for fuzzing. It should not be used for any
497 // other purpose.
498 #ifdef DEBUG
499 // Returns true if we should simulate a timeout.
500 // WARNING: This is a testing-only function that is called with the
501 // MessageChannel monitor held. Don't do anything fancy here or we could
502 // deadlock.
503 virtual bool ArtificialTimeout() { return false; }
505 // Returns true if we want to cause the worker thread to sleep with the
506 // monitor unlocked.
507 virtual bool NeedArtificialSleep() { return false; }
509 // This function should be implemented to sleep for some amount of time on
510 // the worker thread. Will only be called if NeedArtificialSleep() returns
511 // true.
512 virtual void ArtificialSleep() {}
513 #else
514 bool ArtificialTimeout() { return false; }
515 bool NeedArtificialSleep() { return false; }
516 void ArtificialSleep() {}
517 #endif
519 bool IsOnCxxStack() const;
521 virtual void ProcessRemoteNativeEventsInInterruptCall() {}
523 virtual void OnChannelReceivedMessage(const Message& aMsg) {}
525 void OnIPCChannelOpened() { ActorConnected(); }
527 base::ProcessId OtherPidMaybeInvalid() const { return mOtherPid; }
529 private:
530 int32_t NextId();
532 template <class T>
533 using IDMap = nsTHashMap<nsUint32HashKey, T>;
535 base::ProcessId mOtherPid;
537 // NOTE NOTE NOTE
538 // Used to be on mState
539 int32_t mLastLocalId;
540 IDMap<IProtocol*> mActorMap;
541 IDMap<Shmem::SharedMemory*> mShmemMap;
543 MessageChannel mChannel;
546 class IShmemAllocator {
547 public:
548 virtual bool AllocShmem(size_t aSize, mozilla::ipc::Shmem* aShmem) = 0;
549 virtual bool AllocUnsafeShmem(size_t aSize, mozilla::ipc::Shmem* aShmem) = 0;
550 virtual bool DeallocShmem(mozilla::ipc::Shmem& aShmem) = 0;
553 #define FORWARD_SHMEM_ALLOCATOR_TO(aImplClass) \
554 virtual bool AllocShmem(size_t aSize, mozilla::ipc::Shmem* aShmem) \
555 override { \
556 return aImplClass::AllocShmem(aSize, aShmem); \
558 virtual bool AllocUnsafeShmem(size_t aSize, mozilla::ipc::Shmem* aShmem) \
559 override { \
560 return aImplClass::AllocUnsafeShmem(aSize, aShmem); \
562 virtual bool DeallocShmem(mozilla::ipc::Shmem& aShmem) override { \
563 return aImplClass::DeallocShmem(aShmem); \
566 inline bool LoggingEnabled() {
567 #if defined(DEBUG) || defined(FUZZING)
568 return !!PR_GetEnv("MOZ_IPC_MESSAGE_LOG");
569 #else
570 return false;
571 #endif
574 #if defined(DEBUG) || defined(FUZZING)
575 bool LoggingEnabledFor(const char* aTopLevelProtocol, mozilla::ipc::Side aSide,
576 const char* aFilter);
577 #endif
579 inline bool LoggingEnabledFor(const char* aTopLevelProtocol,
580 mozilla::ipc::Side aSide) {
581 #if defined(DEBUG) || defined(FUZZING)
582 return LoggingEnabledFor(aTopLevelProtocol, aSide,
583 PR_GetEnv("MOZ_IPC_MESSAGE_LOG"));
584 #else
585 return false;
586 #endif
589 MOZ_NEVER_INLINE void LogMessageForProtocol(const char* aTopLevelProtocol,
590 base::ProcessId aOtherPid,
591 const char* aContextDescription,
592 uint32_t aMessageId,
593 MessageDirection aDirection);
595 MOZ_NEVER_INLINE void ProtocolErrorBreakpoint(const char* aMsg);
597 // IPC::MessageReader and IPC::MessageWriter call this function for FatalError
598 // calls which come from serialization/deserialization.
599 MOZ_NEVER_INLINE void PickleFatalError(const char* aMsg, IProtocol* aActor);
601 // The code generator calls this function for errors which come from the
602 // methods of protocols. Doing this saves codesize by making the error
603 // cases significantly smaller.
604 MOZ_NEVER_INLINE void FatalError(const char* aMsg, bool aIsParent);
606 // The code generator calls this function for errors which are not
607 // protocol-specific: errors in generated struct methods or errors in
608 // transition functions, for instance. Doing this saves codesize by
609 // by making the error cases significantly smaller.
610 MOZ_NEVER_INLINE void LogicError(const char* aMsg);
612 MOZ_NEVER_INLINE void ActorIdReadError(const char* aActorDescription);
614 MOZ_NEVER_INLINE void BadActorIdError(const char* aActorDescription);
616 MOZ_NEVER_INLINE void ActorLookupError(const char* aActorDescription);
618 MOZ_NEVER_INLINE void MismatchedActorTypeError(const char* aActorDescription);
620 MOZ_NEVER_INLINE void UnionTypeReadError(const char* aUnionName);
622 MOZ_NEVER_INLINE void ArrayLengthReadError(const char* aElementName);
624 MOZ_NEVER_INLINE void SentinelReadError(const char* aElementName);
627 * Annotate the crash reporter with the error code from the most recent system
628 * call. Returns the system error.
630 void AnnotateSystemError();
632 // The ActorLifecycleProxy is a helper type used internally by IPC to maintain a
633 // maybe-owning reference to an IProtocol object. For well-behaved actors
634 // which are not freed until after their `Dealloc` method is called, a
635 // reference to an actor's `ActorLifecycleProxy` object is an owning one, as the
636 // `Dealloc` method will only be called when all references to the
637 // `ActorLifecycleProxy` are released.
639 // Unfortunately, some actors may be destroyed before their `Dealloc` method
640 // is called. For these actors, `ActorLifecycleProxy` acts as a weak pointer,
641 // and will begin to return `nullptr` from its `Get()` method once the
642 // corresponding actor object has been destroyed.
644 // When calling a `Recv` method, IPC will hold a `ActorLifecycleProxy` reference
645 // to the target actor, meaning that well-behaved actors can behave as though a
646 // strong reference is being held.
648 // Generic IPC code MUST treat ActorLifecycleProxy references as weak
649 // references!
650 class ActorLifecycleProxy {
651 public:
652 NS_INLINE_DECL_REFCOUNTING_ONEVENTTARGET(ActorLifecycleProxy)
654 IProtocol* Get() { return mActor; }
656 WeakActorLifecycleProxy* GetWeakProxy();
658 private:
659 friend class IProtocol;
661 explicit ActorLifecycleProxy(IProtocol* aActor);
662 ~ActorLifecycleProxy();
664 ActorLifecycleProxy(const ActorLifecycleProxy&) = delete;
665 ActorLifecycleProxy& operator=(const ActorLifecycleProxy&) = delete;
667 IProtocol* MOZ_NON_OWNING_REF mActor;
669 // Hold a reference to the actor's manager's ActorLifecycleProxy to help
670 // prevent it from dying while we're still alive!
671 RefPtr<ActorLifecycleProxy> mManager;
673 // When requested, the current self-referencing weak reference for this
674 // ActorLifecycleProxy.
675 RefPtr<WeakActorLifecycleProxy> mWeakProxy;
678 // Unlike ActorLifecycleProxy, WeakActorLifecycleProxy only holds a weak
679 // reference to both the proxy and the actual actor, meaning that holding this
680 // type will not attempt to keep the actor object alive.
682 // This type is safe to hold on threads other than the actor's thread, but is
683 // _NOT_ safe to access on other threads, as actors and ActorLifecycleProxy
684 // objects are not threadsafe.
685 class WeakActorLifecycleProxy final {
686 public:
687 NS_INLINE_DECL_THREADSAFE_REFCOUNTING(WeakActorLifecycleProxy)
689 // May only be called on the actor's event target.
690 // Will return `nullptr` if the actor has already been destroyed from IPC's
691 // point of view.
692 IProtocol* Get() const;
694 // Safe to call on any thread.
695 nsISerialEventTarget* ActorEventTarget() const { return mActorEventTarget; }
697 private:
698 friend class ActorLifecycleProxy;
700 explicit WeakActorLifecycleProxy(ActorLifecycleProxy* aProxy);
701 ~WeakActorLifecycleProxy();
703 WeakActorLifecycleProxy(const WeakActorLifecycleProxy&) = delete;
704 WeakActorLifecycleProxy& operator=(const WeakActorLifecycleProxy&) = delete;
706 // This field may only be accessed on the actor's thread, and will be
707 // automatically cleared when the ActorLifecycleProxy is destroyed.
708 ActorLifecycleProxy* MOZ_NON_OWNING_REF mProxy;
710 // The serial event target which owns the actor, and is the only thread where
711 // it is OK to access the ActorLifecycleProxy.
712 const nsCOMPtr<nsISerialEventTarget> mActorEventTarget;
715 class IPDLResolverInner final {
716 public:
717 NS_INLINE_DECL_THREADSAFE_REFCOUNTING_WITH_DESTROY(IPDLResolverInner,
718 Destroy())
720 explicit IPDLResolverInner(UniquePtr<IPC::Message> aReply, IProtocol* aActor);
722 template <typename F>
723 void Resolve(F&& aWrite) {
724 ResolveOrReject(true, aWrite);
727 private:
728 void ResolveOrReject(bool aResolve,
729 FunctionRef<void(IPC::Message*, IProtocol*)> aWrite);
731 void Destroy();
732 ~IPDLResolverInner();
734 UniquePtr<IPC::Message> mReply;
735 RefPtr<WeakActorLifecycleProxy> mWeakProxy;
738 } // namespace ipc
740 template <typename Protocol>
741 class ManagedContainer {
742 public:
743 using iterator = typename nsTArray<Protocol*>::const_iterator;
745 iterator begin() const { return mArray.begin(); }
746 iterator end() const { return mArray.end(); }
747 iterator cbegin() const { return begin(); }
748 iterator cend() const { return end(); }
750 bool IsEmpty() const { return mArray.IsEmpty(); }
751 uint32_t Count() const { return mArray.Length(); }
753 void ToArray(nsTArray<Protocol*>& aArray) const {
754 aArray.AppendElements(mArray);
757 bool EnsureRemoved(Protocol* aElement) {
758 return mArray.RemoveElementSorted(aElement);
761 void Insert(Protocol* aElement) {
762 // Equivalent to `InsertElementSorted`, avoiding inserting a duplicate
763 // element.
764 size_t index = mArray.IndexOfFirstElementGt(aElement);
765 if (index == 0 || mArray[index - 1] != aElement) {
766 mArray.InsertElementAt(index, aElement);
770 void Clear() { mArray.Clear(); }
772 private:
773 nsTArray<Protocol*> mArray;
776 template <typename Protocol>
777 Protocol* LoneManagedOrNullAsserts(
778 const ManagedContainer<Protocol>& aManagees) {
779 if (aManagees.IsEmpty()) {
780 return nullptr;
782 MOZ_ASSERT(aManagees.Count() == 1);
783 return *aManagees.cbegin();
786 template <typename Protocol>
787 Protocol* SingleManagedOrNull(const ManagedContainer<Protocol>& aManagees) {
788 if (aManagees.Count() != 1) {
789 return nullptr;
791 return *aManagees.cbegin();
794 } // namespace mozilla
796 #endif // mozilla_ipc_ProtocolUtils_h