1/*
2 * Copyright (C) 2013 Google 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 are
6 * met:
7 *
8 *     * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 *     * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
13 * distribution.
14 *     * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31#include "config.h"
32#include "core/inspector/AsyncCallStackTracker.h"
33
34#include "core/dom/ContextLifecycleObserver.h"
35#include "core/dom/ExecutionContext.h"
36
37namespace WebCore {
38
39class AsyncCallStackTracker::ExecutionContextData : public ContextLifecycleObserver {
40    WTF_MAKE_FAST_ALLOCATED;
41public:
42    ExecutionContextData(AsyncCallStackTracker* tracker, ExecutionContext* executionContext)
43        : ContextLifecycleObserver(executionContext)
44        , m_tracker(tracker)
45    {
46    }
47
48    virtual void contextDestroyed() OVERRIDE
49    {
50        m_tracker->contextDestroyed(executionContext());
51        ContextLifecycleObserver::contextDestroyed();
52    }
53
54private:
55    friend class AsyncCallStackTracker;
56    AsyncCallStackTracker* m_tracker;
57    HashSet<int> m_intervalTimerIds;
58    HashMap<int, RefPtr<AsyncCallChain> > m_timerCallChains;
59    HashMap<int, RefPtr<AsyncCallChain> > m_animationFrameCallChains;
60};
61
62AsyncCallStackTracker::AsyncCallStack::AsyncCallStack(const String& description, const ScriptValue& callFrames)
63    : m_description(description)
64    , m_callFrames(callFrames)
65{
66}
67
68AsyncCallStackTracker::AsyncCallStack::~AsyncCallStack()
69{
70}
71
72AsyncCallStackTracker::AsyncCallStackTracker()
73    : m_maxAsyncCallStackDepth(0)
74{
75}
76
77void AsyncCallStackTracker::setAsyncCallStackDepth(int depth)
78{
79    if (depth <= 0) {
80        m_maxAsyncCallStackDepth = 0;
81        clear();
82    } else {
83        m_maxAsyncCallStackDepth = depth;
84    }
85}
86
87const AsyncCallStackTracker::AsyncCallChain* AsyncCallStackTracker::currentAsyncCallChain() const
88{
89    if (m_currentAsyncCallChain)
90        ensureMaxAsyncCallChainDepth(m_currentAsyncCallChain.get(), m_maxAsyncCallStackDepth);
91    return m_currentAsyncCallChain.get();
92}
93
94void AsyncCallStackTracker::didInstallTimer(ExecutionContext* context, int timerId, bool singleShot, const ScriptValue& callFrames)
95{
96    DEFINE_STATIC_LOCAL(String, setTimeoutName, ("setTimeout"));
97    DEFINE_STATIC_LOCAL(String, setIntervalName, ("setInterval"));
98
99    ASSERT(context);
100    ASSERT(isEnabled());
101    if (!validateCallFrames(callFrames))
102        return;
103    ASSERT(timerId > 0);
104    ExecutionContextData* data = createContextDataIfNeeded(context);
105    data->m_timerCallChains.set(timerId, createAsyncCallChain(singleShot ? setTimeoutName : setIntervalName, callFrames));
106    if (!singleShot)
107        data->m_intervalTimerIds.add(timerId);
108}
109
110void AsyncCallStackTracker::didRemoveTimer(ExecutionContext* context, int timerId)
111{
112    ASSERT(context);
113    if (!isEnabled() || timerId <= 0)
114        return;
115    ExecutionContextData* data = m_executionContextDataMap.get(context);
116    if (!data)
117        return;
118    data->m_intervalTimerIds.remove(timerId);
119    data->m_timerCallChains.remove(timerId);
120}
121
122void AsyncCallStackTracker::willFireTimer(ExecutionContext* context, int timerId)
123{
124    ASSERT(context);
125    if (!isEnabled())
126        return;
127    ASSERT(timerId > 0);
128    ASSERT(!m_currentAsyncCallChain);
129    ExecutionContextData* data = m_executionContextDataMap.get(context);
130    if (!data)
131        return;
132    if (data->m_intervalTimerIds.contains(timerId))
133        m_currentAsyncCallChain = data->m_timerCallChains.get(timerId);
134    else
135        m_currentAsyncCallChain = data->m_timerCallChains.take(timerId);
136}
137
138void AsyncCallStackTracker::didRequestAnimationFrame(ExecutionContext* context, int callbackId, const ScriptValue& callFrames)
139{
140    DEFINE_STATIC_LOCAL(String, requestAnimationFrameName, ("requestAnimationFrame"));
141
142    ASSERT(context);
143    ASSERT(isEnabled());
144    if (!validateCallFrames(callFrames))
145        return;
146    ASSERT(callbackId > 0);
147    ExecutionContextData* data = createContextDataIfNeeded(context);
148    data->m_animationFrameCallChains.set(callbackId, createAsyncCallChain(requestAnimationFrameName, callFrames));
149}
150
151void AsyncCallStackTracker::didCancelAnimationFrame(ExecutionContext* context, int callbackId)
152{
153    ASSERT(context);
154    if (!isEnabled() || callbackId <= 0)
155        return;
156    if (ExecutionContextData* data = m_executionContextDataMap.get(context))
157        data->m_animationFrameCallChains.remove(callbackId);
158}
159
160void AsyncCallStackTracker::willFireAnimationFrame(ExecutionContext* context, int callbackId)
161{
162    ASSERT(context);
163    if (!isEnabled())
164        return;
165    ASSERT(callbackId > 0);
166    ASSERT(!m_currentAsyncCallChain);
167    if (ExecutionContextData* data = m_executionContextDataMap.get(context))
168        m_currentAsyncCallChain = data->m_animationFrameCallChains.take(callbackId);
169}
170
171void AsyncCallStackTracker::didFireAsyncCall()
172{
173    m_currentAsyncCallChain = 0;
174}
175
176PassRefPtr<AsyncCallStackTracker::AsyncCallChain> AsyncCallStackTracker::createAsyncCallChain(const String& description, const ScriptValue& callFrames)
177{
178    ASSERT(isEnabled());
179    RefPtr<AsyncCallChain> chain = adoptRef(m_currentAsyncCallChain ? new AsyncCallStackTracker::AsyncCallChain(*m_currentAsyncCallChain) : new AsyncCallStackTracker::AsyncCallChain());
180    ensureMaxAsyncCallChainDepth(chain.get(), m_maxAsyncCallStackDepth - 1);
181    chain->m_callStacks.prepend(adoptRef(new AsyncCallStackTracker::AsyncCallStack(description, callFrames)));
182    return chain.release();
183}
184
185void AsyncCallStackTracker::ensureMaxAsyncCallChainDepth(AsyncCallChain* chain, unsigned maxDepth)
186{
187    while (chain->m_callStacks.size() > maxDepth)
188        chain->m_callStacks.removeLast();
189}
190
191bool AsyncCallStackTracker::validateCallFrames(const ScriptValue& callFrames)
192{
193    return !callFrames.hasNoValue();
194}
195
196void AsyncCallStackTracker::contextDestroyed(ExecutionContext* context)
197{
198    ASSERT(context);
199    if (ExecutionContextData* data = m_executionContextDataMap.take(context))
200        delete data;
201}
202
203AsyncCallStackTracker::ExecutionContextData* AsyncCallStackTracker::createContextDataIfNeeded(ExecutionContext* context)
204{
205    ExecutionContextData* data = m_executionContextDataMap.get(context);
206    if (!data) {
207        data = new AsyncCallStackTracker::ExecutionContextData(this, context);
208        m_executionContextDataMap.set(context, data);
209    }
210    return data;
211}
212
213void AsyncCallStackTracker::clear()
214{
215    m_currentAsyncCallChain = 0;
216    Vector<ExecutionContextData*> contextsData;
217    copyValuesToVector(m_executionContextDataMap, contextsData);
218    m_executionContextDataMap.clear();
219    for (Vector<ExecutionContextData*>::const_iterator it = contextsData.begin(); it != contextsData.end(); ++it)
220        delete *it;
221}
222
223} // namespace WebCore
224