Files
palemoon27/xpcom/threads/HangMonitor.cpp
T
roytam1 5a3b3d60eb import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1173260 - stub out tests that fail when 'cursive' is looked up via fontconfig. r=m_kato (0bb3f03cb8)
- bug 1215657 - make AccessibleWrap::get_accDefaultAction work with proxied accessibles r=davidb (5732eb38eb)
- Bug 1210549 - Allow IServiceProvider::QueryService to work for proxied accessibles r=tbsaunde (7dcd9c2271)
- bug 1215657 - make AccessibleWrap::accSelect work with proxies r=davidb (d52e3d4873)
- Bug 1225682 - Don't use nsAuto{,C}String as class member variables in rdf/. r=Pike (f681938445)
- Bug 1232454 - use UniquePtr<T[]> instead of nsAutoArrayPtr<T> in security/apps/; r=keeler (e416936ed6)
- Bug 1235796 - Allow allocating YCbCr textures with Cb/Cr planes bigger than the Y plane. r=jrmuizel (8f1dbe137c)
- Bug 1241816 - In CreateSourceSurfaceFromMacIOSurface, unlock the IOSurface even in failure cases. r=mattwoodrow (218e6da6c1)
- Bug 1240190 - Add D3D9 texture upload profiler labels. r=jrmuizel (1e55b77bdf)
- Bug 1213429 - Recycle e10s D3D9 textures and add partial upload support. r=Bas (97aeeefdd2)
- Bug 1213429 - Check the result of LockRect. r=Bas (1c3c981d80)
- Bug 1213429 - GCC compilation fixup. (5449005c99)
- Lazily initialize D3D11 mix-blend shaders. (bug 1246388, r=mattwoodrow) (6fd3226030)
- Bug 1237375: Add some more extensive debugging information. r=milan (aed95e4774)
- Bug 1239861. Part 2 Properly resize DXGI swap chain buffer size. r=bas (e9bf410de4)
- Bug 1247775 - Part 1: Remove D3D10/D2D 1.0 texture integration from layers. r=dvander (74d7e93792)
- Bug 1247775 - Part 2: Remove Direct2D 1.0 code from Thebes. r=dvander (f0a1f53917)
- Bug 1247775 - Part 3: Remove Moz2D code to support Direct2D 1.0. r=dvander (10d27128eb)
- Bug 1221656 - Copy mp4parse.h in update-rust.sh. r=kinetik (96ebce3eb8)
- Bug 868333 - Match more MP4 family file types in media sniffer. r=rillian (cd29bd2a74)
- Bug 1211802 - Recognize 'avc?' as mp4 video. r=jya (b68726705b)
- Bug 1244523: [mp4] P2. Have sniffer recognise ftyp qt subtype. r=cpearce (1770f0862b)
- Bug 1087488: Remove some SPROP macro usages in Omnijar.cpp, to avoid triggering -Wtautological-compare clang warning. r=glandium (697dfa9895)
- Bug 1228437 - Add BHR stats from e10s child process. B2G fix by Ting-Yu Chou. r=nchen (213fbb9f37)
- Bug 1198196 - rework EVENTLOOP_UI_LAG_EXP_MS to record all lag. r=vladan (2807460ce0)
- Bug 1240484 - fixed control flow patch issue by adding brackets. r=mccr8 (d2aac14ee1)
- Bug 1242119 - Remove early exit in WinXP debug content processes. r=froydnj (2c2626a1ea)
- Bug 1245513 - Use _exit(0) to exit in B2G debug content processes. r=froydnj (c37efd34d9)
- some crash and profiler stuff (87547f6d8f)
- bug 1234417 - fix a leak in CreateECPublicKey r=rbarnes (99848f0fae)
- Bug 1204784: Handle cases in nsThreadPool where Gecko doesn't own the thread that we're running on. r=froydnj (3f523fc544)
- Bug 1204784: Do not shut the main thread down before all outstanding asynchronous thread shutdowns complete. r=froydnj (6abfb2562f)
- Bug 1234126 - Add Chaos Mode support for setting thread affinity on OS X and Windows. r=froydnj (8811430596)
- Bug 1245586 - add debugging aids for thread shutdown; r=khuey (28b7ae88c3)
- Bug 1191936 - Implement SPKI/PKCS#8/JWK import/export for RSA-PSS r=rbarnes (212ab7fec5)
- Bug 1241757 - Permit export of JWK with empty key_ops field, r=rbarnes (b19f177a13)
- Bug 1205168 - Part 0: Remove copy-ctor from strong type. r=jgilbert (a6070322a1)
- Bug 1205168 - Part 1 - Sort all the WebGLTexelFormats. r=jgilbert (857cd58641)
- Bug 1205168 - Part 2: Texel Conversion - RG8 format. r=jgilbert (6c241194ed)
- Bug 1205168 - Part 3: Texel Conversion - RG16F format. r=jgilbert (7573635218)
- Bug 1205168 - Part 4: Texel Conversion - RG32F format. r=jgilbert (f54343317e)
- Bug 1205168 - Part 5: Texel Conversion - RGB11F11F10F format. r=jgilbert (500514e025)
- Bug 1205168 - Part 6: Fix TexImage2D and TexSubImage2D with texture conversion. r=jgilbert (b5e2e75276)
- Bug 1205168 - Part 7: Remove unneeded functions. r=jgilbert (9bd24cd813)
- Bug 1234744 - Fix build errors in ImageBitmap.h. r=roc (b4b67e5905)
- missing telemetry bits (28161fd3f9)
- Bug 1237193 - Fix WebGL getActiveUniforms return type. r=jgilbert, r=smaug (f9a37a360e)
- Bug 1233353 - Initialize rb correctly if rb bind to READ_FRAMEBUFFER. r=jgilbert (bbc77437a4)
- Bug 1237637 - Disallow negative levels for framebuffer attachments. -r=jrmuizel (fa65b6ad24)
- Bug 1236395 - [WebGL2] pass getFramebufferAttachmentParameter in gl-object-get-calls.html, r=jgilbert (6f9fde1cd2)
- Bug 1236784 - [WebGL2] pass getRenderbufferParameter in gl-object-get-calls.html, r=jgilbert (e4f20f54ad)
- Bug 1238865 - Part 1: Validate attachments before clearBuffer. r=jgilbert (a6e6e05a0c)
- Bug 1229210. Handle the new formats required by WebGL2 in ReadPixels. r=jgilbert (66e305f97d)
- Bug 1238865 - Part 2: Add more format/type checks for WebGL2. r=jgilbert (af629782b3)
- Bug 1238865 - Part 3: Prevent IMPLEMENTATION_COLOR_READ_FORMAT return SRGB_ALPHA. r=jgilbert (81da93d791)
- Bug 1240673 - Fix WebGL2 framebuffer parameter problem. r=jgilbert (2c957a8294)
- Bug 1240438 - Fix WebGL2 framebuffer attachment related implementation. r=jgilbert (b4339241c8)
- Bug 1239187 - Use the GLFeature instead. - r=jrmuizel (c5f2c57646)
- Bug 1094458 - Implement RenderbufferStorageMultisample. - r=jrmuizel (f20f776597)
- Bug 1246007 - Ignore RENDERBUFFER_SAMPLES outside of webgl2. - r=jrmuizel (6b8f59ae49)
- Bug 1243907 - Don't query _BITS enums on Core profiles. - r=jrmuizel (e722abe45b)
- partial Bug 1242120 - Remove switch fallthrough (0f47fb7a71)
- Bug 1236080. Null check format in GetParameter. r=jgilbert (09fedc2ea8)
- Bug 1240662 - Add max level check for framebufferTextureLayer. r=jgilbert (f6d5eda15c)
- Bug 1236091. Move validate checks inside of null checks. r=jgilbert (4c67e04e87)
- Bug 1237191 - Add check for getQueryParameter to return correct error. r=jgilbert (93345aab7e)
- Bug 1230089 - If sampler is bound, use parameter of sampler. r=jgilbert (e4139a5174)
- Bug 1242336 - Fix WebGL2 return type of GL_UNPACK_SKIP. r=jgilbert (4a2ef1956e)
- Bug 1240262 - Annotate intentional switch fallthrough and suppress -Wimplicit-fallthrough warnings in dom/canvas/. r=jgilbert (eaee57ba8f)
- Bug 1237194 - Fix getSyncParameter return error. r=jgilbert (13119be06e)
- Bug 1239541 - Fix WebGL2 texImage related checking. r=jgilbert (6777244db0)
- Bug 1225291 - IsTransformFeedback doesn't report error when input is null. r=jgilbert (8c67d072b5)
- Bug 1233094. Handle null buffers in GetIndexedParameter. r=jgilbert (ae5d75bd47)
- Bug 1228676 - WebGL2 VertexAttrib funcs should match WebGL 1 patterns. - r=jgilbert (bf96c0e17b)
- Bug 1237420 - "Fix length-checking when setting WebGL 2 vertex attributes with an array". r=jgilbert (d8e9ca7111)
- Bug 1233819 - Fix WebGL on WinXP. - r=jrmuizel (39b15ba9ee)
- Bug 1233046 - Mark non-try platforms. Align some tests. (9d16ce70a4)
- Bug 1201885,1247752,1247753 - Re-mark passing/failing tests. (381c71c0f8)
- Bug 1247764 - Disable STENCIL_TEST on mac+intel when not needed. - r=jrmuizel (0b544d0c36)
- Bug 1243908 - Use DrawBuffers through GLScreenBuffer when operating on fb0. - r=jrmuizel (0ac0fc6047)
- Bug 1229944 - Add glClear for zeroing texture data. - r=kamidphish (51df8cbb50)
- Bug 1220450 - Clear length on cache OOM. r=kamidphish (44431a0d3e)
- Bug 1232346 - Clarify ResolveForDraw's failure checking. - r=kamidphish (542917bb85)
2024-01-11 09:39:33 +08:00

569 lines
16 KiB
C++

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* 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 "mozilla/HangMonitor.h"
#include "mozilla/Atomics.h"
#include "mozilla/BackgroundHangMonitor.h"
#include "mozilla/Monitor.h"
#include "mozilla/Preferences.h"
#include "mozilla/ProcessedStack.h"
#include "mozilla/Telemetry.h"
#include "mozilla/StaticPtr.h"
#include "mozilla/UniquePtr.h"
#include "nsReadableUtils.h"
#include "mozilla/StackWalk.h"
#include "nsThreadUtils.h"
#include "nsXULAppAPI.h"
#ifdef MOZ_CRASHREPORTER
#include "nsExceptionHandler.h"
#endif
#ifdef MOZ_NUWA_PROCESS
#include "ipc/Nuwa.h"
#endif
#ifdef XP_WIN
#include <windows.h>
#endif
#if defined(MOZ_ENABLE_PROFILER_SPS) && defined(MOZ_PROFILING) && defined(XP_WIN)
#define REPORT_CHROME_HANGS
#endif
namespace mozilla {
namespace HangMonitor {
/**
* A flag which may be set from within a debugger to disable the hang
* monitor.
*/
volatile bool gDebugDisableHangMonitor = false;
const char kHangMonitorPrefName[] = "hangmonitor.timeout";
#ifdef REPORT_CHROME_HANGS
const char kTelemetryPrefName[] = "toolkit.telemetry.enabled";
#endif
// Monitor protects gShutdown and gTimeout, but not gTimestamp which rely on
// being atomically set by the processor; synchronization doesn't really matter
// in this use case.
Monitor* gMonitor;
// The timeout preference, in seconds.
int32_t gTimeout;
PRThread* gThread;
// Set when shutdown begins to signal the thread to exit immediately.
bool gShutdown;
// The timestamp of the last event notification, or PR_INTERVAL_NO_WAIT if
// we're currently not processing events.
Atomic<PRIntervalTime> gTimestamp(PR_INTERVAL_NO_WAIT);
#ifdef REPORT_CHROME_HANGS
// Main thread ID used in reporting chrome hangs under Windows
static HANDLE winMainThreadHandle = nullptr;
// Default timeout for reporting chrome hangs to Telemetry (5 seconds)
static const int32_t DEFAULT_CHROME_HANG_INTERVAL = 5;
// Maximum number of PCs to gather from the stack
static const int32_t MAX_CALL_STACK_PCS = 400;
#endif
// PrefChangedFunc
void
PrefChanged(const char*, void*)
{
int32_t newval = Preferences::GetInt(kHangMonitorPrefName);
#ifdef REPORT_CHROME_HANGS
// Monitor chrome hangs on the profiling branch if Telemetry enabled
if (newval == 0) {
bool telemetryEnabled = Preferences::GetBool(kTelemetryPrefName);
if (telemetryEnabled) {
newval = DEFAULT_CHROME_HANG_INTERVAL;
}
}
#endif
MonitorAutoLock lock(*gMonitor);
if (newval != gTimeout) {
gTimeout = newval;
lock.Notify();
}
}
void
Crash()
{
if (gDebugDisableHangMonitor) {
return;
}
#ifdef XP_WIN
if (::IsDebuggerPresent()) {
return;
}
#endif
#ifdef MOZ_CRASHREPORTER
// If you change this, you must also deal with the threadsafety of AnnotateCrashReport in
// non-chrome processes!
if (GeckoProcessType_Default == XRE_GetProcessType()) {
CrashReporter::AnnotateCrashReport(NS_LITERAL_CSTRING("Hang"),
NS_LITERAL_CSTRING("1"));
}
#endif
NS_RUNTIMEABORT("HangMonitor triggered");
}
#ifdef REPORT_CHROME_HANGS
class ChromeHangAnnotations : public HangAnnotations
{
public:
ChromeHangAnnotations();
~ChromeHangAnnotations();
void AddAnnotation(const nsAString& aName, const int32_t aData) override;
void AddAnnotation(const nsAString& aName, const double aData) override;
void AddAnnotation(const nsAString& aName, const nsAString& aData) override;
void AddAnnotation(const nsAString& aName, const nsACString& aData) override;
void AddAnnotation(const nsAString& aName, const bool aData) override;
size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const override;
bool IsEmpty() const override;
bool GetEnumerator(Enumerator** aOutEnum) override;
typedef std::pair<nsString, nsString> AnnotationType;
typedef std::vector<AnnotationType> VectorType;
typedef VectorType::const_iterator IteratorType;
private:
VectorType mAnnotations;
};
ChromeHangAnnotations::ChromeHangAnnotations()
{
MOZ_COUNT_CTOR(ChromeHangAnnotations);
}
ChromeHangAnnotations::~ChromeHangAnnotations()
{
MOZ_COUNT_DTOR(ChromeHangAnnotations);
}
void
ChromeHangAnnotations::AddAnnotation(const nsAString& aName, const int32_t aData)
{
nsString dataString;
dataString.AppendInt(aData);
AnnotationType annotation = std::make_pair(nsString(aName), dataString);
mAnnotations.push_back(annotation);
}
void
ChromeHangAnnotations::AddAnnotation(const nsAString& aName, const double aData)
{
nsString dataString;
dataString.AppendFloat(aData);
AnnotationType annotation = std::make_pair(nsString(aName), dataString);
mAnnotations.push_back(annotation);
}
void
ChromeHangAnnotations::AddAnnotation(const nsAString& aName, const nsAString& aData)
{
AnnotationType annotation = std::make_pair(nsString(aName), nsString(aData));
mAnnotations.push_back(annotation);
}
void
ChromeHangAnnotations::AddAnnotation(const nsAString& aName, const nsACString& aData)
{
nsString dataString;
AppendUTF8toUTF16(aData, dataString);
AnnotationType annotation = std::make_pair(nsString(aName), dataString);
mAnnotations.push_back(annotation);
}
void
ChromeHangAnnotations::AddAnnotation(const nsAString& aName, const bool aData)
{
nsString dataString;
dataString += aData ? NS_LITERAL_STRING("true") : NS_LITERAL_STRING("false");
AnnotationType annotation = std::make_pair(nsString(aName), dataString);
mAnnotations.push_back(annotation);
}
/**
* This class itself does not use synchronization but it (and its parent object)
* should be protected by mutual exclusion in some way. In Telemetry the chrome
* hang data is protected via TelemetryImpl::mHangReportsMutex.
*/
class ChromeHangAnnotationEnumerator : public HangAnnotations::Enumerator
{
public:
ChromeHangAnnotationEnumerator(const ChromeHangAnnotations::VectorType& aAnnotations);
~ChromeHangAnnotationEnumerator();
virtual bool Next(nsAString& aOutName, nsAString& aOutValue);
private:
ChromeHangAnnotations::IteratorType mIterator;
ChromeHangAnnotations::IteratorType mEnd;
};
ChromeHangAnnotationEnumerator::ChromeHangAnnotationEnumerator(
const ChromeHangAnnotations::VectorType& aAnnotations)
: mIterator(aAnnotations.begin())
, mEnd(aAnnotations.end())
{
MOZ_COUNT_CTOR(ChromeHangAnnotationEnumerator);
}
ChromeHangAnnotationEnumerator::~ChromeHangAnnotationEnumerator()
{
MOZ_COUNT_DTOR(ChromeHangAnnotationEnumerator);
}
bool
ChromeHangAnnotationEnumerator::Next(nsAString& aOutName, nsAString& aOutValue)
{
aOutName.Truncate();
aOutValue.Truncate();
if (mIterator == mEnd) {
return false;
}
aOutName = mIterator->first;
aOutValue = mIterator->second;
++mIterator;
return true;
}
bool
ChromeHangAnnotations::IsEmpty() const
{
return mAnnotations.empty();
}
size_t
ChromeHangAnnotations::SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const
{
size_t result = sizeof(mAnnotations) +
mAnnotations.capacity() * sizeof(AnnotationType);
for (IteratorType i = mAnnotations.begin(), e = mAnnotations.end(); i != e;
++i) {
result += i->first.SizeOfExcludingThisIfUnshared(aMallocSizeOf);
result += i->second.SizeOfExcludingThisIfUnshared(aMallocSizeOf);
}
return result;
}
bool
ChromeHangAnnotations::GetEnumerator(HangAnnotations::Enumerator** aOutEnum)
{
if (!aOutEnum) {
return false;
}
*aOutEnum = nullptr;
if (mAnnotations.empty()) {
return false;
}
*aOutEnum = new ChromeHangAnnotationEnumerator(mAnnotations);
return true;
}
static void
ChromeStackWalker(uint32_t aFrameNumber, void* aPC, void* aSP, void* aClosure)
{
MOZ_ASSERT(aClosure);
std::vector<uintptr_t>* stack =
static_cast<std::vector<uintptr_t>*>(aClosure);
if (stack->size() == MAX_CALL_STACK_PCS) {
return;
}
MOZ_ASSERT(stack->size() < MAX_CALL_STACK_PCS);
stack->push_back(reinterpret_cast<uintptr_t>(aPC));
}
static void
GetChromeHangReport(Telemetry::ProcessedStack& aStack,
int32_t& aSystemUptime,
int32_t& aFirefoxUptime)
{
MOZ_ASSERT(winMainThreadHandle);
// The thread we're about to suspend might have the alloc lock
// so allocate ahead of time
std::vector<uintptr_t> rawStack;
rawStack.reserve(MAX_CALL_STACK_PCS);
DWORD ret = ::SuspendThread(winMainThreadHandle);
if (ret == -1) {
return;
}
MozStackWalk(ChromeStackWalker, /* skipFrames */ 0, /* maxFrames */ 0,
reinterpret_cast<void*>(&rawStack),
reinterpret_cast<uintptr_t>(winMainThreadHandle), nullptr);
ret = ::ResumeThread(winMainThreadHandle);
if (ret == -1) {
return;
}
aStack = Telemetry::GetStackAndModules(rawStack);
// Record system uptime (in minutes) at the time of the hang
aSystemUptime = ((GetTickCount() / 1000) - (gTimeout * 2)) / 60;
// Record Firefox uptime (in minutes) at the time of the hang
bool error;
TimeStamp processCreation = TimeStamp::ProcessCreation(error);
if (!error) {
TimeDuration td = TimeStamp::Now() - processCreation;
aFirefoxUptime = (static_cast<int32_t>(td.ToSeconds()) - (gTimeout * 2)) / 60;
} else {
aFirefoxUptime = -1;
}
}
#endif
void
ThreadMain(void*)
{
PR_SetCurrentThreadName("Hang Monitor");
#ifdef MOZ_NUWA_PROCESS
if (IsNuwaProcess()) {
NuwaMarkCurrentThread(nullptr, nullptr);
}
#endif
MonitorAutoLock lock(*gMonitor);
// In order to avoid issues with the hang monitor incorrectly triggering
// during a general system stop such as sleeping, the monitor thread must
// run twice to trigger hang protection.
PRIntervalTime lastTimestamp = 0;
int waitCount = 0;
#ifdef REPORT_CHROME_HANGS
Telemetry::ProcessedStack stack;
int32_t systemUptime = -1;
int32_t firefoxUptime = -1;
UniquePtr<HangAnnotations> annotations;
#endif
while (true) {
if (gShutdown) {
return; // Exit the thread
}
// avoid rereading the volatile value in this loop
PRIntervalTime timestamp = gTimestamp;
PRIntervalTime now = PR_IntervalNow();
if (timestamp != PR_INTERVAL_NO_WAIT &&
now < timestamp) {
// 32-bit overflow, reset for another waiting period
timestamp = 1; // lowest legal PRInterval value
}
if (timestamp != PR_INTERVAL_NO_WAIT &&
timestamp == lastTimestamp &&
gTimeout > 0) {
++waitCount;
#ifdef REPORT_CHROME_HANGS
// Capture the chrome-hang stack + Firefox & system uptimes after
// the minimum hang duration has been reached (not when the hang ends)
if (waitCount == 2) {
GetChromeHangReport(stack, systemUptime, firefoxUptime);
annotations = ChromeHangAnnotatorCallout();
}
#else
// This is the crash-on-hang feature.
// See bug 867313 for the quirk in the waitCount comparison
if (waitCount >= 2) {
int32_t delay =
int32_t(PR_IntervalToSeconds(now - timestamp));
if (delay >= gTimeout) {
MonitorAutoUnlock unlock(*gMonitor);
Crash();
}
}
#endif
} else {
#ifdef REPORT_CHROME_HANGS
if (waitCount >= 2) {
uint32_t hangDuration = PR_IntervalToSeconds(now - lastTimestamp);
Telemetry::RecordChromeHang(hangDuration, stack, systemUptime,
firefoxUptime, Move(annotations));
stack.Clear();
}
#endif
lastTimestamp = timestamp;
waitCount = 0;
}
PRIntervalTime timeout;
if (gTimeout <= 0) {
timeout = PR_INTERVAL_NO_TIMEOUT;
} else {
timeout = PR_MillisecondsToInterval(gTimeout * 500);
}
lock.Wait(timeout);
}
}
void
Startup()
{
if (GeckoProcessType_Default != XRE_GetProcessType() &&
GeckoProcessType_Content != XRE_GetProcessType()) {
return;
}
MOZ_ASSERT(!gMonitor, "Hang monitor already initialized");
gMonitor = new Monitor("HangMonitor");
Preferences::RegisterCallback(PrefChanged, kHangMonitorPrefName, nullptr);
PrefChanged(nullptr, nullptr);
#ifdef REPORT_CHROME_HANGS
Preferences::RegisterCallback(PrefChanged, kTelemetryPrefName, nullptr);
winMainThreadHandle =
OpenThread(THREAD_ALL_ACCESS, FALSE, GetCurrentThreadId());
if (!winMainThreadHandle) {
return;
}
#endif
// Don't actually start measuring hangs until we hit the main event loop.
// This potentially misses a small class of really early startup hangs,
// but avoids dealing with some xpcshell tests and other situations which
// start XPCOM but don't ever start the event loop.
Suspend();
gThread = PR_CreateThread(PR_USER_THREAD,
ThreadMain,
nullptr, PR_PRIORITY_LOW, PR_GLOBAL_THREAD,
PR_JOINABLE_THREAD, 0);
}
void
Shutdown()
{
if (GeckoProcessType_Default != XRE_GetProcessType() &&
GeckoProcessType_Content != XRE_GetProcessType()) {
return;
}
MOZ_ASSERT(gMonitor, "Hang monitor not started");
{
// Scope the lock we're going to delete later
MonitorAutoLock lock(*gMonitor);
gShutdown = true;
lock.Notify();
}
// thread creation could theoretically fail
if (gThread) {
PR_JoinThread(gThread);
gThread = nullptr;
}
delete gMonitor;
gMonitor = nullptr;
}
static bool
IsUIMessageWaiting()
{
#ifndef XP_WIN
return false;
#else
#define NS_WM_IMEFIRST WM_IME_SETCONTEXT
#define NS_WM_IMELAST WM_IME_KEYUP
BOOL haveUIMessageWaiting = FALSE;
MSG msg;
haveUIMessageWaiting |= ::PeekMessageW(&msg, nullptr, WM_KEYFIRST,
WM_IME_KEYLAST, PM_NOREMOVE);
haveUIMessageWaiting |= ::PeekMessageW(&msg, nullptr, NS_WM_IMEFIRST,
NS_WM_IMELAST, PM_NOREMOVE);
haveUIMessageWaiting |= ::PeekMessageW(&msg, nullptr, WM_MOUSEFIRST,
WM_MOUSELAST, PM_NOREMOVE);
return haveUIMessageWaiting;
#endif
}
void
NotifyActivity(ActivityType aActivityType)
{
MOZ_ASSERT(NS_IsMainThread(),
"HangMonitor::Notify called from off the main thread.");
// Determine the activity type more specifically
if (aActivityType == kGeneralActivity) {
aActivityType = IsUIMessageWaiting() ? kActivityUIAVail :
kActivityNoUIAVail;
}
// Calculate the cumulative amount of lag time since the last UI message
static uint32_t cumulativeUILagMS = 0;
switch (aActivityType) {
case kActivityNoUIAVail:
cumulativeUILagMS = 0;
break;
case kActivityUIAVail:
case kUIActivity:
if (gTimestamp != PR_INTERVAL_NO_WAIT) {
cumulativeUILagMS += PR_IntervalToMilliseconds(PR_IntervalNow() -
gTimestamp);
}
break;
default:
break;
}
// This is not a locked activity because PRTimeStamp is a 32-bit quantity
// which can be read/written atomically, and we don't want to pay locking
// penalties here.
gTimestamp = PR_IntervalNow();
// If we have UI activity we should reset the timer and report it
if (aActivityType == kUIActivity) {
mozilla::Telemetry::Accumulate(mozilla::Telemetry::EVENTLOOP_UI_ACTIVITY_EXP_MS,
cumulativeUILagMS);
cumulativeUILagMS = 0;
}
if (gThread && !gShutdown) {
mozilla::BackgroundHangMonitor().NotifyActivity();
}
}
void
Suspend()
{
MOZ_ASSERT(NS_IsMainThread(),
"HangMonitor::Suspend called from off the main thread.");
// Because gTimestamp changes this resets the wait count.
gTimestamp = PR_INTERVAL_NO_WAIT;
if (gThread && !gShutdown) {
mozilla::BackgroundHangMonitor().NotifyWait();
}
}
} // namespace HangMonitor
} // namespace mozilla