1/*
2 * Copyright (c) 2011 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 "bindings/v8/PageScriptDebugServer.h"
33
34
35#include "V8Window.h"
36#include "bindings/v8/ScriptController.h"
37#include "bindings/v8/ScriptSourceCode.h"
38#include "bindings/v8/V8Binding.h"
39#include "bindings/v8/V8ScriptRunner.h"
40#include "bindings/v8/V8WindowShell.h"
41#include "core/inspector/InspectorInstrumentation.h"
42#include "core/inspector/ScriptDebugListener.h"
43#include "core/frame/Frame.h"
44#include "core/page/Page.h"
45#include "wtf/OwnPtr.h"
46#include "wtf/PassOwnPtr.h"
47#include "wtf/StdLibExtras.h"
48#include "wtf/TemporaryChange.h"
49#include "wtf/text/StringBuilder.h"
50
51namespace WebCore {
52
53static Frame* retrieveFrameWithGlobalObjectCheck(v8::Handle<v8::Context> context)
54{
55    if (context.IsEmpty())
56        return 0;
57
58    // Test that context has associated global dom window object.
59    v8::Handle<v8::Object> global = context->Global();
60    if (global.IsEmpty())
61        return 0;
62
63    global = global->FindInstanceInPrototypeChain(V8Window::domTemplate(context->GetIsolate(), worldTypeInMainThread(context->GetIsolate())));
64    if (global.IsEmpty())
65        return 0;
66
67    return toFrameIfNotDetached(context);
68}
69
70void PageScriptDebugServer::setPreprocessorSource(const String& preprocessorSource)
71{
72    if (preprocessorSource.isEmpty())
73        m_preprocessorSourceCode.clear();
74    else
75        m_preprocessorSourceCode = adoptPtr(new ScriptSourceCode(preprocessorSource));
76    m_scriptPreprocessor.clear();
77}
78
79PageScriptDebugServer& PageScriptDebugServer::shared()
80{
81    DEFINE_STATIC_LOCAL(PageScriptDebugServer, server, ());
82    return server;
83}
84
85PageScriptDebugServer::PageScriptDebugServer()
86    : ScriptDebugServer(v8::Isolate::GetCurrent())
87    , m_pausedPage(0)
88{
89}
90
91void PageScriptDebugServer::addListener(ScriptDebugListener* listener, Page* page)
92{
93    ScriptController& scriptController = page->mainFrame()->script();
94    if (!scriptController.canExecuteScripts(NotAboutToExecuteScript))
95        return;
96
97    v8::HandleScope scope(m_isolate);
98    v8::Local<v8::Context> debuggerContext = v8::Debug::GetDebugContext();
99    v8::Context::Scope contextScope(debuggerContext);
100
101    v8::Local<v8::Object> debuggerScript = m_debuggerScript.newLocal(m_isolate);
102    if (!m_listenersMap.size()) {
103        ensureDebuggerScriptCompiled();
104        ASSERT(!debuggerScript->IsUndefined());
105        v8::Debug::SetDebugEventListener2(&PageScriptDebugServer::v8DebugEventCallback, v8::External::New(m_isolate, this));
106    }
107    m_listenersMap.set(page, listener);
108
109    V8WindowShell* shell = scriptController.existingWindowShell(mainThreadNormalWorld());
110    if (!shell || !shell->isContextInitialized())
111        return;
112    v8::Local<v8::Context> context = shell->context();
113    v8::Handle<v8::Function> getScriptsFunction = v8::Local<v8::Function>::Cast(debuggerScript->Get(v8AtomicString(m_isolate, "getScripts")));
114    v8::Handle<v8::Value> argv[] = { context->GetEmbedderData(0) };
115    v8::Handle<v8::Value> value = V8ScriptRunner::callInternalFunction(getScriptsFunction, debuggerScript, WTF_ARRAY_LENGTH(argv), argv, m_isolate);
116    if (value.IsEmpty())
117        return;
118    ASSERT(!value->IsUndefined() && value->IsArray());
119    v8::Handle<v8::Array> scriptsArray = v8::Handle<v8::Array>::Cast(value);
120    for (unsigned i = 0; i < scriptsArray->Length(); ++i)
121        dispatchDidParseSource(listener, v8::Handle<v8::Object>::Cast(scriptsArray->Get(v8::Integer::New(i, m_isolate))));
122}
123
124void PageScriptDebugServer::removeListener(ScriptDebugListener* listener, Page* page)
125{
126    if (!m_listenersMap.contains(page))
127        return;
128
129    if (m_pausedPage == page)
130        continueProgram();
131
132    m_listenersMap.remove(page);
133
134    if (m_listenersMap.isEmpty())
135        v8::Debug::SetDebugEventListener2(0);
136    // FIXME: Remove all breakpoints set by the agent.
137}
138
139void PageScriptDebugServer::setClientMessageLoop(PassOwnPtr<ClientMessageLoop> clientMessageLoop)
140{
141    m_clientMessageLoop = clientMessageLoop;
142}
143
144void PageScriptDebugServer::compileScript(ScriptState* state, const String& expression, const String& sourceURL, String* scriptId, String* exceptionMessage)
145{
146    ExecutionContext* executionContext = state->executionContext();
147    RefPtr<Frame> protect = toDocument(executionContext)->frame();
148    ScriptDebugServer::compileScript(state, expression, sourceURL, scriptId, exceptionMessage);
149    if (!scriptId->isNull())
150        m_compiledScriptURLs.set(*scriptId, sourceURL);
151}
152
153void PageScriptDebugServer::clearCompiledScripts()
154{
155    ScriptDebugServer::clearCompiledScripts();
156    m_compiledScriptURLs.clear();
157}
158
159void PageScriptDebugServer::runScript(ScriptState* state, const String& scriptId, ScriptValue* result, bool* wasThrown, String* exceptionMessage)
160{
161    String sourceURL = m_compiledScriptURLs.take(scriptId);
162
163    ExecutionContext* executionContext = state->executionContext();
164    Frame* frame = toDocument(executionContext)->frame();
165    InspectorInstrumentationCookie cookie;
166    if (frame)
167        cookie = InspectorInstrumentation::willEvaluateScript(frame, sourceURL, TextPosition::minimumPosition().m_line.oneBasedInt());
168
169    RefPtr<Frame> protect = frame;
170    ScriptDebugServer::runScript(state, scriptId, result, wasThrown, exceptionMessage);
171
172    if (frame)
173        InspectorInstrumentation::didEvaluateScript(cookie);
174}
175
176ScriptDebugListener* PageScriptDebugServer::getDebugListenerForContext(v8::Handle<v8::Context> context)
177{
178    v8::HandleScope scope(m_isolate);
179    Frame* frame = retrieveFrameWithGlobalObjectCheck(context);
180    if (!frame)
181        return 0;
182    return m_listenersMap.get(frame->page());
183}
184
185void PageScriptDebugServer::runMessageLoopOnPause(v8::Handle<v8::Context> context)
186{
187    v8::HandleScope scope(m_isolate);
188    Frame* frame = retrieveFrameWithGlobalObjectCheck(context);
189    m_pausedPage = frame->page();
190
191    // Wait for continue or step command.
192    m_clientMessageLoop->run(m_pausedPage);
193
194    // The listener may have been removed in the nested loop.
195    if (ScriptDebugListener* listener = m_listenersMap.get(m_pausedPage))
196        listener->didContinue();
197
198    m_pausedPage = 0;
199}
200
201void PageScriptDebugServer::quitMessageLoopOnPause()
202{
203    m_clientMessageLoop->quitNow();
204}
205
206void PageScriptDebugServer::preprocessBeforeCompile(const v8::Debug::EventDetails& eventDetails)
207{
208    v8::Handle<v8::Context> eventContext = eventDetails.GetEventContext();
209    Frame* frame = retrieveFrameWithGlobalObjectCheck(eventContext);
210    if (!frame)
211        return;
212
213    if (!canPreprocess(frame))
214        return;
215
216    v8::Handle<v8::Object> eventData = eventDetails.GetEventData();
217    v8::Local<v8::Context> debugContext = v8::Debug::GetDebugContext();
218    v8::Context::Scope contextScope(debugContext);
219    v8::TryCatch tryCatch;
220    // <script> tag source and attribute value source are preprocessed before we enter V8.
221    // Avoid preprocessing any internal scripts by processing only eval source in this V8 event handler.
222    v8::Handle<v8::Value> argvEventData[] = { eventData };
223    v8::Handle<v8::Value> v8Value = callDebuggerMethod("isEvalCompilation", WTF_ARRAY_LENGTH(argvEventData), argvEventData);
224    if (v8Value.IsEmpty() || !v8Value->ToBoolean()->Value())
225        return;
226
227    // The name and source are in the JS event data.
228    String scriptName = toCoreStringWithUndefinedOrNullCheck(callDebuggerMethod("getScriptName", WTF_ARRAY_LENGTH(argvEventData), argvEventData));
229    String script = toCoreStringWithUndefinedOrNullCheck(callDebuggerMethod("getScriptSource", WTF_ARRAY_LENGTH(argvEventData), argvEventData));
230
231    String preprocessedSource  = m_scriptPreprocessor->preprocessSourceCode(script, scriptName);
232
233    v8::Handle<v8::Value> argvPreprocessedScript[] = { eventData, v8String(debugContext->GetIsolate(), preprocessedSource) };
234    callDebuggerMethod("setScriptSource", WTF_ARRAY_LENGTH(argvPreprocessedScript), argvPreprocessedScript);
235}
236
237static bool isCreatingPreprocessor = false;
238
239bool PageScriptDebugServer::canPreprocess(Frame* frame)
240{
241    ASSERT(frame);
242
243    if (!m_preprocessorSourceCode || !frame->page() || isCreatingPreprocessor)
244        return false;
245
246    // We delay the creation of the preprocessor until just before the first JS from the
247    // Web page to ensure that the debugger's console initialization code has completed.
248    if (!m_scriptPreprocessor) {
249        TemporaryChange<bool> isPreprocessing(isCreatingPreprocessor, true);
250        m_scriptPreprocessor = adoptPtr(new ScriptPreprocessor(*m_preprocessorSourceCode.get(), frame->script(), frame->page()->console()));
251    }
252
253    if (m_scriptPreprocessor->isValid())
254        return true;
255
256    m_scriptPreprocessor.clear();
257    // Don't retry the compile if we fail one time.
258    m_preprocessorSourceCode.clear();
259    return false;
260}
261
262// Source to Source processing iff debugger enabled and it has loaded a preprocessor.
263PassOwnPtr<ScriptSourceCode> PageScriptDebugServer::preprocess(Frame* frame, const ScriptSourceCode& sourceCode)
264{
265    if (!canPreprocess(frame))
266        return PassOwnPtr<ScriptSourceCode>();
267
268    String preprocessedSource = m_scriptPreprocessor->preprocessSourceCode(sourceCode.source(), sourceCode.url());
269    return adoptPtr(new ScriptSourceCode(preprocessedSource, sourceCode.url()));
270}
271
272String PageScriptDebugServer::preprocessEventListener(Frame* frame, const String& source, const String& url, const String& functionName)
273{
274    if (!canPreprocess(frame))
275        return source;
276
277    return m_scriptPreprocessor->preprocessSourceCode(source, url, functionName);
278}
279
280} // namespace WebCore
281