2 * Copyright (C) 2009 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
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
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.
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.
34 #include "PlatformBridge.h"
35 #include "ScriptSourceCode.h" // for WebCore::ScriptSourceCode
36 #include "SecurityOrigin.h" // for WebCore::SecurityOrigin
37 #include "SharedPersistent.h"
38 #include "V8AbstractEventListener.h"
39 #include "V8DOMWindowShell.h"
40 #include "V8DOMWrapper.h"
41 #include "V8GCController.h"
42 #include "V8Utilities.h"
43 #include "WrapperTypeInfo.h"
45 #include <wtf/PassRefPtr.h> // so generated bindings don't have to
46 #include <wtf/Vector.h>
48 #if defined(ENABLE_DOM_STATS_COUNTERS) && PLATFORM(CHROMIUM)
49 #define INC_STATS(name) PlatformBridge::incrementStatsCounter(name)
51 #define INC_STATS(name)
61 class ScriptExecutionContext;
63 class V8EventListener;
64 class V8IsolatedContext;
65 class WorldContextHandle;
67 // FIXME: use standard logging facilities in WebCore.
68 void logInfo(Frame*, const String& message, const String& url);
70 // The following Batch structs and methods are used for setting multiple
71 // properties on an ObjectTemplate, used from the generated bindings
72 // initialization (ConfigureXXXTemplate). This greatly reduces the binary
73 // size by moving from code driven setup to data table driven setup.
75 // BatchedAttribute translates into calls to SetAccessor() on either the
76 // instance or the prototype ObjectTemplate, based on |onProto|.
77 struct BatchedAttribute {
78 const char* const name;
79 v8::AccessorGetter getter;
80 v8::AccessorSetter setter;
81 WrapperTypeInfo* data;
82 v8::AccessControl settings;
83 v8::PropertyAttribute attribute;
87 void batchConfigureAttributes(v8::Handle<v8::ObjectTemplate>, v8::Handle<v8::ObjectTemplate>, const BatchedAttribute*, size_t attributeCount);
89 inline void configureAttribute(v8::Handle<v8::ObjectTemplate> instance, v8::Handle<v8::ObjectTemplate> proto, const BatchedAttribute& attribute)
91 (attribute.onProto ? proto : instance)->SetAccessor(v8::String::New(attribute.name),
94 v8::External::Wrap(attribute.data),
99 // BatchedConstant translates into calls to Set() for setting up an object's
100 // constants. It sets the constant on both the FunctionTemplate and the
101 // ObjectTemplate. PropertyAttributes is always ReadOnly.
102 struct BatchedConstant {
103 const char* const name;
107 void batchConfigureConstants(v8::Handle<v8::FunctionTemplate>, v8::Handle<v8::ObjectTemplate>, const BatchedConstant*, size_t constantCount);
109 struct BatchedCallback {
110 const char* const name;
111 v8::InvocationCallback callback;
114 void batchConfigureCallbacks(v8::Handle<v8::ObjectTemplate>,
115 v8::Handle<v8::Signature>,
116 v8::PropertyAttribute,
117 const BatchedCallback*,
118 size_t callbackCount);
120 const int kMaxRecursionDepth = 20;
122 // Information about an extension that is registered for use with V8. If
123 // scheme is non-empty, it contains the URL scheme the extension should be
124 // used with. If group is non-zero, the extension will only be loaded into
125 // script contexts that belong to that group. Otherwise, the extension is
126 // used with all schemes and contexts.
127 struct V8ExtensionInfo {
130 v8::Extension* extension;
132 typedef WTF::Vector<V8ExtensionInfo> V8Extensions;
136 // The types of javascript errors that can be thrown.
145 // When to report errors.
146 enum DelayReporting {
151 explicit V8Proxy(Frame*);
155 Frame* frame() { return m_frame; }
157 void clearForNavigation();
158 void clearForClose();
160 // FIXME: Need comment. User Gesture related.
161 bool inlineCode() const { return m_inlineCode; }
162 void setInlineCode(bool value) { m_inlineCode = value; }
164 bool timerCallback() const { return m_timerCallback; }
165 void setTimerCallback(bool value) { m_timerCallback = value; }
167 // Disconnects the proxy from its owner frame,
168 // and clears all timeouts on the DOM window.
169 void disconnectFrame();
172 static void setSVGContext(void*, SVGElement*);
173 static SVGElement* svgContext(void*);
175 // These helper functions are required in case we are given a PassRefPtr
176 // to a (possibly) newly created object and must prevent its reference
177 // count from dropping to zero as would happen in code like
179 // V8Proxy::setSVGContext(imp->getNewlyCreatedObject().get(), context);
180 // foo(imp->getNewlyCreatedObject().get());
182 // In the above two lines each time getNewlyCreatedObject() is called it
183 // creates a new object because we don't ref() it. (So our attemts to
184 // associate a context with it fail.) Such code should be rewritten to
186 // foo(V8Proxy::withSVGContext(imp->getNewlyCreatedObject(), context).get());
188 // where PassRefPtr::~PassRefPtr() is invoked only after foo() is
190 template <typename T>
191 static PassRefPtr<T> withSVGContext(PassRefPtr<T> object, SVGElement* context)
193 setSVGContext(object.get(), context);
197 template <typename T>
198 static T* withSVGContext(T* object, SVGElement* context)
200 setSVGContext(object, context);
205 void finishedWithEvent(Event*) { }
207 // Evaluate JavaScript in a new isolated world. The script gets its own
208 // global scope, its own prototypes for intrinsic JavaScript objects (String,
209 // Array, and so-on), and its own wrappers for all DOM nodes and DOM
211 void evaluateInIsolatedWorld(int worldId, const Vector<ScriptSourceCode>& sources, int extensionGroup);
213 // Returns true if the proxy is currently executing a script in V8.
214 bool executingScript() const;
216 // Evaluate a script file in the current execution environment.
217 // The caller must hold an execution context.
218 // If cannot evalute the script, it returns an error.
219 v8::Local<v8::Value> evaluate(const ScriptSourceCode&, Node*);
221 // Run an already compiled script.
222 v8::Local<v8::Value> runScript(v8::Handle<v8::Script>, bool isInlineCode);
224 #ifdef ANDROID_INSTRUMENT
225 v8::Local<v8::Value> runScriptInternal(v8::Handle<v8::Script> script, bool inline_code);
228 // Call the function with the given receiver and arguments.
229 v8::Local<v8::Value> callFunction(v8::Handle<v8::Function>, v8::Handle<v8::Object>, int argc, v8::Handle<v8::Value> argv[]);
231 // Call the function with the given receiver and arguments.
232 static v8::Local<v8::Value> callFunctionWithoutFrame(v8::Handle<v8::Function>, v8::Handle<v8::Object>, int argc, v8::Handle<v8::Value> argv[]);
234 // Call the function as constructor with the given arguments.
235 v8::Local<v8::Value> newInstance(v8::Handle<v8::Function>, int argc, v8::Handle<v8::Value> argv[]);
237 // Returns the window object associated with a context.
238 static DOMWindow* retrieveWindow(v8::Handle<v8::Context>);
239 // Returns V8Proxy object of the currently executing context.
240 static V8Proxy* retrieve();
241 // Returns V8Proxy object associated with a frame.
242 static V8Proxy* retrieve(Frame*);
243 // Returns V8Proxy object associated with a script execution context.
244 static V8Proxy* retrieve(ScriptExecutionContext*);
246 // Returns the frame object of the window object associated with
248 static Frame* retrieveFrame(v8::Handle<v8::Context>);
251 // The three functions below retrieve WebFrame instances relating the
252 // currently executing JavaScript. Since JavaScript can make function calls
253 // across frames, though, we need to be more precise.
255 // For example, imagine that a JS function in frame A calls a function in
256 // frame B, which calls native code, which wants to know what the 'active'
259 // The 'entered context' is the context where execution first entered the
260 // script engine; the context that is at the bottom of the JS function stack.
261 // RetrieveFrameForEnteredContext() would return Frame A in our example.
262 // This frame is often referred to as the "dynamic global object."
264 // The 'current context' is the context the JS engine is currently inside of;
265 // the context that is at the top of the JS function stack.
266 // RetrieveFrameForCurrentContext() would return Frame B in our example.
267 // This frame is often referred to as the "lexical global object."
269 // Finally, the 'calling context' is the context one below the current
270 // context on the JS function stack. For example, if function f calls
271 // function g, then the calling context will be the context associated with
272 // f. This context is commonly used by DOM security checks because they want
273 // to know who called them.
275 // If you are unsure which of these functions to use, ask abarth.
277 // NOTE: These cannot be declared as inline function, because VS complains at
279 static Frame* retrieveFrameForEnteredContext();
280 static Frame* retrieveFrameForCurrentContext();
281 static Frame* retrieveFrameForCallingContext();
283 // Returns V8 Context of a frame. If none exists, creates
284 // a new context. It is potentially slow and consumes memory.
285 static v8::Local<v8::Context> context(Frame*);
286 static v8::Local<v8::Context> mainWorldContext(Frame*);
287 static v8::Local<v8::Context> currentContext();
289 // If the current context causes out of memory, JavaScript setting
290 // is disabled and it returns true.
291 static bool handleOutOfMemory();
293 static v8::Handle<v8::Value> checkNewLegal(const v8::Arguments&);
295 static v8::Handle<v8::Script> compileScript(v8::Handle<v8::String> code, const String& fileName, int baseLine, v8::ScriptData* = 0);
297 #ifdef ANDROID_INSTRUMENT
298 static v8::Handle<v8::Script> compileScriptInternal(v8::Handle<v8::String> code, const String& fileName, int baseLine);
301 // If the exception code is different from zero, a DOM exception is
302 // schedule to be thrown.
303 static void setDOMException(int exceptionCode);
305 // Schedule an error object to be thrown.
306 static v8::Handle<v8::Value> throwError(ErrorType, const char* message);
308 // Helpers for throwing syntax and type errors with predefined messages.
309 static v8::Handle<v8::Value> throwTypeError();
310 static v8::Handle<v8::Value> throwSyntaxError();
312 template <typename T>
313 static v8::Handle<v8::Value> constructDOMObject(const v8::Arguments&, WrapperTypeInfo*);
315 template <typename T>
316 static v8::Handle<v8::Value> constructDOMObjectWithScriptExecutionContext(const v8::Arguments&, WrapperTypeInfo*);
318 // Process any pending JavaScript console messages.
319 static void processConsoleMessages();
321 v8::Local<v8::Context> context();
322 v8::Local<v8::Context> mainWorldContext();
324 // FIXME: This should eventually take DOMWrapperWorld argument!
325 V8DOMWindowShell* windowShell() const { return m_windowShell.get(); }
327 bool setContextDebugId(int id);
328 static int contextDebugId(v8::Handle<v8::Context>);
330 // Registers a v8 extension to be available on webpages. The two forms
331 // offer various restrictions on what types of contexts the extension is
332 // loaded into. If a scheme is provided, only pages whose URL has the given
333 // scheme will match. If extensionGroup is provided, the extension will
334 // only be loaded into scripts run via evaluateInNewWorld with the
335 // matching group. Will only affect v8 contexts initialized after this
336 // call. Takes ownership of the v8::Extension object passed.
337 static void registerExtension(v8::Extension*, const String& schemeRestriction);
338 static void registerExtension(v8::Extension*, int extensionGroup);
340 static void registerExtensionWithV8(v8::Extension*);
341 static bool registeredExtensionWithV8(v8::Extension*);
343 static const V8Extensions& extensions() { return m_extensions; }
345 // Report an unsafe attempt to access the given frame on the console.
346 static void reportUnsafeAccessTo(Frame* target, DelayReporting delay);
349 // If m_recursionCount is 0, let LocalStorage know so we can release
350 // the storage mutex.
351 void releaseStorageMutex();
353 void resetIsolatedWorlds();
355 PassOwnPtr<v8::ScriptData> precompileScript(v8::Handle<v8::String>, CachedScript*);
357 // Returns false when we're out of memory in V8.
358 bool setInjectedScriptContextDebugId(v8::Handle<v8::Context> targetContext);
360 static const char* rangeExceptionName(int exceptionCode);
361 static const char* eventExceptionName(int exceptionCode);
362 static const char* xmlHttpRequestExceptionName(int exceptionCode);
363 static const char* domExceptionName(int exceptionCode);
366 static const char* xpathExceptionName(int exceptionCode);
370 static const char* svgExceptionName(int exceptionCode);
374 static const char* sqlExceptionName(int exceptionCode);
379 // For the moment, we have one of these. Soon we will have one per DOMWrapperWorld.
380 RefPtr<V8DOMWindowShell> m_windowShell;
382 // True for <a href="javascript:foo()"> and false for <script>foo()</script>.
383 // Only valid during execution.
386 // True when executing from within a timer callback. Only valid during
388 bool m_timerCallback;
390 // Track the recursion depth to be able to avoid too deep recursion. The V8
391 // engine allows much more recursion than KJS does so we need to guard against
392 // excessive recursion in the binding layer.
395 // All of the extensions registered with the context.
396 static V8Extensions m_extensions;
398 // The isolated worlds we are tracking for this frame. We hold them alive
399 // here so that they can be used again by future calls to
400 // evaluateInIsolatedWorld().
402 // Note: although the pointer is raw, the instance is kept alive by a strong
403 // reference to the v8 context it contains, which is not made weak until we
404 // call world->destroy().
406 // FIXME: We want to eventually be holding window shells instead of the
407 // IsolatedContext directly.
408 typedef HashMap<int, V8IsolatedContext*> IsolatedWorldMap;
409 IsolatedWorldMap m_isolatedWorlds;
412 template <typename T>
413 v8::Handle<v8::Value> V8Proxy::constructDOMObject(const v8::Arguments& args, WrapperTypeInfo* type)
415 if (!args.IsConstructCall())
416 return throwError(V8Proxy::TypeError, "DOM object constructor cannot be called as a function.");
418 // Note: it's OK to let this RefPtr go out of scope because we also call
419 // SetDOMWrapper(), which effectively holds a reference to obj.
420 RefPtr<T> obj = T::create();
421 V8DOMWrapper::setDOMWrapper(args.Holder(), type, obj.get());
423 V8DOMWrapper::setJSWrapperForDOMObject(obj.get(), v8::Persistent<v8::Object>::New(args.Holder()));
424 return args.Holder();
427 template <typename T>
428 v8::Handle<v8::Value> V8Proxy::constructDOMObjectWithScriptExecutionContext(const v8::Arguments& args, WrapperTypeInfo* type)
430 if (!args.IsConstructCall())
431 return throwError(V8Proxy::TypeError, "");
433 ScriptExecutionContext* context = getScriptExecutionContext();
435 return throwError(V8Proxy::ReferenceError, "");
437 // Note: it's OK to let this RefPtr go out of scope because we also call
438 // SetDOMWrapper(), which effectively holds a reference to obj.
439 RefPtr<T> obj = T::create(context);
440 V8DOMWrapper::setDOMWrapper(args.Holder(), type, obj.get());
442 V8DOMWrapper::setJSWrapperForDOMObject(obj.get(), v8::Persistent<v8::Object>::New(args.Holder()));
443 return args.Holder();
447 v8::Local<v8::Context> toV8Context(ScriptExecutionContext*, const WorldContextHandle& worldContext);
449 // Used by an interceptor callback that it hasn't found anything to
451 inline static v8::Local<v8::Object> notHandledByInterceptor()
453 return v8::Local<v8::Object>();
456 inline static v8::Local<v8::Boolean> deletionNotHandledByInterceptor()
458 return v8::Local<v8::Boolean>();
460 inline v8::Handle<v8::Primitive> throwError(const char* message, V8Proxy::ErrorType type = V8Proxy::TypeError)
462 if (!v8::V8::IsExecutionTerminating())
463 V8Proxy::throwError(type, message);
464 return v8::Undefined();
467 inline v8::Handle<v8::Primitive> throwError(ExceptionCode ec)
469 if (!v8::V8::IsExecutionTerminating())
470 V8Proxy::setDOMException(ec);
471 return v8::Undefined();
474 inline v8::Handle<v8::Primitive> throwError(v8::Local<v8::Value> exception)
476 if (!v8::V8::IsExecutionTerminating())
477 v8::ThrowException(exception);
478 return v8::Undefined();
481 template <class T> inline v8::Handle<v8::Object> toV8(PassRefPtr<T> object, v8::Local<v8::Object> holder)
484 V8DOMWrapper::setJSWrapperForDOMObject(object.get(), v8::Persistent<v8::Object>::New(holder));