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/. */
6 
7 #ifndef mozilla_ipc_ProtocolUtils_h
8 #define mozilla_ipc_ProtocolUtils_h 1
9 
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 "nsTHashMap.h"
32 #include "nsDebug.h"
33 #include "nsISupports.h"
34 #include "nsTArrayForwardDeclare.h"
35 #include "nsTHashSet.h"
36 
37 // XXX Things that could be replaced by a forward header
38 #include "mozilla/ipc/Transport.h"  // for Transport
39 
40 // XXX Things that could be moved to ProtocolUtils.cpp
41 #include "base/process_util.h"  // for CloseProcessHandle
42 #include "prenv.h"              // for PR_GetEnv
43 
44 #if defined(ANDROID) && defined(DEBUG)
45 #  include <android/log.h>
46 #endif
47 
48 template <typename T>
49 class nsPtrHashKey;
50 
51 // WARNING: this takes into account the private, special-message-type
52 // enum in ipc_channel.h.  They need to be kept in sync.
53 namespace {
54 // XXX the max message ID is actually kuint32max now ... when this
55 // changed, the assumptions of the special message IDs changed in that
56 // they're not carving out messages from likely-unallocated space, but
57 // rather carving out messages from the end of space allocated to
58 // protocol 0.  Oops!  We can get away with this until protocol 0
59 // starts approaching its 65,536th message.
60 enum {
61   // Message types used by NodeChannel
62   ACCEPT_INVITE_MESSAGE_TYPE = kuint16max - 14,
63   REQUEST_INTRODUCTION_MESSAGE_TYPE = kuint16max - 13,
64   INTRODUCE_MESSAGE_TYPE = kuint16max - 12,
65   BROADCAST_MESSAGE_TYPE = kuint16max - 11,
66   EVENT_MESSAGE_TYPE = kuint16max - 10,
67 
68   // Message types used by MessageChannel
69   IMPENDING_SHUTDOWN_MESSAGE_TYPE = kuint16max - 9,
70   BUILD_IDS_MATCH_MESSAGE_TYPE = kuint16max - 8,
71   BUILD_ID_MESSAGE_TYPE = kuint16max - 7,  // unused
72   CHANNEL_OPENED_MESSAGE_TYPE = kuint16max - 6,
73   SHMEM_DESTROYED_MESSAGE_TYPE = kuint16max - 5,
74   SHMEM_CREATED_MESSAGE_TYPE = kuint16max - 4,
75   GOODBYE_MESSAGE_TYPE = kuint16max - 3,
76   CANCEL_MESSAGE_TYPE = kuint16max - 2,
77 
78   // kuint16max - 1 is used by ipc_channel.h.
79 };
80 
81 }  // namespace
82 
83 class MessageLoop;
84 class PickleIterator;
85 class nsISerialEventTarget;
86 class nsUint32HashKey;
87 
88 namespace mozilla {
89 class SchedulerGroup;
90 
91 namespace dom {
92 class ContentParent;
93 }  // namespace dom
94 
95 namespace net {
96 class NeckoParent;
97 }  // namespace net
98 
99 namespace ipc {
100 
101 #ifdef FUZZING
102 class ProtocolFuzzerHelper;
103 #endif
104 
105 #ifdef XP_WIN
106 const base::ProcessHandle kInvalidProcessHandle = INVALID_HANDLE_VALUE;
107 
108 // In theory, on Windows, this is a valid process ID, but in practice they are
109 // currently divisible by four. Process IDs share the kernel handle allocation
110 // code and they are guaranteed to be divisible by four.
111 // As this could change for process IDs we shouldn't generally rely on this
112 // property, however even if that were to change, it seems safe to rely on this
113 // particular value never being used.
114 const base::ProcessId kInvalidProcessId = kuint32max;
115 #else
116 const base::ProcessHandle kInvalidProcessHandle = -1;
117 const base::ProcessId kInvalidProcessId = -1;
118 #endif
119 
120 // Scoped base::ProcessHandle to ensure base::CloseProcessHandle is called.
121 struct ScopedProcessHandleTraits {
122   typedef base::ProcessHandle type;
123 
emptyScopedProcessHandleTraits124   static type empty() { return kInvalidProcessHandle; }
125 
releaseScopedProcessHandleTraits126   static void release(type aProcessHandle) {
127     if (aProcessHandle && aProcessHandle != kInvalidProcessHandle) {
128       base::CloseProcessHandle(aProcessHandle);
129     }
130   }
131 };
132 typedef mozilla::Scoped<ScopedProcessHandleTraits> ScopedProcessHandle;
133 
134 class ProtocolFdMapping;
135 class ProtocolCloneContext;
136 
137 // Used to pass references to protocol actors across the wire.
138 // Actors created on the parent-side have a positive ID, and actors
139 // allocated on the child side have a negative ID.
140 struct ActorHandle {
141   int mId;
142 };
143 
144 // What happens if Interrupt calls race?
145 enum RacyInterruptPolicy { RIPError, RIPChildWins, RIPParentWins };
146 
147 enum class LinkStatus : uint8_t {
148   // The actor has not established a link yet, or the actor is no longer in use
149   // by IPC, and its 'Dealloc' method has been called or is being called.
150   //
151   // NOTE: This state is used instead of an explicit `Freed` state when IPC no
152   // longer holds references to the current actor as we currently re-open
153   // existing actors. Once we fix these poorly behaved actors, this loopback
154   // state can be split to have the final state not be the same as the initial
155   // state.
156   Inactive,
157 
158   // A live link is connected to the other side of this actor.
159   Connected,
160 
161   // The link has begun being destroyed. Messages may still be received, but
162   // cannot be sent. (exception: sync/intr replies may be sent while Doomed).
163   Doomed,
164 
165   // The link has been destroyed, and messages will no longer be sent or
166   // received.
167   Destroyed,
168 };
169 
170 typedef IPCMessageStart ProtocolId;
171 
172 // Generated by IPDL compiler
173 const char* ProtocolIdToName(IPCMessageStart aId);
174 
175 class IToplevelProtocol;
176 class ActorLifecycleProxy;
177 class WeakActorLifecycleProxy;
178 class IPDLResolverInner;
179 
180 class IProtocol : public HasResultCodes {
181  public:
182   enum ActorDestroyReason {
183     FailedConstructor,
184     Deletion,
185     AncestorDeletion,
186     NormalShutdown,
187     AbnormalShutdown
188   };
189 
190   typedef base::ProcessId ProcessId;
191   typedef IPC::Message Message;
192   typedef IPC::MessageInfo MessageInfo;
193 
IProtocol(ProtocolId aProtoId,Side aSide)194   IProtocol(ProtocolId aProtoId, Side aSide)
195       : mId(0),
196         mProtocolId(aProtoId),
197         mSide(aSide),
198         mLinkStatus(LinkStatus::Inactive),
199         mLifecycleProxy(nullptr),
200         mManager(nullptr),
201         mToplevel(nullptr) {}
202 
ToplevelProtocol()203   IToplevelProtocol* ToplevelProtocol() { return mToplevel; }
204 
205   // The following methods either directly forward to the toplevel protocol, or
206   // almost directly do.
207   int32_t Register(IProtocol* aRouted);
208   int32_t RegisterID(IProtocol* aRouted, int32_t aId);
209   IProtocol* Lookup(int32_t aId);
210   void Unregister(int32_t aId);
211 
212   Shmem::SharedMemory* CreateSharedMemory(size_t aSize,
213                                           SharedMemory::SharedMemoryType aType,
214                                           bool aUnsafe, int32_t* aId);
215   Shmem::SharedMemory* LookupSharedMemory(int32_t aId);
216   bool IsTrackingSharedMemory(Shmem::SharedMemory* aSegment);
217   bool DestroySharedMemory(Shmem& aShmem);
218 
219   MessageChannel* GetIPCChannel();
220   const MessageChannel* GetIPCChannel() const;
221 
222   // Sets an event target to which all messages for aActor will be
223   // dispatched. This method must be called before right before the SendPFoo
224   // message for aActor is sent. And SendPFoo *must* be called if
225   // SetEventTargetForActor is called. The receiver when calling
226   // SetEventTargetForActor must be the actor that will be the manager for
227   // aActor.
228   void SetEventTargetForActor(IProtocol* aActor,
229                               nsISerialEventTarget* aEventTarget);
230 
231   // Replace the event target for the messages of aActor. There must not be
232   // any messages of aActor in the task queue, or we might run into some
233   // unexpected behavior.
234   void ReplaceEventTargetForActor(IProtocol* aActor,
235                                   nsISerialEventTarget* aEventTarget);
236 
237   nsISerialEventTarget* GetActorEventTarget();
238   already_AddRefed<nsISerialEventTarget> GetActorEventTarget(IProtocol* aActor);
239 
240   ProcessId OtherPid() const;
241 
242   // Actor lifecycle and other properties.
GetProtocolId()243   ProtocolId GetProtocolId() const { return mProtocolId; }
GetProtocolName()244   const char* GetProtocolName() const { return ProtocolIdToName(mProtocolId); }
245 
Id()246   int32_t Id() const { return mId; }
Manager()247   IProtocol* Manager() const { return mManager; }
248 
GetLifecycleProxy()249   ActorLifecycleProxy* GetLifecycleProxy() { return mLifecycleProxy; }
250 
GetSide()251   Side GetSide() const { return mSide; }
CanSend()252   bool CanSend() const { return mLinkStatus == LinkStatus::Connected; }
CanRecv()253   bool CanRecv() const {
254     return mLinkStatus == LinkStatus::Connected ||
255            mLinkStatus == LinkStatus::Doomed;
256   }
257 
258   // Remove or deallocate a managee given its type.
259   virtual void RemoveManagee(int32_t, IProtocol*) = 0;
260   virtual void DeallocManagee(int32_t, IProtocol*) = 0;
261 
262   Maybe<IProtocol*> ReadActor(const IPC::Message* aMessage,
263                               PickleIterator* aIter, bool aNullable,
264                               const char* aActorDescription,
265                               int32_t aProtocolTypeId);
266 
267   virtual Result OnMessageReceived(const Message& aMessage) = 0;
268   virtual Result OnMessageReceived(const Message& aMessage,
269                                    Message*& aReply) = 0;
270   virtual Result OnCallReceived(const Message& aMessage, Message*& aReply) = 0;
271   bool AllocShmem(size_t aSize, Shmem::SharedMemory::SharedMemoryType aType,
272                   Shmem* aOutMem);
273   bool AllocUnsafeShmem(size_t aSize,
274                         Shmem::SharedMemory::SharedMemoryType aType,
275                         Shmem* aOutMem);
276   bool DeallocShmem(Shmem& aMem);
277 
278   void FatalError(const char* const aErrorMsg) const;
279   virtual void HandleFatalError(const char* aErrorMsg) const;
280 
281  protected:
282   virtual ~IProtocol();
283 
284   friend class IToplevelProtocol;
285   friend class ActorLifecycleProxy;
286   friend class IPDLResolverInner;
287 
288   void SetId(int32_t aId);
289 
290   // We have separate functions because the accessibility code manually
291   // calls SetManager.
292   void SetManager(IProtocol* aManager);
293 
294   // Sets the manager for the protocol and registers the protocol with
295   // its manager, setting up channels for the protocol as well.  Not
296   // for use outside of IPDL.
297   void SetManagerAndRegister(IProtocol* aManager);
298   void SetManagerAndRegister(IProtocol* aManager, int32_t aId);
299 
300   // Helpers for calling `Send` on our underlying IPC channel.
301   bool ChannelSend(IPC::Message* aMsg);
302   bool ChannelSend(IPC::Message* aMsg, IPC::Message* aReply);
303   bool ChannelCall(IPC::Message* aMsg, IPC::Message* aReply);
304   template <typename Value>
ChannelSend(IPC::Message * aMsg,ResolveCallback<Value> && aResolve,RejectCallback && aReject)305   void ChannelSend(IPC::Message* aMsg, ResolveCallback<Value>&& aResolve,
306                    RejectCallback&& aReject) {
307     UniquePtr<IPC::Message> msg(aMsg);
308     if (CanSend()) {
309       GetIPCChannel()->Send(std::move(msg), this, std::move(aResolve),
310                             std::move(aReject));
311     } else {
312       NS_WARNING("IPC message discarded: actor cannot send");
313       aReject(ResponseRejectReason::SendError);
314     }
315   }
316 
317   // Collect all actors managed by this object in an array. To make this safer
318   // to iterate, `ActorLifecycleProxy` references are returned rather than raw
319   // actor pointers.
320   virtual void AllManagedActors(
321       nsTArray<RefPtr<ActorLifecycleProxy>>& aActors) const = 0;
322 
323   // Internal method called when the actor becomes connected.
324   void ActorConnected();
325 
326   // Called immediately before setting the actor state to doomed, and triggering
327   // async actor destruction. Messages may be sent from this callback, but no
328   // later.
329   // FIXME(nika): This is currently unused!
ActorDoom()330   virtual void ActorDoom() {}
331   void DoomSubtree();
332 
333   // Called when the actor has been destroyed due to an error, a __delete__
334   // message, or a __doom__ reply.
ActorDestroy(ActorDestroyReason aWhy)335   virtual void ActorDestroy(ActorDestroyReason aWhy) {}
336   void DestroySubtree(ActorDestroyReason aWhy);
337 
338   // Called when IPC has acquired its first reference to the actor. This method
339   // may take references which will later be freed by `ActorDealloc`.
ActorAlloc()340   virtual void ActorAlloc() {}
341 
342   // Called when IPC has released its final reference to the actor. It will call
343   // the dealloc method, causing the actor to be actually freed.
344   //
345   // The actor has been freed after this method returns.
ActorDealloc()346   virtual void ActorDealloc() {
347     if (Manager()) {
348       Manager()->DeallocManagee(mProtocolId, this);
349     }
350   }
351 
352   static const int32_t kNullActorId = 0;
353   static const int32_t kFreedActorId = 1;
354 
355  private:
356   int32_t mId;
357   ProtocolId mProtocolId;
358   Side mSide;
359   LinkStatus mLinkStatus;
360   ActorLifecycleProxy* mLifecycleProxy;
361   IProtocol* mManager;
362   IToplevelProtocol* mToplevel;
363 };
364 
365 #define IPC_OK() mozilla::ipc::IPCResult::Ok()
366 #define IPC_FAIL(actor, why) \
367   mozilla::ipc::IPCResult::Fail(WrapNotNull(actor), __func__, (why))
368 #define IPC_FAIL_NO_REASON(actor) \
369   mozilla::ipc::IPCResult::Fail(WrapNotNull(actor), __func__)
370 
371 /**
372  * All message deserializer and message handler should return this
373  * type via above macros. We use a less generic name here to avoid
374  * conflict with mozilla::Result because we have quite a few using
375  * namespace mozilla::ipc; in the code base.
376  */
377 class IPCResult {
378  public:
Ok()379   static IPCResult Ok() { return IPCResult(true); }
380   static IPCResult Fail(NotNull<IProtocol*> aActor, const char* aWhere,
381                         const char* aWhy = "");
382   MOZ_IMPLICIT operator bool() const { return mSuccess; }
383 
384  private:
IPCResult(bool aResult)385   explicit IPCResult(bool aResult) : mSuccess(aResult) {}
386   bool mSuccess;
387 };
388 
389 template <class PFooSide>
390 class Endpoint;
391 
392 template <class PFooSide>
393 class ManagedEndpoint;
394 
395 /**
396  * All top-level protocols should inherit this class.
397  *
398  * IToplevelProtocol tracks all top-level protocol actors created from
399  * this protocol actor.
400  */
401 class IToplevelProtocol : public IProtocol {
402 #ifdef FUZZING
403   friend class mozilla::ipc::ProtocolFuzzerHelper;
404 #endif
405 
406   template <class PFooSide>
407   friend class Endpoint;
408 
409  protected:
410   explicit IToplevelProtocol(const char* aName, ProtocolId aProtoId,
411                              Side aSide);
412   ~IToplevelProtocol() = default;
413 
414  public:
415   // Shadow methods on IProtocol which are implemented directly on toplevel
416   // actors.
417   int32_t Register(IProtocol* aRouted);
418   int32_t RegisterID(IProtocol* aRouted, int32_t aId);
419   IProtocol* Lookup(int32_t aId);
420   void Unregister(int32_t aId);
421 
422   Shmem::SharedMemory* CreateSharedMemory(size_t aSize,
423                                           SharedMemory::SharedMemoryType aType,
424                                           bool aUnsafe, int32_t* aId);
425   Shmem::SharedMemory* LookupSharedMemory(int32_t aId);
426   bool IsTrackingSharedMemory(Shmem::SharedMemory* aSegment);
427   bool DestroySharedMemory(Shmem& aShmem);
428 
GetIPCChannel()429   MessageChannel* GetIPCChannel() { return &mChannel; }
GetIPCChannel()430   const MessageChannel* GetIPCChannel() const { return &mChannel; }
431 
432   // NOTE: The target actor's Manager must already be set.
433   void SetEventTargetForActorInternal(IProtocol* aActor,
434                                       nsISerialEventTarget* aEventTarget);
435   void ReplaceEventTargetForActor(IProtocol* aActor,
436                                   nsISerialEventTarget* aEventTarget);
437   nsISerialEventTarget* GetActorEventTarget();
438   already_AddRefed<nsISerialEventTarget> GetActorEventTarget(IProtocol* aActor);
439 
440   ProcessId OtherPid() const;
441   void SetOtherProcessId(base::ProcessId aOtherPid);
442 
443   virtual void OnChannelClose() = 0;
444   virtual void OnChannelError() = 0;
ProcessingError(Result aError,const char * aMsgName)445   virtual void ProcessingError(Result aError, const char* aMsgName) {}
446 
447   bool Open(ScopedPort aPort, base::ProcessId aOtherPid);
448 
449   bool Open(MessageChannel* aChannel, nsISerialEventTarget* aEventTarget,
450             mozilla::ipc::Side aSide = mozilla::ipc::UnknownSide);
451 
452   // Open a toplevel actor such that both ends of the actor's channel are on
453   // the same thread. This method should be called on the thread to perform
454   // the link.
455   //
456   // WARNING: Attempting to send a sync or intr message on the same thread
457   // will crash.
458   bool OpenOnSameThread(MessageChannel* aChannel,
459                         mozilla::ipc::Side aSide = mozilla::ipc::UnknownSide);
460 
461   /**
462    * This sends a special message that is processed on the IO thread, so that
463    * other actors can know that the process will soon shutdown.
464    */
465   void NotifyImpendingShutdown();
466 
467   void Close();
468 
469   void SetReplyTimeoutMs(int32_t aTimeoutMs);
470 
471   void DeallocShmems();
472   bool ShmemCreated(const Message& aMsg);
473   bool ShmemDestroyed(const Message& aMsg);
474 
ShouldContinueFromReplyTimeout()475   virtual bool ShouldContinueFromReplyTimeout() { return false; }
476 
477   // WARNING: This function is called with the MessageChannel monitor held.
IntentionalCrash()478   virtual void IntentionalCrash() { MOZ_CRASH("Intentional IPDL crash"); }
479 
480   // The code here is only useful for fuzzing. It should not be used for any
481   // other purpose.
482 #ifdef DEBUG
483   // Returns true if we should simulate a timeout.
484   // WARNING: This is a testing-only function that is called with the
485   // MessageChannel monitor held. Don't do anything fancy here or we could
486   // deadlock.
ArtificialTimeout()487   virtual bool ArtificialTimeout() { return false; }
488 
489   // Returns true if we want to cause the worker thread to sleep with the
490   // monitor unlocked.
NeedArtificialSleep()491   virtual bool NeedArtificialSleep() { return false; }
492 
493   // This function should be implemented to sleep for some amount of time on
494   // the worker thread. Will only be called if NeedArtificialSleep() returns
495   // true.
ArtificialSleep()496   virtual void ArtificialSleep() {}
497 #else
ArtificialTimeout()498   bool ArtificialTimeout() { return false; }
NeedArtificialSleep()499   bool NeedArtificialSleep() { return false; }
ArtificialSleep()500   void ArtificialSleep() {}
501 #endif
502 
EnteredCxxStack()503   virtual void EnteredCxxStack() {}
ExitedCxxStack()504   virtual void ExitedCxxStack() {}
EnteredCall()505   virtual void EnteredCall() {}
ExitedCall()506   virtual void ExitedCall() {}
507 
508   bool IsOnCxxStack() const;
509 
MediateInterruptRace(const MessageInfo & parent,const MessageInfo & child)510   virtual RacyInterruptPolicy MediateInterruptRace(const MessageInfo& parent,
511                                                    const MessageInfo& child) {
512     return RIPChildWins;
513   }
514 
515   /**
516    * Return true if windows messages can be handled while waiting for a reply
517    * to a sync IPDL message.
518    */
HandleWindowsMessages(const Message & aMsg)519   virtual bool HandleWindowsMessages(const Message& aMsg) const { return true; }
520 
OnEnteredSyncSend()521   virtual void OnEnteredSyncSend() {}
OnExitedSyncSend()522   virtual void OnExitedSyncSend() {}
523 
ProcessRemoteNativeEventsInInterruptCall()524   virtual void ProcessRemoteNativeEventsInInterruptCall() {}
525 
OnChannelReceivedMessage(const Message & aMsg)526   virtual void OnChannelReceivedMessage(const Message& aMsg) {}
527 
OnIPCChannelOpened()528   void OnIPCChannelOpened() { ActorConnected(); }
529 
530   already_AddRefed<nsISerialEventTarget> GetMessageEventTarget(
531       const Message& aMsg);
532 
OtherPidMaybeInvalid()533   base::ProcessId OtherPidMaybeInvalid() const { return mOtherPid; }
534 
535  private:
536   int32_t NextId();
537 
538   template <class T>
539   using IDMap = nsTHashMap<nsUint32HashKey, T>;
540 
541   base::ProcessId mOtherPid;
542 
543   // NOTE NOTE NOTE
544   // Used to be on mState
545   int32_t mLastLocalId;
546   IDMap<IProtocol*> mActorMap;
547   IDMap<Shmem::SharedMemory*> mShmemMap;
548 
549   // XXX: We no longer need mEventTargetMap for Quantum DOM, so it may be
550   // worthwhile to remove it before people start depending on it for other weird
551   // things.
552   Mutex mEventTargetMutex;
553   IDMap<nsCOMPtr<nsISerialEventTarget>> mEventTargetMap;
554 
555   MessageChannel mChannel;
556 };
557 
558 class IShmemAllocator {
559  public:
560   virtual bool AllocShmem(size_t aSize,
561                           mozilla::ipc::SharedMemory::SharedMemoryType aShmType,
562                           mozilla::ipc::Shmem* aShmem) = 0;
563   virtual bool AllocUnsafeShmem(
564       size_t aSize, mozilla::ipc::SharedMemory::SharedMemoryType aShmType,
565       mozilla::ipc::Shmem* aShmem) = 0;
566   virtual bool DeallocShmem(mozilla::ipc::Shmem& aShmem) = 0;
567 };
568 
569 #define FORWARD_SHMEM_ALLOCATOR_TO(aImplClass)                             \
570   virtual bool AllocShmem(                                                 \
571       size_t aSize, mozilla::ipc::SharedMemory::SharedMemoryType aShmType, \
572       mozilla::ipc::Shmem* aShmem) override {                              \
573     return aImplClass::AllocShmem(aSize, aShmType, aShmem);                \
574   }                                                                        \
575   virtual bool AllocUnsafeShmem(                                           \
576       size_t aSize, mozilla::ipc::SharedMemory::SharedMemoryType aShmType, \
577       mozilla::ipc::Shmem* aShmem) override {                              \
578     return aImplClass::AllocUnsafeShmem(aSize, aShmType, aShmem);          \
579   }                                                                        \
580   virtual bool DeallocShmem(mozilla::ipc::Shmem& aShmem) override {        \
581     return aImplClass::DeallocShmem(aShmem);                               \
582   }
583 
LoggingEnabled()584 inline bool LoggingEnabled() {
585 #if defined(DEBUG) || defined(FUZZING)
586   return !!PR_GetEnv("MOZ_IPC_MESSAGE_LOG");
587 #else
588   return false;
589 #endif
590 }
591 
592 #if defined(DEBUG) || defined(FUZZING)
593 bool LoggingEnabledFor(const char* aTopLevelProtocol, const char* aFilter);
594 #endif
595 
LoggingEnabledFor(const char * aTopLevelProtocol)596 inline bool LoggingEnabledFor(const char* aTopLevelProtocol) {
597 #if defined(DEBUG) || defined(FUZZING)
598   return LoggingEnabledFor(aTopLevelProtocol, PR_GetEnv("MOZ_IPC_MESSAGE_LOG"));
599 #else
600   return false;
601 #endif
602 }
603 
604 MOZ_NEVER_INLINE void LogMessageForProtocol(const char* aTopLevelProtocol,
605                                             base::ProcessId aOtherPid,
606                                             const char* aContextDescription,
607                                             uint32_t aMessageId,
608                                             MessageDirection aDirection);
609 
610 MOZ_NEVER_INLINE void ProtocolErrorBreakpoint(const char* aMsg);
611 
612 // The code generator calls this function for errors which come from the
613 // methods of protocols.  Doing this saves codesize by making the error
614 // cases significantly smaller.
615 MOZ_NEVER_INLINE void FatalError(const char* aMsg, bool aIsParent);
616 
617 // The code generator calls this function for errors which are not
618 // protocol-specific: errors in generated struct methods or errors in
619 // transition functions, for instance.  Doing this saves codesize by
620 // by making the error cases significantly smaller.
621 MOZ_NEVER_INLINE void LogicError(const char* aMsg);
622 
623 MOZ_NEVER_INLINE void ActorIdReadError(const char* aActorDescription);
624 
625 MOZ_NEVER_INLINE void BadActorIdError(const char* aActorDescription);
626 
627 MOZ_NEVER_INLINE void ActorLookupError(const char* aActorDescription);
628 
629 MOZ_NEVER_INLINE void MismatchedActorTypeError(const char* aActorDescription);
630 
631 MOZ_NEVER_INLINE void UnionTypeReadError(const char* aUnionName);
632 
633 MOZ_NEVER_INLINE void ArrayLengthReadError(const char* aElementName);
634 
635 MOZ_NEVER_INLINE void SentinelReadError(const char* aElementName);
636 
637 #if defined(XP_WIN)
638 // This is a restricted version of Windows' DuplicateHandle() function
639 // that works inside the sandbox and can send handles but not retrieve
640 // them.  Unlike DuplicateHandle(), it takes a process ID rather than
641 // a process handle.  It returns true on success, false otherwise.
642 bool DuplicateHandle(HANDLE aSourceHandle, DWORD aTargetProcessId,
643                      HANDLE* aTargetHandle, DWORD aDesiredAccess,
644                      DWORD aOptions);
645 #endif
646 
647 /**
648  * Annotate the crash reporter with the error code from the most recent system
649  * call. Returns the system error.
650  */
651 void AnnotateSystemError();
652 
653 // The ActorLifecycleProxy is a helper type used internally by IPC to maintain a
654 // maybe-owning reference to an IProtocol object. For well-behaved actors
655 // which are not freed until after their `Dealloc` method is called, a
656 // reference to an actor's `ActorLifecycleProxy` object is an owning one, as the
657 // `Dealloc` method will only be called when all references to the
658 // `ActorLifecycleProxy` are released.
659 //
660 // Unfortunately, some actors may be destroyed before their `Dealloc` method
661 // is called. For these actors, `ActorLifecycleProxy` acts as a weak pointer,
662 // and will begin to return `nullptr` from its `Get()` method once the
663 // corresponding actor object has been destroyed.
664 //
665 // When calling a `Recv` method, IPC will hold a `ActorLifecycleProxy` reference
666 // to the target actor, meaning that well-behaved actors can behave as though a
667 // strong reference is being held.
668 //
669 // Generic IPC code MUST treat ActorLifecycleProxy references as weak
670 // references!
671 class ActorLifecycleProxy {
672  public:
NS_INLINE_DECL_REFCOUNTING_ONEVENTTARGET(ActorLifecycleProxy)673   NS_INLINE_DECL_REFCOUNTING_ONEVENTTARGET(ActorLifecycleProxy)
674 
675   IProtocol* Get() { return mActor; }
676 
677   WeakActorLifecycleProxy* GetWeakProxy();
678 
679  private:
680   friend class IProtocol;
681 
682   explicit ActorLifecycleProxy(IProtocol* aActor);
683   ~ActorLifecycleProxy();
684 
685   ActorLifecycleProxy(const ActorLifecycleProxy&) = delete;
686   ActorLifecycleProxy& operator=(const ActorLifecycleProxy&) = delete;
687 
688   IProtocol* MOZ_NON_OWNING_REF mActor;
689 
690   // Hold a reference to the actor's manager's ActorLifecycleProxy to help
691   // prevent it from dying while we're still alive!
692   RefPtr<ActorLifecycleProxy> mManager;
693 
694   // When requested, the current self-referencing weak reference for this
695   // ActorLifecycleProxy.
696   RefPtr<WeakActorLifecycleProxy> mWeakProxy;
697 };
698 
699 // Unlike ActorLifecycleProxy, WeakActorLifecycleProxy only holds a weak
700 // reference to both the proxy and the actual actor, meaning that holding this
701 // type will not attempt to keep the actor object alive.
702 //
703 // This type is safe to hold on threads other than the actor's thread, but is
704 // _NOT_ safe to access on other threads, as actors and ActorLifecycleProxy
705 // objects are not threadsafe.
706 class WeakActorLifecycleProxy final {
707  public:
708   NS_INLINE_DECL_THREADSAFE_REFCOUNTING(WeakActorLifecycleProxy)
709 
710   // May only be called on the actor's event target.
711   // Will return `nullptr` if the actor has already been destroyed from IPC's
712   // point of view.
713   IProtocol* Get() const;
714 
715   // Safe to call on any thread.
ActorEventTarget()716   nsISerialEventTarget* ActorEventTarget() const { return mActorEventTarget; }
717 
718  private:
719   friend class ActorLifecycleProxy;
720 
721   explicit WeakActorLifecycleProxy(ActorLifecycleProxy* aProxy);
722   ~WeakActorLifecycleProxy();
723 
724   WeakActorLifecycleProxy(const WeakActorLifecycleProxy&) = delete;
725   WeakActorLifecycleProxy& operator=(const WeakActorLifecycleProxy&) = delete;
726 
727   // This field may only be accessed on the actor's thread, and will be
728   // automatically cleared when the ActorLifecycleProxy is destroyed.
729   ActorLifecycleProxy* MOZ_NON_OWNING_REF mProxy;
730 
731   // The serial event target which owns the actor, and is the only thread where
732   // it is OK to access the ActorLifecycleProxy.
733   const nsCOMPtr<nsISerialEventTarget> mActorEventTarget;
734 };
735 
736 class IPDLResolverInner final {
737  public:
738   NS_INLINE_DECL_THREADSAFE_REFCOUNTING_WITH_DESTROY(IPDLResolverInner,
739                                                      Destroy())
740 
741   explicit IPDLResolverInner(UniquePtr<IPC::Message> aReply, IProtocol* aActor);
742 
743   template <typename F>
Resolve(F && aWrite)744   void Resolve(F&& aWrite) {
745     ResolveOrReject(true, aWrite);
746   }
747 
748  private:
749   void ResolveOrReject(bool aResolve,
750                        FunctionRef<void(IPC::Message*, IProtocol*)> aWrite);
751 
752   void Destroy();
753   ~IPDLResolverInner();
754 
755   UniquePtr<IPC::Message> mReply;
756   RefPtr<WeakActorLifecycleProxy> mWeakProxy;
757 };
758 
759 }  // namespace ipc
760 
761 template <typename Protocol>
762 class ManagedContainer {
763  public:
764   using iterator = typename nsTArray<Protocol*>::const_iterator;
765 
begin()766   iterator begin() const { return mArray.begin(); }
end()767   iterator end() const { return mArray.end(); }
cbegin()768   iterator cbegin() const { return begin(); }
cend()769   iterator cend() const { return end(); }
770 
IsEmpty()771   bool IsEmpty() const { return mArray.IsEmpty(); }
Count()772   uint32_t Count() const { return mArray.Length(); }
773 
ToArray(nsTArray<Protocol * > & aArray)774   void ToArray(nsTArray<Protocol*>& aArray) const {
775     aArray.AppendElements(mArray);
776   }
777 
EnsureRemoved(Protocol * aElement)778   bool EnsureRemoved(Protocol* aElement) {
779     return mArray.RemoveElementSorted(aElement);
780   }
781 
Insert(Protocol * aElement)782   void Insert(Protocol* aElement) {
783     // Equivalent to `InsertElementSorted`, avoiding inserting a duplicate
784     // element.
785     size_t index = mArray.IndexOfFirstElementGt(aElement);
786     if (index == 0 || mArray[index - 1] != aElement) {
787       mArray.InsertElementAt(index, aElement);
788     }
789   }
790 
Clear()791   void Clear() { mArray.Clear(); }
792 
793  private:
794   nsTArray<Protocol*> mArray;
795 };
796 
797 template <typename Protocol>
LoneManagedOrNullAsserts(const ManagedContainer<Protocol> & aManagees)798 Protocol* LoneManagedOrNullAsserts(
799     const ManagedContainer<Protocol>& aManagees) {
800   if (aManagees.IsEmpty()) {
801     return nullptr;
802   }
803   MOZ_ASSERT(aManagees.Count() == 1);
804   return *aManagees.cbegin();
805 }
806 
807 template <typename Protocol>
SingleManagedOrNull(const ManagedContainer<Protocol> & aManagees)808 Protocol* SingleManagedOrNull(const ManagedContainer<Protocol>& aManagees) {
809   if (aManagees.Count() != 1) {
810     return nullptr;
811   }
812   return *aManagees.cbegin();
813 }
814 
815 }  // namespace mozilla
816 
817 #endif  // mozilla_ipc_ProtocolUtils_h
818