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 http://mozilla.org/MPL/2.0/. */
7 #ifndef mozilla_mscom_EnsureMTA_h
8 #define mozilla_mscom_EnsureMTA_h
10 #include "MainThreadUtils.h"
11 #include "mozilla/Attributes.h"
12 #include "mozilla/DebugOnly.h"
13 #include "mozilla/MozPromise.h"
14 #include "mozilla/Unused.h"
15 #include "mozilla/mscom/AgileReference.h"
16 #include "mozilla/mscom/Utils.h"
17 #include "mozilla/RefPtr.h"
19 #include "nsIThread.h"
20 #include "nsThreadUtils.h"
21 #include "nsWindowsHelpers.h"
29 // Forward declarations
37 struct MTAReleaseInChildProcess
;
39 struct PreservedStreamDeleter
;
43 // This class is OK to use as a temporary on the stack.
44 class MOZ_STACK_CLASS EnsureMTA final
{
47 * This constructor just ensures that the MTA thread is up and running.
50 nsCOMPtr
<nsIThread
> thread
= GetMTAThread();
57 // Forcibly dispatch to the thread returned by GetMTAThread(), even if the
58 // current thread is already inside a MTA.
63 * Synchronously run |aClosure| on a thread living in the COM multithreaded
64 * apartment. If the current thread lives inside the COM MTA, then it runs
65 * |aClosure| immediately unless |aOpt| == Option::ForceDispatch.
67 template <typename FuncT
>
68 explicit EnsureMTA(FuncT
&& aClosure
, Option aOpt
= Option::Default
) {
69 if (aOpt
!= Option::ForceDispatch
&& IsCurrentThreadMTA()) {
70 // We're already on the MTA, we can run aClosure directly
75 // In this case we need to run aClosure on a background thread in the MTA
76 nsCOMPtr
<nsIThread
> thread
= GetMTAThread();
82 // Note that we might reenter the EnsureMTA constructor while we wait on
83 // this event due to APC dispatch, therefore we need a unique event object
84 // for each entry. If perf becomes an issue then we will want to maintain
85 // an array of events where the Nth event is unique to the Nth reentry.
86 nsAutoHandle
event(::CreateEventW(nullptr, FALSE
, FALSE
, nullptr));
91 HANDLE eventHandle
= event
.get();
93 auto eventSetter
= [&aClosure
, eventHandle
]() -> void {
95 ::SetEvent(eventHandle
);
98 nsresult rv
= thread
->Dispatch(
99 NS_NewRunnableFunction("EnsureMTA", std::move(eventSetter
)),
101 MOZ_ASSERT(NS_SUCCEEDED(rv
));
107 while ((waitResult
= ::WaitForSingleObjectEx(event
, INFINITE
, TRUE
)) ==
108 WAIT_IO_COMPLETION
) {
110 MOZ_ASSERT(waitResult
== WAIT_OBJECT_0
);
113 using CreateInstanceAgileRefPromise
=
114 MozPromise
<AgileReference
, HRESULT
, false>;
117 * *** A MSCOM PEER SHOULD REVIEW ALL NEW USES OF THIS API! ***
119 * Asynchronously instantiate a new COM object from a MTA thread, unless the
120 * current thread is already living inside the multithreaded apartment, in
121 * which case the object is immediately instantiated.
123 * This function only supports the most common configurations for creating
124 * a new object, so it only supports in-process servers. Furthermore, this
125 * function does not support aggregation (ie. the |pUnkOuter| parameter to
128 * Given that attempting to instantiate an Apartment-threaded COM object
129 * inside the MTA results in a *loss* of performance, we assert when that
132 * The resulting promise, once resolved, provides an AgileReference that may
133 * be passed between any COM-initialized thread in the current process.
135 * *** A MSCOM PEER SHOULD REVIEW ALL NEW USES OF THIS API! ***
138 * Some COM objects do not support creation in the multithreaded apartment,
139 * in which case this function is not available as an option. In this case,
140 * the promise will always be rejected. In debug builds we will assert.
142 * *** A MSCOM PEER SHOULD REVIEW ALL NEW USES OF THIS API! ***
145 * Any in-process COM objects whose interfaces accept HWNDs are probably
146 * *not* safe to instantiate in the multithreaded apartment! Even if this
147 * function succeeds when creating such an object, you *MUST NOT* do so, as
148 * these failures might not become apparent until your code is running out in
149 * the wild on the release channel!
151 * *** A MSCOM PEER SHOULD REVIEW ALL NEW USES OF THIS API! ***
154 * When you obtain an interface from the AgileReference, it may or may not be
155 * a proxy to the real object. This depends entirely on the implementation of
156 * the underlying class and the multithreading capabilities that the class
157 * declares to the COM runtime. If the interface is proxied, it might be
158 * expensive to invoke methods on that interface! *Always* test the
159 * performance of your method calls when calling interfaces that are resolved
162 * *** A MSCOM PEER SHOULD REVIEW ALL NEW USES OF THIS API! ***
164 * (Despite this myriad of warnings, it is still *much* safer to use this
165 * function to asynchronously create COM objects than it is to roll your own!)
167 * *** A MSCOM PEER SHOULD REVIEW ALL NEW USES OF THIS API! ***
169 static RefPtr
<CreateInstanceAgileRefPromise
> CreateInstance(REFCLSID aClsid
,
173 static RefPtr
<CreateInstanceAgileRefPromise
> CreateInstanceInternal(
174 REFCLSID aClsid
, REFIID aIid
);
176 static nsCOMPtr
<nsIThread
> GetMTAThread();
178 // The following function is private in order to force any consumers to be
179 // declared as friends of EnsureMTA. The intention is to prevent
180 // AsyncOperation from becoming some kind of free-for-all mechanism for
181 // asynchronously executing work on a background thread.
182 template <typename FuncT
>
183 static void AsyncOperation(FuncT
&& aClosure
) {
184 if (IsCurrentThreadMTA()) {
189 nsCOMPtr
<nsIThread
> thread(GetMTAThread());
195 DebugOnly
<nsresult
> rv
= thread
->Dispatch(
196 NS_NewRunnableFunction("mscom::EnsureMTA::AsyncOperation",
197 std::move(aClosure
)),
199 MOZ_ASSERT(NS_SUCCEEDED(rv
));
202 template <typename T
>
203 friend struct mozilla::mscom::detail::MTADelete
;
205 template <typename T
>
206 friend struct mozilla::mscom::detail::MTARelease
;
208 template <typename T
>
209 friend struct mozilla::mscom::detail::MTAReleaseInChildProcess
;
211 friend struct mozilla::mscom::detail::PreservedStreamDeleter
;
215 } // namespace mozilla
217 #endif // mozilla_mscom_EnsureMTA_h