Always enable ENABLE(XPATH)
[WebKit-https.git] / 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 v8::Local<v8::Object> V8DOMWrapper::instantiateV8Object(V8Proxy* proxy, WrapperTypeInfo* type, void* impl)
234 {
235 #if ENABLE(WORKERS)
236     WorkerContext* workerContext = 0;
237 #endif
238     if (V8IsolatedContext::getEntered()) {
239         // This effectively disables the wrapper cache for isolated worlds.
240         proxy = 0;
241         // FIXME: Do we need a wrapper cache for the isolated world?  We should
242         //        see if the performance gains are worth while.
243         // We'll get one once we give the isolated context a proper window shell.
244     } else if (!proxy) {
245         v8::Handle<v8::Context> context = v8::Context::GetCurrent();
246         if (!context.IsEmpty()) {
247             v8::Handle<v8::Object> globalPrototype = v8::Handle<v8::Object>::Cast(context->Global()->GetPrototype());
248             if (isWrapperOfType(globalPrototype, &V8DOMWindow::info))
249                 proxy = V8Proxy::retrieve(V8DOMWindow::toNative(globalPrototype)->frame());
250 #if ENABLE(WORKERS)
251             else
252                 workerContext = V8WorkerContext::toNative(lookupDOMWrapper(V8WorkerContext::GetTemplate(), context->Global()));
253 #endif
254         }
255     }
256
257     v8::Local<v8::Object> instance;
258     if (proxy)
259         // FIXME: Fix this to work properly with isolated worlds (see above).
260         instance = proxy->windowShell()->createWrapperFromCache(type);
261     else {
262         v8::Local<v8::Function> function;
263 #if ENABLE(WORKERS)
264         if (workerContext)
265             function = getConstructor(type, workerContext);
266         else
267 #endif
268             function = type->getTemplate()->GetFunction();
269         instance = SafeAllocation::newInstance(function);
270     }
271     if (!instance.IsEmpty()) {
272         // Avoid setting the DOM wrapper for failed allocations.
273         setDOMWrapper(instance, type, impl);
274         if (type == &V8HTMLDocument::info)
275             instance = V8HTMLDocument::WrapInShadowObject(instance, static_cast<Node*>(impl));
276     }
277     return instance;
278 }
279
280 #ifndef NDEBUG
281 bool V8DOMWrapper::maybeDOMWrapper(v8::Handle<v8::Value> value)
282 {
283     if (value.IsEmpty() || !value->IsObject())
284         return false;
285
286     v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(value);
287     if (!object->InternalFieldCount())
288         return false;
289
290     ASSERT(object->InternalFieldCount() >= v8DefaultWrapperInternalFieldCount);
291
292     v8::Handle<v8::Value> wrapper = object->GetInternalField(v8DOMWrapperObjectIndex);
293     ASSERT(wrapper->IsNumber() || wrapper->IsExternal());
294
295     return true;
296 }
297 #endif
298
299 bool V8DOMWrapper::isValidDOMObject(v8::Handle<v8::Value> value)
300 {
301     if (value.IsEmpty() || !value->IsObject())
302         return false;
303     return v8::Handle<v8::Object>::Cast(value)->InternalFieldCount();
304 }
305
306 bool V8DOMWrapper::isWrapperOfType(v8::Handle<v8::Value> value, WrapperTypeInfo* type)
307 {
308     if (!isValidDOMObject(value))
309         return false;
310
311     v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(value);
312     ASSERT(object->InternalFieldCount() >= v8DefaultWrapperInternalFieldCount);
313
314     v8::Handle<v8::Value> wrapper = object->GetInternalField(v8DOMWrapperObjectIndex);
315     ASSERT(wrapper->IsNumber() || wrapper->IsExternal());
316
317     WrapperTypeInfo* typeInfo = static_cast<WrapperTypeInfo*>(object->GetPointerFromInternalField(v8DOMWrapperTypeIndex));
318     return typeInfo == type;
319 }
320
321 v8::Handle<v8::Object> V8DOMWrapper::getWrapperSlow(Node* node)
322 {
323     V8IsolatedContext* context = V8IsolatedContext::getEntered();
324     if (LIKELY(!context)) {
325         v8::Persistent<v8::Object>* wrapper = node->wrapper();
326         if (!wrapper)
327             return v8::Handle<v8::Object>();
328         return *wrapper;
329     }
330     DOMNodeMapping& domNodeMap = context->world()->domDataStore()->domNodeMap();
331     return domNodeMap.get(node);
332 }
333
334 // A JS object of type EventTarget is limited to a small number of possible classes.
335 // Check EventTarget.h for new type conversion methods
336 v8::Handle<v8::Value> V8DOMWrapper::convertEventTargetToV8Object(EventTarget* target)
337 {
338     if (!target)
339         return v8::Null();
340
341 #if ENABLE(SVG)
342     if (SVGElementInstance* instance = target->toSVGElementInstance())
343         return toV8(instance);
344 #endif
345
346 #if ENABLE(WORKERS)
347     if (Worker* worker = target->toWorker())
348         return toV8(worker);
349
350     if (DedicatedWorkerContext* workerContext = target->toDedicatedWorkerContext())
351         return toV8(workerContext);
352 #endif // WORKERS
353
354 #if ENABLE(SHARED_WORKERS)
355     if (SharedWorker* sharedWorker = target->toSharedWorker())
356         return toV8(sharedWorker);
357
358     if (SharedWorkerContext* sharedWorkerContext = target->toSharedWorkerContext())
359         return toV8(sharedWorkerContext);
360 #endif // SHARED_WORKERS
361
362 #if ENABLE(NOTIFICATIONS)
363     if (Notification* notification = target->toNotification())
364         return toV8(notification);
365 #endif
366
367 #if ENABLE(INDEXED_DATABASE)
368     if (IDBDatabase* idbDatabase = target->toIDBDatabase())
369         return toV8(idbDatabase);
370     if (IDBRequest* idbRequest = target->toIDBRequest())
371         return toV8(idbRequest);
372     if (IDBTransaction* idbTransaction = target->toIDBTransaction())
373         return toV8(idbTransaction);
374 #endif
375
376 #if ENABLE(WEB_SOCKETS)
377     if (WebSocket* webSocket = target->toWebSocket())
378         return toV8(webSocket);
379 #endif
380
381     if (Node* node = target->toNode())
382         return toV8(node);
383
384     if (DOMWindow* domWindow = target->toDOMWindow())
385         return toV8(domWindow);
386
387     // XMLHttpRequest is created within its JS counterpart.
388     if (XMLHttpRequest* xmlHttpRequest = target->toXMLHttpRequest()) {
389         v8::Handle<v8::Object> wrapper = getActiveDOMObjectMap().get(xmlHttpRequest);
390         ASSERT(!wrapper.IsEmpty());
391         return wrapper;
392     }
393
394     // MessagePort is created within its JS counterpart
395     if (MessagePort* port = target->toMessagePort()) {
396         v8::Handle<v8::Object> wrapper = getActiveDOMObjectMap().get(port);
397         ASSERT(!wrapper.IsEmpty());
398         return wrapper;
399     }
400
401     if (XMLHttpRequestUpload* upload = target->toXMLHttpRequestUpload()) {
402         v8::Handle<v8::Object> wrapper = getDOMObjectMap().get(upload);
403         ASSERT(!wrapper.IsEmpty());
404         return wrapper;
405     }
406
407     if (DOMApplicationCache* domAppCache = target->toDOMApplicationCache())
408         return toV8(domAppCache);
409
410     if (EventSource* eventSource = target->toEventSource())
411         return toV8(eventSource);
412
413 #if ENABLE(BLOB)
414     if (FileReader* fileReader = target->toFileReader())
415         return toV8(fileReader);
416 #endif
417
418 #if ENABLE(FILE_SYSTEM)
419     if (FileWriter* fileWriter = target->toFileWriter())
420         return toV8(fileWriter);
421 #endif
422
423 #if ENABLE(WEB_AUDIO)
424     if (JavaScriptAudioNode* jsAudioNode = target->toJavaScriptAudioNode())
425         return toV8(jsAudioNode);
426     if (AudioContext* audioContext = target->toAudioContext())
427         return toV8(audioContext);
428 #endif    
429
430 #if ENABLE(MEDIA_STREAM)
431     if (LocalMediaStream* stream = target->toLocalMediaStream())
432         return toV8(stream);
433
434     if (MediaStream* stream = target->toMediaStream())
435         return toV8(stream);
436
437     if (PeerConnection* peerConnection = target->toPeerConnection())
438         return toV8(peerConnection);
439 #endif
440
441     ASSERT(0);
442     return notHandledByInterceptor();
443 }
444
445 PassRefPtr<EventListener> V8DOMWrapper::getEventListener(v8::Local<v8::Value> value, bool isAttribute, ListenerLookupType lookup)
446 {
447     v8::Handle<v8::Context> context = v8::Context::GetCurrent();
448     if (context.IsEmpty())
449         return 0;
450     if (lookup == ListenerFindOnly)
451         return V8EventListenerList::findWrapper(value, isAttribute);
452     v8::Handle<v8::Object> globalPrototype = v8::Handle<v8::Object>::Cast(context->Global()->GetPrototype());
453     if (isWrapperOfType(globalPrototype, &V8DOMWindow::info))
454         return V8EventListenerList::findOrCreateWrapper<V8EventListener>(value, isAttribute);
455 #if ENABLE(WORKERS)
456     return V8EventListenerList::findOrCreateWrapper<V8WorkerContextEventListener>(value, isAttribute);
457 #else
458     return 0;
459 #endif
460 }
461
462 // XPath-related utilities
463 RefPtr<XPathNSResolver> V8DOMWrapper::getXPathNSResolver(v8::Handle<v8::Value> value, V8Proxy* proxy)
464 {
465     RefPtr<XPathNSResolver> resolver;
466     if (V8XPathNSResolver::HasInstance(value))
467         resolver = V8XPathNSResolver::toNative(v8::Handle<v8::Object>::Cast(value));
468     else if (value->IsObject())
469         resolver = V8CustomXPathNSResolver::create(value->ToObject());
470     return resolver;
471 }
472
473 }  // namespace WebCore