initial import
[vuplus_webkit] / Source / WebCore / bindings / v8 / V8DOMWrapper.cpp
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 #include "config.h"
32 #include "V8DOMWrapper.h"
33
34 #include "ArrayBufferView.h"
35 #include "CSSMutableStyleDeclaration.h"
36 #include "DOMDataStore.h"
37 #include "DocumentLoader.h"
38 #include "FrameLoaderClient.h"
39 #include "Notification.h"
40 #include "V8AbstractEventListener.h"
41 #include "V8Binding.h"
42 #include "V8Collection.h"
43 #include "V8DOMApplicationCache.h"
44 #include "V8DOMMap.h"
45 #include "V8DOMWindow.h"
46 #include "V8DedicatedWorkerContext.h"
47 #include "V8EventListener.h"
48 #include "V8EventListenerList.h"
49 #include "V8EventSource.h"
50 #include "V8FileReader.h"
51 #include "V8FileWriter.h"
52 #include "V8HTMLCollection.h"
53 #include "V8HTMLDocument.h"
54 #include "V8HiddenPropertyName.h"
55 #include "V8IDBDatabase.h"
56 #include "V8IDBRequest.h"
57 #include "V8IDBTransaction.h"
58 #include "V8IsolatedContext.h"
59 #include "V8LocalMediaStream.h"
60 #include "V8Location.h"
61 #include "V8MediaStream.h"
62 #include "V8MessageChannel.h"
63 #include "V8NamedNodeMap.h"
64 #include "V8Node.h"
65 #include "V8NodeFilterCondition.h"
66 #include "V8NodeList.h"
67 #include "V8Notification.h"
68 #include "V8PeerConnection.h"
69 #include "V8Proxy.h"
70 #include "V8SharedWorker.h"
71 #include "V8SharedWorkerContext.h"
72 #include "V8StyleSheet.h"
73 #include "V8WebSocket.h"
74 #include "V8Worker.h"
75 #include "V8WorkerContext.h"
76 #include "V8WorkerContextEventListener.h"
77 #include "V8XMLHttpRequest.h"
78 #include "WebGLContextAttributes.h"
79 #include "WebGLUniformLocation.h"
80 #include "WorkerContextExecutionProxy.h"
81 #include "WrapperTypeInfo.h"
82
83 #if ENABLE(SVG)
84 #include "SVGElementInstance.h"
85 #include "SVGPathSeg.h"
86 #include "V8SVGElementInstance.h"
87 #endif
88
89 #if ENABLE(WEB_AUDIO)
90 #include "V8AudioContext.h"
91 #include "V8JavaScriptAudioNode.h"
92 #endif
93
94 #include <algorithm>
95 #include <utility>
96 #include <v8-debug.h>
97 #include <wtf/Assertions.h>
98 #include <wtf/OwnArrayPtr.h>
99 #include <wtf/StdLibExtras.h>
100 #include <wtf/UnusedParam.h>
101
102 namespace WebCore {
103
104 typedef HashMap<Node*, v8::Object*> DOMNodeMap;
105 typedef HashMap<void*, v8::Object*> DOMObjectMap;
106
107 // The caller must have increased obj's ref count.
108 void V8DOMWrapper::setJSWrapperForDOMObject(void* object, v8::Persistent<v8::Object> wrapper)
109 {
110     ASSERT(V8DOMWrapper::maybeDOMWrapper(wrapper));
111     ASSERT(!domWrapperType(wrapper)->toActiveDOMObjectFunction);
112     getDOMObjectMap().set(object, wrapper);
113 }
114
115 // The caller must have increased obj's ref count.
116 void V8DOMWrapper::setJSWrapperForActiveDOMObject(void* object, v8::Persistent<v8::Object> wrapper)
117 {
118     ASSERT(V8DOMWrapper::maybeDOMWrapper(wrapper));
119     ASSERT(domWrapperType(wrapper)->toActiveDOMObjectFunction);
120     getActiveDOMObjectMap().set(object, wrapper);
121 }
122
123 // The caller must have increased node's ref count.
124 void V8DOMWrapper::setJSWrapperForDOMNode(Node* node, v8::Persistent<v8::Object> wrapper)
125 {
126     ASSERT(V8DOMWrapper::maybeDOMWrapper(wrapper));
127     getDOMNodeMap().set(node, wrapper);
128 }
129
130 v8::Local<v8::Function> V8DOMWrapper::getConstructor(WrapperTypeInfo* type, v8::Handle<v8::Value> objectPrototype)
131 {
132     // A DOM constructor is a function instance created from a DOM constructor
133     // template. There is one instance per context. A DOM constructor is
134     // different from a normal function in two ways:
135     //   1) it cannot be called as constructor (aka, used to create a DOM object)
136     //   2) its __proto__ points to Object.prototype rather than
137     //      Function.prototype.
138     // The reason for 2) is that, in Safari, a DOM constructor is a normal JS
139     // object, but not a function. Hotmail relies on the fact that, in Safari,
140     // HTMLElement.__proto__ == Object.prototype.
141     v8::Handle<v8::FunctionTemplate> functionTemplate = type->getTemplate();
142     // Getting the function might fail if we're running out of
143     // stack or memory.
144     v8::TryCatch tryCatch;
145     v8::Local<v8::Function> value = functionTemplate->GetFunction();
146     if (value.IsEmpty())
147         return v8::Local<v8::Function>();
148     // Hotmail fix, see comments above.
149     if (!objectPrototype.IsEmpty())
150         value->SetPrototype(objectPrototype);
151     return value;
152 }
153
154 v8::Local<v8::Function> V8DOMWrapper::getConstructorForContext(WrapperTypeInfo* type, v8::Handle<v8::Context> context)
155 {
156     // Enter the scope for this context to get the correct constructor.
157     v8::Context::Scope scope(context);
158
159     return getConstructor(type, V8DOMWindowShell::getHiddenObjectPrototype(context));
160 }
161
162 v8::Local<v8::Function> V8DOMWrapper::getConstructor(WrapperTypeInfo* type, DOMWindow* window)
163 {
164     Frame* frame = window->frame();
165     if (!frame)
166         return v8::Local<v8::Function>();
167
168     v8::Handle<v8::Context> context = V8Proxy::context(frame);
169     if (context.IsEmpty())
170         return v8::Local<v8::Function>();
171
172     return getConstructorForContext(type, context);
173 }
174
175 #if ENABLE(WORKERS)
176 v8::Local<v8::Function> V8DOMWrapper::getConstructor(WrapperTypeInfo* type, WorkerContext*)
177 {
178     WorkerScriptController* controller = WorkerScriptController::controllerForContext();
179     WorkerContextExecutionProxy* proxy = controller ? controller->proxy() : 0;
180     if (!proxy)
181         return v8::Local<v8::Function>();
182
183     v8::Handle<v8::Context> context = proxy->context();
184     if (context.IsEmpty())
185         return v8::Local<v8::Function>();
186
187     return getConstructorForContext(type, context);
188 }
189 #endif
190
191
192 void V8DOMWrapper::setNamedHiddenReference(v8::Handle<v8::Object> parent, const char* name, v8::Handle<v8::Value> child)
193 {
194     parent->SetHiddenValue(V8HiddenPropertyName::hiddenReferenceName(name), child);
195 }
196
197 void V8DOMWrapper::setNamedHiddenWindowReference(Frame* frame, const char* name, v8::Handle<v8::Value> jsObject)
198 {
199     // Get DOMWindow
200     if (!frame)
201         return; // Object might be detached from window
202     v8::Handle<v8::Context> context = V8Proxy::context(frame);
203     if (context.IsEmpty())
204         return;
205
206     v8::Handle<v8::Object> global = context->Global();
207     // Look for real DOM wrapper.
208     global = V8DOMWrapper::lookupDOMWrapper(V8DOMWindow::GetTemplate(), global);
209     ASSERT(!global.IsEmpty());
210
211     setNamedHiddenReference(global, name, jsObject);
212 }
213
214 WrapperTypeInfo* V8DOMWrapper::domWrapperType(v8::Handle<v8::Object> object)
215 {
216     ASSERT(V8DOMWrapper::maybeDOMWrapper(object));
217     return static_cast<WrapperTypeInfo*>(object->GetPointerFromInternalField(v8DOMWrapperTypeIndex));
218 }
219
220 PassRefPtr<NodeFilter> V8DOMWrapper::wrapNativeNodeFilter(v8::Handle<v8::Value> filter)
221 {
222     // A NodeFilter is used when walking through a DOM tree or iterating tree
223     // nodes.
224     // FIXME: we may want to cache NodeFilterCondition and NodeFilter
225     // object, but it is minor.
226     // NodeFilter is passed to NodeIterator that has a ref counted pointer
227     // to NodeFilter. NodeFilter has a ref counted pointer to NodeFilterCondition.
228     // In NodeFilterCondition, filter object is persisted in its constructor,
229     // and disposed in its destructor.
230     return NodeFilter::create(V8NodeFilterCondition::create(filter));
231 }
232
233 static bool globalObjectPrototypeIsDOMWindow(v8::Handle<v8::Object> objectPrototype)
234 {
235     // We can identify what type of context the global object is wrapping by looking at the
236     // internal field count of its prototype. This assumes WorkerContexts and DOMWindows have different numbers
237     // of internal fields, so a COMPILE_ASSERT is included to warn if this ever changes.
238 #if ENABLE(WORKERS)
239     COMPILE_ASSERT(V8DOMWindow::internalFieldCount != V8WorkerContext::internalFieldCount,
240         DOMWindowAndWorkerContextHaveUnequalFieldCounts);
241     COMPILE_ASSERT(V8DOMWindow::internalFieldCount != V8DedicatedWorkerContext::internalFieldCount,
242         DOMWindowAndDedicatedWorkerContextHaveUnequalFieldCounts);
243 #endif
244 #if ENABLE(SHARED_WORKERS)
245     COMPILE_ASSERT(V8DOMWindow::internalFieldCount != V8SharedWorkerContext::internalFieldCount,
246         DOMWindowAndSharedWorkerContextHaveUnequalFieldCounts);
247 #endif
248     return objectPrototype->InternalFieldCount() == V8DOMWindow::internalFieldCount;
249 }
250
251 v8::Local<v8::Object> V8DOMWrapper::instantiateV8Object(V8Proxy* proxy, WrapperTypeInfo* type, void* impl)
252 {
253 #if ENABLE(WORKERS)
254     WorkerContext* workerContext = 0;
255 #endif
256     if (V8IsolatedContext::getEntered()) {
257         // This effectively disables the wrapper cache for isolated worlds.
258         proxy = 0;
259         // FIXME: Do we need a wrapper cache for the isolated world?  We should
260         //        see if the performance gains are worth while.
261         // We'll get one once we give the isolated context a proper window shell.
262     } else if (!proxy) {
263         v8::Handle<v8::Context> context = v8::Context::GetCurrent();
264         if (!context.IsEmpty()) {
265             v8::Handle<v8::Object> globalPrototype = v8::Handle<v8::Object>::Cast(context->Global()->GetPrototype());
266             if (globalObjectPrototypeIsDOMWindow(globalPrototype))
267                 proxy = V8Proxy::retrieve(V8DOMWindow::toNative(globalPrototype)->frame());
268 #if ENABLE(WORKERS)
269             else
270                 workerContext = V8WorkerContext::toNative(lookupDOMWrapper(V8WorkerContext::GetTemplate(), context->Global()));
271 #endif
272         }
273     }
274
275     v8::Local<v8::Object> instance;
276     if (proxy)
277         // FIXME: Fix this to work properly with isolated worlds (see above).
278         instance = proxy->windowShell()->createWrapperFromCache(type);
279     else {
280         v8::Local<v8::Function> function;
281 #if ENABLE(WORKERS)
282         if (workerContext)
283             function = getConstructor(type, workerContext);
284         else
285 #endif
286             function = type->getTemplate()->GetFunction();
287         instance = SafeAllocation::newInstance(function);
288     }
289     if (!instance.IsEmpty()) {
290         // Avoid setting the DOM wrapper for failed allocations.
291         setDOMWrapper(instance, type, impl);
292         if (type == &V8HTMLDocument::info)
293             instance = V8HTMLDocument::WrapInShadowObject(instance, static_cast<Node*>(impl));
294     }
295     return instance;
296 }
297
298 #ifndef NDEBUG
299 bool V8DOMWrapper::maybeDOMWrapper(v8::Handle<v8::Value> value)
300 {
301     if (value.IsEmpty() || !value->IsObject())
302         return false;
303
304     v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(value);
305     if (!object->InternalFieldCount())
306         return false;
307
308     ASSERT(object->InternalFieldCount() >= v8DefaultWrapperInternalFieldCount);
309
310     v8::Handle<v8::Value> wrapper = object->GetInternalField(v8DOMWrapperObjectIndex);
311     ASSERT(wrapper->IsNumber() || wrapper->IsExternal());
312
313     return true;
314 }
315 #endif
316
317 bool V8DOMWrapper::isValidDOMObject(v8::Handle<v8::Value> value)
318 {
319     if (value.IsEmpty() || !value->IsObject())
320         return false;
321     return v8::Handle<v8::Object>::Cast(value)->InternalFieldCount();
322 }
323
324 bool V8DOMWrapper::isWrapperOfType(v8::Handle<v8::Value> value, WrapperTypeInfo* type)
325 {
326     if (!isValidDOMObject(value))
327         return false;
328
329     v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(value);
330     ASSERT(object->InternalFieldCount() >= v8DefaultWrapperInternalFieldCount);
331
332     v8::Handle<v8::Value> wrapper = object->GetInternalField(v8DOMWrapperObjectIndex);
333     ASSERT(wrapper->IsNumber() || wrapper->IsExternal());
334
335     WrapperTypeInfo* typeInfo = static_cast<WrapperTypeInfo*>(object->GetPointerFromInternalField(v8DOMWrapperTypeIndex));
336     return typeInfo == type;
337 }
338
339 v8::Handle<v8::Object> V8DOMWrapper::getWrapperSlow(Node* node)
340 {
341     V8IsolatedContext* context = V8IsolatedContext::getEntered();
342     if (LIKELY(!context)) {
343         v8::Persistent<v8::Object>* wrapper = node->wrapper();
344         if (!wrapper)
345             return v8::Handle<v8::Object>();
346         return *wrapper;
347     }
348     DOMNodeMapping& domNodeMap = context->world()->domDataStore()->domNodeMap();
349     return domNodeMap.get(node);
350 }
351
352 // A JS object of type EventTarget is limited to a small number of possible classes.
353 // Check EventTarget.h for new type conversion methods
354 v8::Handle<v8::Value> V8DOMWrapper::convertEventTargetToV8Object(EventTarget* target)
355 {
356     if (!target)
357         return v8::Null();
358
359 #if ENABLE(SVG)
360     if (SVGElementInstance* instance = target->toSVGElementInstance())
361         return toV8(instance);
362 #endif
363
364 #if ENABLE(WORKERS)
365     if (Worker* worker = target->toWorker())
366         return toV8(worker);
367
368     if (DedicatedWorkerContext* workerContext = target->toDedicatedWorkerContext())
369         return toV8(workerContext);
370 #endif // WORKERS
371
372 #if ENABLE(SHARED_WORKERS)
373     if (SharedWorker* sharedWorker = target->toSharedWorker())
374         return toV8(sharedWorker);
375
376     if (SharedWorkerContext* sharedWorkerContext = target->toSharedWorkerContext())
377         return toV8(sharedWorkerContext);
378 #endif // SHARED_WORKERS
379
380 #if ENABLE(NOTIFICATIONS)
381     if (Notification* notification = target->toNotification())
382         return toV8(notification);
383 #endif
384
385 #if ENABLE(INDEXED_DATABASE)
386     if (IDBDatabase* idbDatabase = target->toIDBDatabase())
387         return toV8(idbDatabase);
388     if (IDBRequest* idbRequest = target->toIDBRequest())
389         return toV8(idbRequest);
390     if (IDBTransaction* idbTransaction = target->toIDBTransaction())
391         return toV8(idbTransaction);
392 #endif
393
394 #if ENABLE(WEB_SOCKETS)
395     if (WebSocket* webSocket = target->toWebSocket())
396         return toV8(webSocket);
397 #endif
398
399     if (Node* node = target->toNode())
400         return toV8(node);
401
402     if (DOMWindow* domWindow = target->toDOMWindow())
403         return toV8(domWindow);
404
405     // XMLHttpRequest is created within its JS counterpart.
406     if (XMLHttpRequest* xmlHttpRequest = target->toXMLHttpRequest()) {
407         v8::Handle<v8::Object> wrapper = getActiveDOMObjectMap().get(xmlHttpRequest);
408         ASSERT(!wrapper.IsEmpty());
409         return wrapper;
410     }
411
412     // MessagePort is created within its JS counterpart
413     if (MessagePort* port = target->toMessagePort()) {
414         v8::Handle<v8::Object> wrapper = getActiveDOMObjectMap().get(port);
415         ASSERT(!wrapper.IsEmpty());
416         return wrapper;
417     }
418
419     if (XMLHttpRequestUpload* upload = target->toXMLHttpRequestUpload()) {
420         v8::Handle<v8::Object> wrapper = getDOMObjectMap().get(upload);
421         ASSERT(!wrapper.IsEmpty());
422         return wrapper;
423     }
424
425 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
426     if (DOMApplicationCache* domAppCache = target->toDOMApplicationCache())
427         return toV8(domAppCache);
428 #endif
429
430 #if ENABLE(EVENTSOURCE)
431     if (EventSource* eventSource = target->toEventSource())
432         return toV8(eventSource);
433 #endif
434
435 #if ENABLE(BLOB)
436     if (FileReader* fileReader = target->toFileReader())
437         return toV8(fileReader);
438 #endif
439
440 #if ENABLE(FILE_SYSTEM)
441     if (FileWriter* fileWriter = target->toFileWriter())
442         return toV8(fileWriter);
443 #endif
444
445 #if ENABLE(WEB_AUDIO)
446     if (JavaScriptAudioNode* jsAudioNode = target->toJavaScriptAudioNode())
447         return toV8(jsAudioNode);
448     if (AudioContext* audioContext = target->toAudioContext())
449         return toV8(audioContext);
450 #endif    
451
452 #if ENABLE(MEDIA_STREAM)
453     if (LocalMediaStream* stream = target->toLocalMediaStream())
454         return toV8(stream);
455
456     if (MediaStream* stream = target->toMediaStream())
457         return toV8(stream);
458
459     if (PeerConnection* peerConnection = target->toPeerConnection())
460         return toV8(peerConnection);
461 #endif
462
463     ASSERT(0);
464     return notHandledByInterceptor();
465 }
466
467 PassRefPtr<EventListener> V8DOMWrapper::getEventListener(v8::Local<v8::Value> value, bool isAttribute, ListenerLookupType lookup)
468 {
469     v8::Handle<v8::Context> context = v8::Context::GetCurrent();
470     if (context.IsEmpty())
471         return 0;
472     if (lookup == ListenerFindOnly)
473         return V8EventListenerList::findWrapper(value, isAttribute);
474     v8::Handle<v8::Object> globalPrototype = v8::Handle<v8::Object>::Cast(context->Global()->GetPrototype());
475     if (globalObjectPrototypeIsDOMWindow(globalPrototype))
476         return V8EventListenerList::findOrCreateWrapper<V8EventListener>(value, isAttribute);
477 #if ENABLE(WORKERS)
478     return V8EventListenerList::findOrCreateWrapper<V8WorkerContextEventListener>(value, isAttribute);
479 #else
480     return 0;
481 #endif
482 }
483
484 #if ENABLE(XPATH)
485 // XPath-related utilities
486 RefPtr<XPathNSResolver> V8DOMWrapper::getXPathNSResolver(v8::Handle<v8::Value> value, V8Proxy* proxy)
487 {
488     RefPtr<XPathNSResolver> resolver;
489     if (V8XPathNSResolver::HasInstance(value))
490         resolver = V8XPathNSResolver::toNative(v8::Handle<v8::Object>::Cast(value));
491     else if (value->IsObject())
492         resolver = V8CustomXPathNSResolver::create(value->ToObject());
493     return resolver;
494 }
495 #endif
496
497 }  // namespace WebCore