#include "config.h"
#include "Watchdog.h"
#include "CallFrame.h"
#include <wtf/CurrentTime.h>
#include <wtf/MathExtras.h>
namespace JSC {
#define NO_LIMIT std::numeric_limits<double>::infinity()
Watchdog::Watchdog()
: m_timerDidFire(false)
, m_didFire(false)
, m_limit(NO_LIMIT)
, m_startTime(0)
, m_elapsedTime(0)
, m_reentryCount(0)
, m_isStopped(true)
, m_callback(0)
, m_callbackData1(0)
, m_callbackData2(0)
{
initTimer();
}
Watchdog::~Watchdog()
{
ASSERT(!isArmed());
stopCountdown();
destroyTimer();
}
void Watchdog::setTimeLimit(VM& vm, double limit,
ShouldTerminateCallback callback, void* data1, void* data2)
{
bool wasEnabled = isEnabled();
if (!m_isStopped)
stopCountdown();
m_didFire = false;
m_limit = limit;
m_callback = callback;
m_callbackData1 = data1;
m_callbackData2 = data2;
if (!wasEnabled) {
vm.releaseExecutableMemory();
}
startCountdownIfNeeded();
}
bool Watchdog::didFire(ExecState* exec)
{
if (m_didFire)
return true;
if (!m_timerDidFire)
return false;
m_timerDidFire = false;
stopCountdown();
double currentTime = currentCPUTime();
double deltaTime = currentTime - m_startTime;
double totalElapsedTime = m_elapsedTime + deltaTime;
if (totalElapsedTime > m_limit) {
bool needsTermination = !m_callback
|| m_callback(exec, m_callbackData1, m_callbackData2);
if (needsTermination) {
m_didFire = true;
return true;
}
startCountdownIfNeeded();
} else {
double remainingTime = m_limit - totalElapsedTime;
m_elapsedTime = totalElapsedTime;
m_startTime = currentTime;
startCountdown(remainingTime);
}
return false;
}
bool Watchdog::isEnabled()
{
return (m_limit != NO_LIMIT);
}
void Watchdog::fire()
{
m_didFire = true;
}
void Watchdog::arm()
{
m_reentryCount++;
if (m_reentryCount == 1)
startCountdownIfNeeded();
}
void Watchdog::disarm()
{
ASSERT(m_reentryCount > 0);
if (m_reentryCount == 1)
stopCountdown();
m_reentryCount--;
}
void Watchdog::startCountdownIfNeeded()
{
if (!m_isStopped)
return;
if (!isArmed())
return;
if (isEnabled()) {
m_elapsedTime = 0;
m_startTime = currentCPUTime();
startCountdown(m_limit);
}
}
void Watchdog::startCountdown(double limit)
{
ASSERT(m_isStopped);
m_isStopped = false;
startTimer(limit);
}
void Watchdog::stopCountdown()
{
if (m_isStopped)
return;
stopTimer();
m_isStopped = true;
}
Watchdog::Scope::Scope(Watchdog& watchdog)
: m_watchdog(watchdog)
{
m_watchdog.arm();
}
Watchdog::Scope::~Scope()
{
m_watchdog.disarm();
}
}