Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / bindings / v8 / V8LazyEventListener.cpp
1 /*
2  * Copyright (C) 2006, 2007, 2008, 2009 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/V8LazyEventListener.h"
33
34 #include "V8Document.h"
35 #include "V8HTMLFormElement.h"
36 #include "V8Node.h"
37 #include "bindings/v8/ScriptController.h"
38 #include "bindings/v8/ScriptSourceCode.h"
39 #include "bindings/v8/V8Binding.h"
40 #include "bindings/v8/V8DOMWrapper.h"
41 #include "bindings/v8/V8ScriptRunner.h"
42 #include "core/dom/Document.h"
43 #include "core/dom/Node.h"
44 #include "core/html/HTMLElement.h"
45 #include "core/html/HTMLFormElement.h"
46 #include "core/inspector/InspectorInstrumentation.h"
47 #include "core/frame/ContentSecurityPolicy.h"
48 #include "core/frame/Frame.h"
49
50 #include "wtf/StdLibExtras.h"
51
52 namespace WebCore {
53
54 V8LazyEventListener::V8LazyEventListener(const AtomicString& functionName, const AtomicString& eventParameterName, const String& code, const String sourceURL, const TextPosition& position, Node* node, v8::Isolate* isolate)
55     : V8AbstractEventListener(true, DOMWrapperWorld::mainWorld(), isolate)
56     , m_functionName(functionName)
57     , m_eventParameterName(eventParameterName)
58     , m_code(code)
59     , m_sourceURL(sourceURL)
60     , m_node(node)
61     , m_position(position)
62 {
63 }
64
65 template<typename T>
66 v8::Handle<v8::Object> toObjectWrapper(T* domObject, v8::Isolate* isolate)
67 {
68     if (!domObject)
69         return v8::Object::New(isolate);
70     v8::Handle<v8::Value> value = toV8(domObject, v8::Handle<v8::Object>(), isolate);
71     if (value.IsEmpty())
72         return v8::Object::New(isolate);
73     return v8::Local<v8::Object>::New(isolate, value.As<v8::Object>());
74 }
75
76 v8::Local<v8::Value> V8LazyEventListener::callListenerFunction(ExecutionContext* context, v8::Handle<v8::Value> jsEvent, Event* event)
77 {
78     v8::Local<v8::Object> listenerObject = getListenerObject(context);
79     if (listenerObject.IsEmpty())
80         return v8::Local<v8::Value>();
81
82     v8::Local<v8::Function> handlerFunction = listenerObject.As<v8::Function>();
83     v8::Local<v8::Object> receiver = getReceiverObject(context, event);
84     if (handlerFunction.IsEmpty() || receiver.IsEmpty())
85         return v8::Local<v8::Value>();
86
87     // FIXME: Can |context| be 0 here?
88     if (!context)
89         return v8::Local<v8::Value>();
90
91     if (!context->isDocument())
92         return v8::Local<v8::Value>();
93
94     Frame* frame = toDocument(context)->frame();
95     if (!frame)
96         return v8::Local<v8::Value>();
97
98     if (!frame->script().canExecuteScripts(AboutToExecuteScript))
99         return v8::Local<v8::Value>();
100
101     v8::Handle<v8::Value> parameters[1] = { jsEvent };
102     return frame->script().callFunction(handlerFunction, receiver, WTF_ARRAY_LENGTH(parameters), parameters);
103 }
104
105 static void V8LazyEventListenerToString(const v8::FunctionCallbackInfo<v8::Value>& info)
106 {
107     v8SetReturnValue(info, getHiddenValue(info.GetIsolate(), info.Holder(), "toStringString"));
108 }
109
110 void V8LazyEventListener::prepareListenerObject(ExecutionContext* context)
111 {
112     if (context->isDocument() && !toDocument(context)->allowInlineEventHandlers(m_node, this, m_sourceURL, m_position.m_line)) {
113         clearListenerObject();
114         return;
115     }
116
117     if (hasExistingListenerObject())
118         return;
119
120     ASSERT(context->isDocument());
121
122     v8::Isolate* isolate = toIsolate(context);
123     v8::HandleScope handleScope(isolate);
124
125     // Use the outer scope to hold context.
126     v8::Local<v8::Context> v8Context = toV8Context(context, world());
127     // Bail out if we cannot get the context.
128     if (v8Context.IsEmpty())
129         return;
130
131     v8::Context::Scope scope(v8Context);
132
133     String listenerSource =  InspectorInstrumentation::preprocessEventListener(toDocument(context)->frame(), m_code, m_sourceURL, m_functionName);
134
135     // FIXME: Remove the following 'with' hack.
136     //
137     // Nodes other than the document object, when executing inline event
138     // handlers push document, form owner, and the target node on the scope chain.
139     // We do this by using 'with' statement.
140     // See chrome/fast/forms/form-action.html
141     //     chrome/fast/forms/selected-index-value.html
142     //     base/fast/overflow/onscroll-layer-self-destruct.html
143     //
144     // Don't use new lines so that lines in the modified handler
145     // have the same numbers as in the original code.
146     // FIXME: V8 does not allow us to programmatically create object environments so
147     //        we have to do this hack! What if m_code escapes to run arbitrary script?
148     //
149     // Call with 4 arguments instead of 3, pass additional null as the last parameter.
150     // By calling the function with 4 arguments, we create a setter on arguments object
151     // which would shadow property "3" on the prototype.
152     String code = "(function() {"
153         "with (this[2]) {"
154         "with (this[1]) {"
155         "with (this[0]) {"
156             "return function(" + m_eventParameterName + ") {" +
157                 listenerSource + "\n" // Insert '\n' otherwise //-style comments could break the handler.
158             "};"
159         "}}}})";
160
161     v8::Handle<v8::String> codeExternalString = v8String(isolate, code);
162
163     v8::Local<v8::Value> result = V8ScriptRunner::compileAndRunInternalScript(codeExternalString, isolate, m_sourceURL, m_position, 0);
164     if (result.IsEmpty())
165         return;
166
167     // Call the outer function to get the inner function.
168     ASSERT(result->IsFunction());
169     v8::Local<v8::Function> intermediateFunction = result.As<v8::Function>();
170
171     HTMLFormElement* formElement = 0;
172     if (m_node && m_node->isHTMLElement())
173         formElement = toHTMLElement(m_node)->formOwner();
174
175     v8::Handle<v8::Object> nodeWrapper = toObjectWrapper<Node>(m_node, isolate);
176     v8::Handle<v8::Object> formWrapper = toObjectWrapper<HTMLFormElement>(formElement, isolate);
177     v8::Handle<v8::Object> documentWrapper = toObjectWrapper<Document>(m_node ? m_node->ownerDocument() : 0, isolate);
178
179     v8::Local<v8::Object> thisObject = v8::Object::New(isolate);
180     if (thisObject.IsEmpty())
181         return;
182     if (!thisObject->ForceSet(v8::Integer::New(isolate, 0), nodeWrapper))
183         return;
184     if (!thisObject->ForceSet(v8::Integer::New(isolate, 1), formWrapper))
185         return;
186     if (!thisObject->ForceSet(v8::Integer::New(isolate, 2), documentWrapper))
187         return;
188
189     // FIXME: Remove this code when we stop doing the 'with' hack above.
190     v8::Local<v8::Value> innerValue = V8ScriptRunner::callInternalFunction(intermediateFunction, thisObject, 0, 0, isolate);
191     if (innerValue.IsEmpty() || !innerValue->IsFunction())
192         return;
193
194     v8::Local<v8::Function> wrappedFunction = innerValue.As<v8::Function>();
195
196     // Change the toString function on the wrapper function to avoid it
197     // returning the source for the actual wrapper function. Instead it
198     // returns source for a clean wrapper function with the event
199     // argument wrapping the event source code. The reason for this is
200     // that some web sites use toString on event functions and eval the
201     // source returned (sometimes a RegExp is applied as well) for some
202     // other use. That fails miserably if the actual wrapper source is
203     // returned.
204     v8::Local<v8::Function> toStringFunction = v8::Function::New(isolate, V8LazyEventListenerToString);
205     ASSERT(!toStringFunction.IsEmpty());
206     String toStringString = "function " + m_functionName + "(" + m_eventParameterName + ") {\n  " + m_code + "\n}";
207     setHiddenValue(isolate, wrappedFunction, "toStringString", v8String(isolate, toStringString));
208     wrappedFunction->Set(v8AtomicString(isolate, "toString"), toStringFunction);
209     wrappedFunction->SetName(v8String(isolate, m_functionName));
210
211     // FIXME: Remove the following comment-outs.
212     // See https://bugs.webkit.org/show_bug.cgi?id=85152 for more details.
213     //
214     // For the time being, we comment out the following code since the
215     // second parsing can happen.
216     // // Since we only parse once, there's no need to keep data used for parsing around anymore.
217     // m_functionName = String();
218     // m_code = String();
219     // m_eventParameterName = String();
220     // m_sourceURL = String();
221
222     setListenerObject(wrappedFunction);
223 }
224
225 } // namespace WebCore