OSDN Git Service

am 02f67ae0: am ae583467: add meta-files about 3rd party projects
[android-x86/external-webkit.git] / WebCore / bindings / v8 / V8Proxy.h
1 /*
2  * Copyright (C) 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 #ifndef V8Proxy_h
32 #define V8Proxy_h
33
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"
44 #include <v8.h>
45 #include <wtf/PassRefPtr.h> // so generated bindings don't have to
46 #include <wtf/Vector.h>
47
48 #if defined(ENABLE_DOM_STATS_COUNTERS) && PLATFORM(CHROMIUM)
49 #define INC_STATS(name) PlatformBridge::incrementStatsCounter(name)
50 #else
51 #define INC_STATS(name)
52 #endif
53
54 namespace WebCore {
55
56     class CachedScript;
57     class DOMWindow;
58     class Frame;
59     class Node;
60     class SVGElement;
61     class ScriptExecutionContext;
62     class String;
63     class V8EventListener;
64     class V8IsolatedContext;
65     class WorldContextHandle;
66
67     // FIXME: use standard logging facilities in WebCore.
68     void logInfo(Frame*, const String& message, const String& url);
69
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.
74
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;
84         bool onProto;
85     };
86
87     void batchConfigureAttributes(v8::Handle<v8::ObjectTemplate>, v8::Handle<v8::ObjectTemplate>, const BatchedAttribute*, size_t attributeCount);
88
89     inline void configureAttribute(v8::Handle<v8::ObjectTemplate> instance, v8::Handle<v8::ObjectTemplate> proto, const BatchedAttribute& attribute)
90     {
91         (attribute.onProto ? proto : instance)->SetAccessor(v8::String::New(attribute.name),
92             attribute.getter,
93             attribute.setter,
94             v8::External::Wrap(attribute.data),
95             attribute.settings,
96             attribute.attribute);
97     }
98
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;
104         int value;
105     };
106
107     void batchConfigureConstants(v8::Handle<v8::FunctionTemplate>, v8::Handle<v8::ObjectTemplate>, const BatchedConstant*, size_t constantCount);
108
109     struct BatchedCallback {
110         const char* const name;
111         v8::InvocationCallback callback;
112     };
113
114     void batchConfigureCallbacks(v8::Handle<v8::ObjectTemplate>, 
115                                  v8::Handle<v8::Signature>,
116                                  v8::PropertyAttribute,
117                                  const BatchedCallback*, 
118                                  size_t callbackCount);
119
120     const int kMaxRecursionDepth = 20;
121
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 {
128         String scheme;
129         int group;
130         v8::Extension* extension;
131     };
132     typedef WTF::Vector<V8ExtensionInfo> V8Extensions;
133
134     class V8Proxy {
135     public:
136         // The types of javascript errors that can be thrown.
137         enum ErrorType {
138             RangeError,
139             ReferenceError,
140             SyntaxError,
141             TypeError,
142             GeneralError
143         };
144
145         // When to report errors.
146         enum DelayReporting {
147             ReportLater,
148             ReportNow
149         };
150
151         explicit V8Proxy(Frame*);
152
153         ~V8Proxy();
154
155         Frame* frame() { return m_frame; }
156
157         void clearForNavigation();
158         void clearForClose();
159
160         // FIXME: Need comment. User Gesture related.
161         bool inlineCode() const { return m_inlineCode; }
162         void setInlineCode(bool value) { m_inlineCode = value; }
163
164         bool timerCallback() const { return m_timerCallback; }
165         void setTimerCallback(bool value) { m_timerCallback = value; }
166
167         // Disconnects the proxy from its owner frame,
168         // and clears all timeouts on the DOM window.
169         void disconnectFrame();
170
171 #if ENABLE(SVG)
172         static void setSVGContext(void*, SVGElement*);
173         static SVGElement* svgContext(void*);
174
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
178         //
179         //   V8Proxy::setSVGContext(imp->getNewlyCreatedObject().get(), context);
180         //   foo(imp->getNewlyCreatedObject().get());
181         //
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
185         //
186         //   foo(V8Proxy::withSVGContext(imp->getNewlyCreatedObject(), context).get());
187         //
188         // where PassRefPtr::~PassRefPtr() is invoked only after foo() is
189         // called.
190         template <typename T>
191         static PassRefPtr<T> withSVGContext(PassRefPtr<T> object, SVGElement* context)
192         {
193             setSVGContext(object.get(), context);
194             return object;
195         }
196
197         template <typename T>
198         static T* withSVGContext(T* object, SVGElement* context)
199         {
200             setSVGContext(object, context);
201             return object;
202         }
203 #endif
204
205         void finishedWithEvent(Event*) { }
206
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
210         // constructors.
211         void evaluateInIsolatedWorld(int worldId, const Vector<ScriptSourceCode>& sources, int extensionGroup);
212
213         // Returns true if the proxy is currently executing a script in V8.
214         bool executingScript() const;
215
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*);
220
221         // Run an already compiled script.
222         v8::Local<v8::Value> runScript(v8::Handle<v8::Script>, bool isInlineCode);
223
224 #ifdef ANDROID_INSTRUMENT
225         v8::Local<v8::Value> runScriptInternal(v8::Handle<v8::Script> script, bool inline_code);
226 #endif
227
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[]);
230
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[]);
233
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[]);
236
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*);
245
246         // Returns the frame object of the window object associated with
247         // a context.
248         static Frame* retrieveFrame(v8::Handle<v8::Context>);
249
250
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.
254         //
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'
257         // frame is.
258         //
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."
263         //
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."
268         //
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.
274         //
275         // If you are unsure which of these functions to use, ask abarth.
276         //
277         // NOTE: These cannot be declared as inline function, because VS complains at
278         // linking time.
279         static Frame* retrieveFrameForEnteredContext();
280         static Frame* retrieveFrameForCurrentContext();
281         static Frame* retrieveFrameForCallingContext();
282
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();
288
289         // If the current context causes out of memory, JavaScript setting
290         // is disabled and it returns true.
291         static bool handleOutOfMemory();
292
293         static v8::Handle<v8::Value> checkNewLegal(const v8::Arguments&);
294
295         static v8::Handle<v8::Script> compileScript(v8::Handle<v8::String> code, const String& fileName, int baseLine, v8::ScriptData* = 0);
296
297 #ifdef ANDROID_INSTRUMENT
298         static v8::Handle<v8::Script> compileScriptInternal(v8::Handle<v8::String> code, const String& fileName, int baseLine);
299 #endif
300
301         // If the exception code is different from zero, a DOM exception is
302         // schedule to be thrown.
303         static void setDOMException(int exceptionCode);
304
305         // Schedule an error object to be thrown.
306         static v8::Handle<v8::Value> throwError(ErrorType, const char* message);
307
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();
311
312         template <typename T>
313         static v8::Handle<v8::Value> constructDOMObject(const v8::Arguments&, WrapperTypeInfo*);
314
315         template <typename T>
316         static v8::Handle<v8::Value> constructDOMObjectWithScriptExecutionContext(const v8::Arguments&, WrapperTypeInfo*);
317
318         // Process any pending JavaScript console messages.
319         static void processConsoleMessages();
320
321         v8::Local<v8::Context> context();
322         v8::Local<v8::Context> mainWorldContext();
323
324         // FIXME: This should eventually take DOMWrapperWorld argument!
325         V8DOMWindowShell* windowShell() const { return m_windowShell.get(); }
326
327         bool setContextDebugId(int id);
328         static int contextDebugId(v8::Handle<v8::Context>);
329
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);
339
340         static void registerExtensionWithV8(v8::Extension*);
341         static bool registeredExtensionWithV8(v8::Extension*);
342
343         static const V8Extensions& extensions() { return m_extensions; }
344
345         // Report an unsafe attempt to access the given frame on the console.
346         static void reportUnsafeAccessTo(Frame* target, DelayReporting delay);
347
348     private:
349         // If m_recursionCount is 0, let LocalStorage know so we can release
350         // the storage mutex.
351         void releaseStorageMutex();
352
353         void resetIsolatedWorlds();
354
355         PassOwnPtr<v8::ScriptData> precompileScript(v8::Handle<v8::String>, CachedScript*);
356
357         // Returns false when we're out of memory in V8.
358         bool setInjectedScriptContextDebugId(v8::Handle<v8::Context> targetContext);
359
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);
364
365 #if ENABLE(XPATH)
366         static const char* xpathExceptionName(int exceptionCode);
367 #endif
368
369 #if ENABLE(SVG)
370         static const char* svgExceptionName(int exceptionCode);
371 #endif
372
373 #if ENABLE(DATABASE)
374         static const char* sqlExceptionName(int exceptionCode);
375 #endif
376
377         Frame* m_frame;
378
379         // For the moment, we have one of these.  Soon we will have one per DOMWrapperWorld.
380         RefPtr<V8DOMWindowShell> m_windowShell;
381
382         // True for <a href="javascript:foo()"> and false for <script>foo()</script>.
383         // Only valid during execution.
384         bool m_inlineCode;
385
386         // True when executing from within a timer callback. Only valid during
387         // execution.
388         bool m_timerCallback;
389
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.
393         int m_recursion;
394
395         // All of the extensions registered with the context.
396         static V8Extensions m_extensions;
397
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().
401         //
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().
405         //
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;
410     };
411
412     template <typename T>
413     v8::Handle<v8::Value> V8Proxy::constructDOMObject(const v8::Arguments& args, WrapperTypeInfo* type)
414     {
415         if (!args.IsConstructCall())
416             return throwError(V8Proxy::TypeError, "DOM object constructor cannot be called as a function.");
417
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());
422         obj->ref();
423         V8DOMWrapper::setJSWrapperForDOMObject(obj.get(), v8::Persistent<v8::Object>::New(args.Holder()));
424         return args.Holder();
425     }
426
427     template <typename T>
428     v8::Handle<v8::Value> V8Proxy::constructDOMObjectWithScriptExecutionContext(const v8::Arguments& args, WrapperTypeInfo* type)
429     {
430         if (!args.IsConstructCall())
431             return throwError(V8Proxy::TypeError, "");
432
433         ScriptExecutionContext* context = getScriptExecutionContext();
434         if (!context)
435             return throwError(V8Proxy::ReferenceError, "");
436
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());
441         obj->ref();
442         V8DOMWrapper::setJSWrapperForDOMObject(obj.get(), v8::Persistent<v8::Object>::New(args.Holder()));
443         return args.Holder();
444     }
445
446
447     v8::Local<v8::Context> toV8Context(ScriptExecutionContext*, const WorldContextHandle& worldContext);
448
449     // Used by an interceptor callback that it hasn't found anything to
450     // intercept.
451     inline static v8::Local<v8::Object> notHandledByInterceptor()
452     {
453         return v8::Local<v8::Object>();
454     }
455
456     inline static v8::Local<v8::Boolean> deletionNotHandledByInterceptor()
457     {
458         return v8::Local<v8::Boolean>();
459     }
460     inline v8::Handle<v8::Primitive> throwError(const char* message, V8Proxy::ErrorType type = V8Proxy::TypeError)
461     {
462         if (!v8::V8::IsExecutionTerminating())
463             V8Proxy::throwError(type, message);
464         return v8::Undefined();
465     }
466
467     inline v8::Handle<v8::Primitive> throwError(ExceptionCode ec)
468     {
469         if (!v8::V8::IsExecutionTerminating())
470             V8Proxy::setDOMException(ec);
471         return v8::Undefined();
472     }
473
474     inline v8::Handle<v8::Primitive> throwError(v8::Local<v8::Value> exception)
475     {
476         if (!v8::V8::IsExecutionTerminating())
477             v8::ThrowException(exception);
478         return v8::Undefined();
479     }
480
481     template <class T> inline v8::Handle<v8::Object> toV8(PassRefPtr<T> object, v8::Local<v8::Object> holder)
482     {
483         object->ref();
484         V8DOMWrapper::setJSWrapperForDOMObject(object.get(), v8::Persistent<v8::Object>::New(holder));
485         return holder;
486     }
487
488 }
489
490 #endif // V8Proxy_h