1/*
2 * Copyright (C) 2013-2017 Apple Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26#include "config.h"
27#include "Watchdog.h"
28
29#include "CallFrame.h"
30#include <wtf/CPUTime.h>
31#include <wtf/MathExtras.h>
32
33namespace JSC {
34
35Watchdog::Watchdog(VM* vm)
36 : m_vm(vm)
37 , m_timeLimit(noTimeLimit)
38 , m_cpuDeadline(noTimeLimit)
39 , m_deadline(MonotonicTime::infinity())
40 , m_callback(0)
41 , m_callbackData1(0)
42 , m_callbackData2(0)
43 , m_timerQueue(WorkQueue::create("jsc.watchdog.queue", WorkQueue::Type::Serial, WorkQueue::QOS::Utility))
44{
45}
46
47void Watchdog::setTimeLimit(Seconds limit,
48 ShouldTerminateCallback callback, void* data1, void* data2)
49{
50 ASSERT(m_vm->currentThreadIsHoldingAPILock());
51
52 m_timeLimit = limit;
53 m_callback = callback;
54 m_callbackData1 = data1;
55 m_callbackData2 = data2;
56
57 if (m_hasEnteredVM && hasTimeLimit())
58 startTimer(m_timeLimit);
59}
60
61bool Watchdog::shouldTerminate(JSGlobalObject* globalObject)
62{
63 ASSERT(m_vm->currentThreadIsHoldingAPILock());
64 if (MonotonicTime::now() < m_deadline)
65 return false; // Just a stale timer firing. Nothing to do.
66
67 // Set m_deadline to MonotonicTime::infinity() here so that we can reject all future
68 // spurious wakes.
69 m_deadline = MonotonicTime::infinity();
70
71 auto cpuTime = CPUTime::forCurrentThread();
72 if (cpuTime < m_cpuDeadline) {
73 auto remainingCPUTime = m_cpuDeadline - cpuTime;
74 startTimer(remainingCPUTime);
75 return false;
76 }
77
78 // Note: we should not be holding the lock while calling the callbacks. The callbacks may
79 // call setTimeLimit() which will try to lock as well.
80
81 // If m_callback is not set, then we terminate by default.
82 // Else, we let m_callback decide if we should terminate or not.
83 bool needsTermination = !m_callback
84 || m_callback(globalObject, m_callbackData1, m_callbackData2);
85 if (needsTermination)
86 return true;
87
88 // If we get here, then the callback above did not want to terminate execution. As a
89 // result, the callback may have done one of the following:
90 // 1. cleared the time limit (i.e. watchdog is disabled),
91 // 2. set a new time limit via Watchdog::setTimeLimit(), or
92 // 3. did nothing (i.e. allow another cycle of the current time limit).
93 //
94 // In the case of 1, we don't have to do anything.
95 // In the case of 2, Watchdog::setTimeLimit() would already have started the timer.
96 // In the case of 3, we need to re-start the timer here.
97
98 ASSERT(m_hasEnteredVM);
99 bool callbackAlreadyStartedTimer = (m_cpuDeadline != noTimeLimit);
100 if (hasTimeLimit() && !callbackAlreadyStartedTimer)
101 startTimer(m_timeLimit);
102
103 return false;
104}
105
106bool Watchdog::hasTimeLimit()
107{
108 return (m_timeLimit != noTimeLimit);
109}
110
111void Watchdog::enteredVM()
112{
113 m_hasEnteredVM = true;
114 if (hasTimeLimit())
115 startTimer(m_timeLimit);
116}
117
118void Watchdog::exitedVM()
119{
120 ASSERT(m_hasEnteredVM);
121 stopTimer();
122 m_hasEnteredVM = false;
123}
124
125void Watchdog::startTimer(Seconds timeLimit)
126{
127 ASSERT(m_hasEnteredVM);
128 ASSERT(m_vm->currentThreadIsHoldingAPILock());
129 ASSERT(hasTimeLimit());
130 ASSERT(timeLimit <= m_timeLimit);
131
132 m_cpuDeadline = CPUTime::forCurrentThread() + timeLimit;
133 auto now = MonotonicTime::now();
134 auto deadline = now + timeLimit;
135
136 if ((now < m_deadline) && (m_deadline <= deadline))
137 return; // Wait for the current active timer to expire before starting a new one.
138
139 // Else, the current active timer won't fire soon enough. So, start a new timer.
140 m_deadline = deadline;
141
142 // We need to ensure that the Watchdog outlives the timer.
143 // For the same reason, the timer may also outlive the VM that the Watchdog operates on.
144 // So, we always need to null check m_vm before using it. The VM will notify the Watchdog
145 // via willDestroyVM() before it goes away.
146 RefPtr<Watchdog> protectedThis = this;
147 m_timerQueue->dispatchAfter(timeLimit, [this, protectedThis] {
148 LockHolder locker(m_lock);
149 if (m_vm)
150 m_vm->notifyNeedWatchdogCheck();
151 });
152}
153
154void Watchdog::stopTimer()
155{
156 ASSERT(m_hasEnteredVM);
157 ASSERT(m_vm->currentThreadIsHoldingAPILock());
158 m_cpuDeadline = noTimeLimit;
159}
160
161void Watchdog::willDestroyVM(VM* vm)
162{
163 LockHolder locker(m_lock);
164 ASSERT_UNUSED(vm, m_vm == vm);
165 m_vm = nullptr;
166}
167
168} // namespace JSC
169