Files
roytam1 39770f3213 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1274192 part 1 - make the MediaDecoderReaderWrapper as a proxy of WaitForData(); r=jwwang (9debdca9a9)
- Bug 1274192 part 2 - make MDSM and SeekTask to adopt new MediaDecoderReaderWrapper API; r=jwwang (156f924dc9)
- Bug 1276495: Don't reset audio promises for video only seek. r=jwwang,jya (c4632c7ff6)
- Bug 1276318, part 1 - Fix leading tabs in ipc/glue. r=billm (46bcc4ccb3)
- Bug 1035125 Part 6: Take Chromium commit 3181ba39ee787e1b40f4aea4be23f4f666ad0945 to add Windows 10 version to enumeration. r=aklotz (af62c8065f)
- Bug 1270752 - Fix lifetime of buffer passed to PR_SetEnv(). r=jduell (bfce06ebea)
- Bug 1275117 - Fix static strings leaks when mozlogging is on. r=jduell (8e9066c5d7)
- Bug 1273048 - Add MOZ_GCC_VERSION_AT_MOST macro. r=froydnj (cfb5acdbe6)
- Bug 1269968 - Remove unnecessary deduction on RefPtr.h. r=froydnj (30cf9bbf47)
- Bug 525063 - add attribute to mark member variables that should be skipped by clang plugin initialization checker. r=nfroyd (78aa863f88)
- Bug 1278391 - add move constructor to EnumeratedArray (r=njn) (5effe4e473)
- Bug 1268518: Update basic-integer tests for rotations + clean up; r=sunfish (46827b6211)
- Bug 1270370 - Part 1: Move SetIteratorObject to MapObject.h; r=jorendorff (01a27fbd50)
- Bug 1270370 - Part 2: Expose MapIterator and SetIterator through ESClassValues; r=jorendorff (3edb3c7551)
- Bug 1267551 (part 3) - Use MOZ_MUST_USE more in js/src/builtin/. r=jonco. (ea96d0fae0)
- Bug 1267551 (part 4) - Use MOZ_MUST_USE more in js/src/asmjs/. r=bbouvier. (3e622c736d)
- Bug 1268910: Refactor WebAssembly trap handling; r=luke (b59394a287)
- Bug 1268910: Trap on edge cases for integer div/mod; r=sunfish (3d85230cc8)
- Bug 1267551 (part 5) - Use MOZ_MUST_USE more in js/src/ctypes/. r=sfink. (e6580fb645)
- Bug 1267551 (part 6) - Remove dead GenerateBlockId declaration. r=jorendorff. (74afcc549e)
- Bug 1240072 - Add public JS APIs related to modules r=shu Bug 1267551 (part 7) - Use MOZ_MUST_USE more in js/src/frontend/. r=jorendorff. (5275c57768)
- Bug 1267551 (part 8) - Use MOZ_MUST_USE more in js/src/gc/. r=terrence. (2572cc1c58)
- Bug 1261063 - Part 1 - Remove public Telemetry functions that return raw histogram instances. r=chutten (3a68653c8f)
- Bug 1261063 - Part 2 - Expose C++ function to clear Telemetry histograms. r=chutten (1f42f6aa1e)
- Bug 1261063 - Part 3 - Make RasterImage use the public Telemetry API. r=tnikkel (0f564f3836)
- Bug 1261063 - Part 4 - Use a count histogram for WebRTC call counts. r=jesup (b6b7b649e0)
- Bug 1270073 - Point to Telemetry documentation in Telemetry.h. r=chutten (517279b284)
- Bug 1261052 - Move C++ histogram implementation code into a separate module. r=gfritzsche. (66bcb1e167)
- Bug 1145164 - Allow non-unitary increments to count histograms. r=gfritzsche (507e076e28)
- Bug 1173447 - Add test for incremental pre-barriers when storing things under roots, r=jonco (caf8bd16be)
- Bug 1267551 (part 10) - Use MOZ_MUST_USE in AutoVectorRooterBase. r=terrence. (2c5ed87a9f)
- This catches a missing check. (b2fcd30fc5)
- Bug 1267551 (part 11b) - Follow-up to fix Android bustage. r=me (f464ca7b98)
- Bug 1271854 - Part 1: Allow specifying multiple GC zeal levels; r=terrence (da3c3e1281)
- Bug 1271854 - Part 2: Allow specifying zeal modes by name as well; r=terrence (f63926e45b)
- Bug 1271854 - Part 3: Avoid saving the GC zeal string inside the JS shell; r=terrence (f09b262e55)
- Bug 1270062 - Unbust Windows full duplex. a=Tomcat (3c8b5887b6)
- Bug 1270062 - Update libcubeb. rs=jesup (71805cb0e0)
- Bug 1270004 - Update libcubeb. rs=jesup (2d90b9662f)
- Bug 1280280 - Update cubeb to 073c9f011114. r=kinetik (6bee6a7f21)
- Bug 1280280 - Update media/libcube/update.sh to add cubeb_jack.cpp, and sort the list of files. r=kinetik (430b7533c4)
- Bug 1272604 - Add a zeal mode to check the heap after a moving GC r=terrence (85c018d71f)
- Bug 1272604 - Fix bad implicit conversion constructor build error r=me (5c4e1dbc44)
- Bug 1272604 - Fix hazard analysis failure r=me (0591aa2dca)
- Bug 1232417 - Use a Variant to represent the CrossCompartmentWrapperMap key; r=jonco (512da0bab3)
- Bug 1269928 - Fold DirectProxyHandler into Wrapper, which is now its only (non-test) consumer. r=efaust (7c6bb6e898)
- Bug 1273639 - Add a nonunified spidermonkey build, r=terrence (d6fa13545c)
- Bug 1273639 - Fix nonunified spidermonkey builds, r=terrence (3e0544510d)
- Bug 1273180 - Trigger major GC if necessary after minor GC r=terrence (a9a9be8b17)
- Bug 1268992 - Assert that the heap is empty after a shutdown GC; r=jonco (fe3ac5bdd6)
- Bug 1273908 - Refactor GC to make it easier to add new kinds of GC thing r=terrence (51c92e1b05)
2024-10-09 21:36:44 +08:00

478 lines
12 KiB
C++

/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "MessagePump.h"
#include "nsIRunnable.h"
#include "nsIThread.h"
#include "nsITimer.h"
#include "nsICancelableRunnable.h"
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/scoped_nsautorelease_pool.h"
#include "mozilla/Assertions.h"
#include "mozilla/DebugOnly.h"
#include "nsComponentManagerUtils.h"
#include "nsDebug.h"
#include "nsServiceManagerUtils.h"
#include "nsString.h"
#include "nsThreadUtils.h"
#include "nsTimerImpl.h"
#include "nsXULAppAPI.h"
#include "prthread.h"
#ifdef MOZ_NUWA_PROCESS
#include "ipc/Nuwa.h"
#endif
using base::TimeTicks;
using namespace mozilla::ipc;
NS_DEFINE_NAMED_CID(NS_TIMER_CID);
#ifdef DEBUG
static MessagePump::Delegate* gFirstDelegate;
#endif
namespace mozilla {
namespace ipc {
class DoWorkRunnable final : public CancelableRunnable,
public nsITimerCallback
{
public:
explicit DoWorkRunnable(MessagePump* aPump)
: mPump(aPump)
{
MOZ_ASSERT(aPump);
}
NS_DECL_ISUPPORTS_INHERITED
NS_DECL_NSIRUNNABLE
NS_DECL_NSITIMERCALLBACK
nsresult Cancel() override;
private:
~DoWorkRunnable()
{ }
MessagePump* mPump;
// DoWorkRunnable is designed as a stateless singleton. Do not add stateful
// members here!
};
} /* namespace ipc */
} /* namespace mozilla */
MessagePump::MessagePump(nsIThread* aThread)
: mThread(aThread)
{
mDoWorkEvent = new DoWorkRunnable(this);
}
MessagePump::~MessagePump()
{
}
void
MessagePump::Run(MessagePump::Delegate* aDelegate)
{
MOZ_ASSERT(keep_running_);
MOZ_RELEASE_ASSERT(NS_IsMainThread(),
"Use mozilla::ipc::MessagePumpForNonMainThreads instead!");
MOZ_RELEASE_ASSERT(!mThread);
nsIThread* thisThread = NS_GetCurrentThread();
MOZ_ASSERT(thisThread);
mDelayedWorkTimer = do_CreateInstance(kNS_TIMER_CID);
MOZ_ASSERT(mDelayedWorkTimer);
base::ScopedNSAutoreleasePool autoReleasePool;
for (;;) {
autoReleasePool.Recycle();
bool did_work = NS_ProcessNextEvent(thisThread, false) ? true : false;
if (!keep_running_)
break;
// NB: it is crucial *not* to directly call |aDelegate->DoWork()|
// here. To ensure that MessageLoop tasks and XPCOM events have
// equal priority, we sensitively rely on processing exactly one
// Task per DoWorkRunnable XPCOM event.
did_work |= aDelegate->DoDelayedWork(&delayed_work_time_);
if (did_work && delayed_work_time_.is_null()
#ifdef MOZ_NUWA_PROCESS
&& (!IsNuwaReady() || !IsNuwaProcess())
#endif
)
mDelayedWorkTimer->Cancel();
if (!keep_running_)
break;
if (did_work)
continue;
did_work = aDelegate->DoIdleWork();
if (!keep_running_)
break;
if (did_work)
continue;
// This will either sleep or process an event.
NS_ProcessNextEvent(thisThread, true);
}
#ifdef MOZ_NUWA_PROCESS
if (!IsNuwaReady() || !IsNuwaProcess())
#endif
mDelayedWorkTimer->Cancel();
keep_running_ = true;
}
void
MessagePump::ScheduleWork()
{
// Make sure the event loop wakes up.
if (mThread) {
mThread->Dispatch(mDoWorkEvent, NS_DISPATCH_NORMAL);
} else {
// Some things (like xpcshell) don't use the app shell and so Run hasn't
// been called. We still need to wake up the main thread.
NS_DispatchToMainThread(mDoWorkEvent);
}
event_.Signal();
}
void
MessagePump::ScheduleWorkForNestedLoop()
{
// This method is called when our MessageLoop has just allowed
// nested tasks. In our setup, whenever that happens we know that
// DoWork() will be called "soon", so there's no need to pay the
// cost of what will be a no-op nsThread::Dispatch(mDoWorkEvent).
}
void
MessagePump::ScheduleDelayedWork(const base::TimeTicks& aDelayedTime)
{
#ifdef MOZ_NUWA_PROCESS
if (IsNuwaReady() && IsNuwaProcess())
return;
#endif
// To avoid racing on mDelayedWorkTimer, we need to be on the same thread as
// ::Run().
MOZ_RELEASE_ASSERT(NS_GetCurrentThread() == mThread ||
(!mThread && NS_IsMainThread()));
if (!mDelayedWorkTimer) {
mDelayedWorkTimer = do_CreateInstance(kNS_TIMER_CID);
if (!mDelayedWorkTimer) {
// Called before XPCOM has started up? We can't do this correctly.
NS_WARNING("Delayed task might not run!");
delayed_work_time_ = aDelayedTime;
return;
}
}
if (!delayed_work_time_.is_null()) {
mDelayedWorkTimer->Cancel();
}
delayed_work_time_ = aDelayedTime;
// TimeDelta's constructor initializes to 0
base::TimeDelta delay;
if (aDelayedTime > base::TimeTicks::Now())
delay = aDelayedTime - base::TimeTicks::Now();
uint32_t delayMS = uint32_t(delay.InMilliseconds());
mDelayedWorkTimer->InitWithCallback(mDoWorkEvent, delayMS,
nsITimer::TYPE_ONE_SHOT);
}
nsIEventTarget*
MessagePump::GetXPCOMThread()
{
if (mThread) {
return mThread;
}
// Main thread
nsCOMPtr<nsIThread> mainThread = do_GetMainThread();
return mainThread;
}
void
MessagePump::DoDelayedWork(base::MessagePump::Delegate* aDelegate)
{
aDelegate->DoDelayedWork(&delayed_work_time_);
if (!delayed_work_time_.is_null()) {
ScheduleDelayedWork(delayed_work_time_);
}
}
NS_IMPL_ISUPPORTS_INHERITED(DoWorkRunnable, CancelableRunnable,
nsITimerCallback)
NS_IMETHODIMP
DoWorkRunnable::Run()
{
MessageLoop* loop = MessageLoop::current();
MOZ_ASSERT(loop);
bool nestableTasksAllowed = loop->NestableTasksAllowed();
// MessageLoop::RunTask() disallows nesting, but our Frankenventloop will
// always dispatch DoWork() below from what looks to MessageLoop like a nested
// context. So we unconditionally allow nesting here.
loop->SetNestableTasksAllowed(true);
loop->DoWork();
loop->SetNestableTasksAllowed(nestableTasksAllowed);
return NS_OK;
}
NS_IMETHODIMP
DoWorkRunnable::Notify(nsITimer* aTimer)
{
MessageLoop* loop = MessageLoop::current();
MOZ_ASSERT(loop);
bool nestableTasksAllowed = loop->NestableTasksAllowed();
loop->SetNestableTasksAllowed(true);
mPump->DoDelayedWork(loop);
loop->SetNestableTasksAllowed(nestableTasksAllowed);
return NS_OK;
}
nsresult
DoWorkRunnable::Cancel()
{
// Workers require cancelable runnables, but we can't really cancel cleanly
// here. If we don't process this runnable then we will leave something
// unprocessed in the message_loop. Therefore, eagerly complete our work
// instead by immediately calling Run(). Run() should be called separately
// after this. Unfortunately we cannot use flags to verify this because
// DoWorkRunnable is a stateless singleton that can be in the event queue
// multiple times simultaneously.
MOZ_ALWAYS_SUCCEEDS(Run());
return NS_OK;
}
void
MessagePumpForChildProcess::Run(base::MessagePump::Delegate* aDelegate)
{
if (mFirstRun) {
MOZ_ASSERT(aDelegate && !gFirstDelegate);
#ifdef DEBUG
gFirstDelegate = aDelegate;
#endif
mFirstRun = false;
if (NS_FAILED(XRE_RunAppShell())) {
NS_WARNING("Failed to run app shell?!");
}
MOZ_ASSERT(aDelegate && aDelegate == gFirstDelegate);
#ifdef DEBUG
gFirstDelegate = nullptr;
#endif
return;
}
MOZ_ASSERT(aDelegate && aDelegate == gFirstDelegate);
// We can get to this point in startup with Tasks in our loop's
// incoming_queue_ or pending_queue_, but without a matching
// DoWorkRunnable(). In MessagePump::Run() above, we sensitively
// depend on *not* directly calling delegate->DoWork(), because that
// prioritizes Tasks above XPCOM events. However, from this point
// forward, any Task posted to our loop is guaranteed to have a
// DoWorkRunnable enqueued for it.
//
// So we just flush the pending work here and move on.
MessageLoop* loop = MessageLoop::current();
bool nestableTasksAllowed = loop->NestableTasksAllowed();
loop->SetNestableTasksAllowed(true);
while (aDelegate->DoWork());
loop->SetNestableTasksAllowed(nestableTasksAllowed);
// Really run.
mozilla::ipc::MessagePump::Run(aDelegate);
}
void
MessagePumpForNonMainThreads::Run(base::MessagePump::Delegate* aDelegate)
{
MOZ_ASSERT(keep_running_);
MOZ_RELEASE_ASSERT(!NS_IsMainThread(), "Use mozilla::ipc::MessagePump instead!");
nsIThread* thread = NS_GetCurrentThread();
MOZ_RELEASE_ASSERT(mThread == thread);
mDelayedWorkTimer = do_CreateInstance(kNS_TIMER_CID);
MOZ_ASSERT(mDelayedWorkTimer);
if (NS_FAILED(mDelayedWorkTimer->SetTarget(thread))) {
MOZ_CRASH("Failed to set timer target!");
}
// Chromium event notifications to be processed will be received by this
// event loop as a DoWorkRunnables via ScheduleWork. Chromium events that
// were received before our thread is valid, however, will not generate
// runnable wrappers. We must process any of these before we enter this
// loop, or we will forever have unprocessed chromium messages in our queue.
//
// Note we would like to request a flush of the chromium event queue
// using a runnable on the xpcom side, but some thread implementations
// (dom workers) get cranky if we call ScheduleWork here (ScheduleWork
// calls dispatch on mThread) before the thread processes an event. As
// such, clear the queue manually.
while (aDelegate->DoWork()) {
}
base::ScopedNSAutoreleasePool autoReleasePool;
for (;;) {
autoReleasePool.Recycle();
bool didWork = NS_ProcessNextEvent(thread, false) ? true : false;
if (!keep_running_) {
break;
}
didWork |= aDelegate->DoDelayedWork(&delayed_work_time_);
if (didWork && delayed_work_time_.is_null()) {
mDelayedWorkTimer->Cancel();
}
if (!keep_running_) {
break;
}
if (didWork) {
continue;
}
didWork = aDelegate->DoIdleWork();
if (!keep_running_) {
break;
}
if (didWork) {
continue;
}
// This will either sleep or process an event.
NS_ProcessNextEvent(thread, true);
}
mDelayedWorkTimer->Cancel();
keep_running_ = true;
}
#if defined(XP_WIN)
NS_IMPL_QUERY_INTERFACE(MessagePumpForNonMainUIThreads, nsIThreadObserver)
#define CHECK_QUIT_STATE { if (state_->should_quit) { break; } }
void
MessagePumpForNonMainUIThreads::DoRunLoop()
{
MOZ_RELEASE_ASSERT(!NS_IsMainThread(), "Use mozilla::ipc::MessagePump instead!");
// If this is a chromium thread and no nsThread is associated
// with it, this call will create a new nsThread.
nsIThread* thread = NS_GetCurrentThread();
MOZ_ASSERT(thread);
// Set the main thread observer so we can wake up when
// xpcom events need to get processed.
nsCOMPtr<nsIThreadInternal> ti(do_QueryInterface(thread));
MOZ_ASSERT(ti);
ti->SetObserver(this);
base::ScopedNSAutoreleasePool autoReleasePool;
for (;;) {
autoReleasePool.Recycle();
bool didWork = NS_ProcessNextEvent(thread, false);
didWork |= ProcessNextWindowsMessage();
CHECK_QUIT_STATE
didWork |= state_->delegate->DoWork();
CHECK_QUIT_STATE
didWork |= state_->delegate->DoDelayedWork(&delayed_work_time_);
if (didWork && delayed_work_time_.is_null()) {
KillTimer(message_hwnd_, reinterpret_cast<UINT_PTR>(this));
}
CHECK_QUIT_STATE
if (didWork) {
continue;
}
didWork = state_->delegate->DoIdleWork();
CHECK_QUIT_STATE
SetInWait();
bool hasWork = NS_HasPendingEvents(thread);
if (didWork || hasWork) {
ClearInWait();
continue;
}
WaitForWork(); // Calls MsgWaitForMultipleObjectsEx(QS_ALLINPUT)
ClearInWait();
}
ClearInWait();
ti->SetObserver(nullptr);
}
NS_IMETHODIMP
MessagePumpForNonMainUIThreads::OnDispatchedEvent(nsIThreadInternal *thread)
{
// If our thread is sleeping in DoRunLoop's call to WaitForWork() and an
// event posts to the nsIThread event queue - break our thread out of
// chromium's WaitForWork.
if (GetInWait()) {
ScheduleWork();
}
return NS_OK;
}
NS_IMETHODIMP
MessagePumpForNonMainUIThreads::OnProcessNextEvent(nsIThreadInternal *thread,
bool mayWait)
{
return NS_OK;
}
NS_IMETHODIMP
MessagePumpForNonMainUIThreads::AfterProcessNextEvent(nsIThreadInternal *thread,
bool eventWasProcessed)
{
return NS_OK;
}
#endif // XP_WIN