Files
palemoon27/ipc/glue/MessagePump.cpp
T
roytam1 ca069b707a import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1244228 - fix DrawTargetSkia::OptimizeSourceSurface to still create Skia surfaces for GPU canvases even if creating a GPU surface failed. r=jmuizelaar (fbc02e4dc2)
- Bug 1259621 - use AlphaBoxBlur in DrawTargetSkia::DrawSurfaceWithShadow. r=mchang (2c9df0d317)
- Bug 1257717 - throw InvalidStateError when CreatePattern fails to snapshot source. r=jrmuizel (95fc5c4101)
- Bug 1264246 - verify that SkCanvas::getClipBounds succeeds before using result. r=mchang (20de1e897d)
- Bug 1249033 - Enable Subpixel AA Text on Skia for Dwrite and GDI Fonts. r=jrmuizel (f7402a4c9d)
- Bug 1250787 - ensure that subpixel text is disabled for Skia's Cairo font host so that font rendering matches our font metrics. r=mchang (4d77670f3f)
- Bug 1260454. Disable LCD font smoothing if we have grayscale AA on OS X. r=lsalzman (44bf859df5)
- bug 1263685 - Check if paint has a shader before modifying local matrix in DrawTargetSkia::MaskSurface. r=mchang (7937265238)
- missing bit for bump version (e3b14b6854)
- Bug 1252650 - Add data parameter to NS_CreateServicesFromCategory; r=froydnj (3a3d392669)
- Bug 1252650 - char16_t*/char16ptr_t mismatch fixup. (66d4bb1d1b)
- Bug 1261382 - Add ReadUntil method to Tokenizer r=mayhemer (3c0b05a359)
- Bug 1242963 - nsID stringification helper for logging; r=froydnj (966c73478a)
- Bug 1262400 - remove outer pointers from nsCreateInstance* classes; r=erahm (16680909c0)
- Bug 1257331 - Use LPWSTR instead of LPVOID to prevent C4477 warning; r=froydnj (456b677e25)
- bits of Bug 868814 - Fold mozallo (3580f23f5a)
- Bug 1256027 - Cast a few things in varargs to the expected types for MSVC 2015 warning-compatibility. r=froydnj (6e3e5f1763)
- Bug 1257262 - Removed invalid nsAString:Assign variant. r=bsmedberg (1f4b303f7a)
- bug 761909 - crash reporter plumbing for gonk. r=bsmedberg (e27b276147)
- Bug 1223800 - Accept BHR reports from 50% of beta clients. Up from 1%. r=vladan (fb67094a56)
- Bug 1241507 - Enable BHR reporting on 100% of the Beta population. r=rvitillo (6b0abc7767)
- Bug 1234618. Fix misdetected BHR hangs. r=jchen (4adc7d57a1)
- bits of Bug 1128768: Part 2 - Refactor (f75559fe5b)
- Bug 1168167 - Mark LazyIdleThread::mIdleObserver with MOZ_UNSAFE_REF. r=froydnj (9750c9686d)
- Bug 1250829 - add customized assertions for completion promises to facilitate promise chaining. r=bobbyholley. (66fe29ec68)
- Bug 1191063 - Followup comments. r=me DONTBUILD (a627c0bb62)
- bits of Bug 1172769 (6ce96f8829)
- Bug 1241656 - Lazify AutoTaskDispatcher::mDirectTasks. r=bholley. (48fab6f3fb)
- Bug 1202667 - make TaskQueue dispatching slightly more efficient; r=mccr8 (0c9f19fae5)
- Bug 1202667 - make TaskQueue task running slightly more efficient; r=mccr8 (cee8821a9f)
- Bug 1207031 - Suppress -Wshadow warnings from google-breakpad headers in xpcom/threads. r=froydnj (e2426fcf8a)
- Bug 1222101 - Reorder some thread code (r=jld) a=kwierso (4b816f501e)
- Bug 1257862 - Allow running things from the delayed work queue during a nested event loop. r=khuey,dvander (066ce6ab76)
- Bug 1236789. Part 2 - fix assertions when |aFlags == NS_DISPATCH_TAIL|. r=bholley (d6500cceb0)
- Bug 1254218 - Rely on old-configure.in to detect dladdr(). r=njn (8beefa2792)
- Bug 1257786 - Proper init of LogModule for Nuwa r=khuey (5170b5250b)
- Bug 1236108: Add support for exception-context annotations for content processes to the crash reporter; r=bsmedberg (3441aa3773)
- Bug 1256541: Fix incorrect generation of path for child process .extra files when content sandboxing is disabled; r=bsmedberg (ae8ba562ca)
- bug 1264242 - Write memory info streams for Windows Minidumps of child processes. r=bsmedberg (245b797566)
- Bug 1257486 - Annotate global memory status in the crash reporter for child process; r=bsmedberg (9af844a7dd)
- Bug 1257209 - record uptime in crash metadata/pings, r=gfritzsche (bfe0ea8759)
- Bug 1241613 - Only pass MOZ_BUILDID to the one source that requires it in toolkit/xre. r=mshal (944abe034f)
- Bug 1255655 - Heap-allocate _progname. r=froydnj. (3cce05ccaa)
- Bug 828704: Avoid duplicate -foreground argument when launching Firefox on OSX. r=mstange (2e5c12bdda)
- bug 1166759 - force annotateCrashReport arguments to be UTF-8. r=bsmedberg (5f2c30676a)
- Bug 1261751 - Problems with OS X Sandboxed TempDir and Rules. r=bobowen r=gcp (9ad9272b92)
2024-07-17 22:13:12 +08:00

466 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);
}
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