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.
32 #include "V8DOMWrapper.h"
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"
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"
65 #include "V8NodeFilterCondition.h"
66 #include "V8NodeList.h"
67 #include "V8Notification.h"
68 #include "V8PeerConnection.h"
70 #include "V8SharedWorker.h"
71 #include "V8SharedWorkerContext.h"
72 #include "V8StyleSheet.h"
73 #include "V8WebSocket.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"
84 #include "SVGElementInstance.h"
85 #include "SVGPathSeg.h"
86 #include "V8SVGElementInstance.h"
90 #include "V8AudioContext.h"
91 #include "V8JavaScriptAudioNode.h"
97 #include <wtf/Assertions.h>
98 #include <wtf/OwnArrayPtr.h>
99 #include <wtf/StdLibExtras.h>
100 #include <wtf/UnusedParam.h>
104 typedef HashMap<Node*, v8::Object*> DOMNodeMap;
105 typedef HashMap<void*, v8::Object*> DOMObjectMap;
107 // The caller must have increased obj's ref count.
108 void V8DOMWrapper::setJSWrapperForDOMObject(void* object, v8::Persistent<v8::Object> wrapper)
110 ASSERT(V8DOMWrapper::maybeDOMWrapper(wrapper));
111 ASSERT(!domWrapperType(wrapper)->toActiveDOMObjectFunction);
112 getDOMObjectMap().set(object, wrapper);
115 // The caller must have increased obj's ref count.
116 void V8DOMWrapper::setJSWrapperForActiveDOMObject(void* object, v8::Persistent<v8::Object> wrapper)
118 ASSERT(V8DOMWrapper::maybeDOMWrapper(wrapper));
119 ASSERT(domWrapperType(wrapper)->toActiveDOMObjectFunction);
120 getActiveDOMObjectMap().set(object, wrapper);
123 // The caller must have increased node's ref count.
124 void V8DOMWrapper::setJSWrapperForDOMNode(Node* node, v8::Persistent<v8::Object> wrapper)
126 ASSERT(V8DOMWrapper::maybeDOMWrapper(wrapper));
127 getDOMNodeMap().set(node, wrapper);
130 v8::Local<v8::Function> V8DOMWrapper::getConstructor(WrapperTypeInfo* type, v8::Handle<v8::Value> objectPrototype)
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
144 v8::TryCatch tryCatch;
145 v8::Local<v8::Function> value = functionTemplate->GetFunction();
147 return v8::Local<v8::Function>();
148 // Hotmail fix, see comments above.
149 if (!objectPrototype.IsEmpty())
150 value->SetPrototype(objectPrototype);
154 v8::Local<v8::Function> V8DOMWrapper::getConstructorForContext(WrapperTypeInfo* type, v8::Handle<v8::Context> context)
156 // Enter the scope for this context to get the correct constructor.
157 v8::Context::Scope scope(context);
159 return getConstructor(type, V8DOMWindowShell::getHiddenObjectPrototype(context));
162 v8::Local<v8::Function> V8DOMWrapper::getConstructor(WrapperTypeInfo* type, DOMWindow* window)
164 Frame* frame = window->frame();
166 return v8::Local<v8::Function>();
168 v8::Handle<v8::Context> context = V8Proxy::context(frame);
169 if (context.IsEmpty())
170 return v8::Local<v8::Function>();
172 return getConstructorForContext(type, context);
176 v8::Local<v8::Function> V8DOMWrapper::getConstructor(WrapperTypeInfo* type, WorkerContext*)
178 WorkerScriptController* controller = WorkerScriptController::controllerForContext();
179 WorkerContextExecutionProxy* proxy = controller ? controller->proxy() : 0;
181 return v8::Local<v8::Function>();
183 v8::Handle<v8::Context> context = proxy->context();
184 if (context.IsEmpty())
185 return v8::Local<v8::Function>();
187 return getConstructorForContext(type, context);
192 void V8DOMWrapper::setNamedHiddenReference(v8::Handle<v8::Object> parent, const char* name, v8::Handle<v8::Value> child)
194 parent->SetHiddenValue(V8HiddenPropertyName::hiddenReferenceName(name), child);
197 void V8DOMWrapper::setNamedHiddenWindowReference(Frame* frame, const char* name, v8::Handle<v8::Value> jsObject)
201 return; // Object might be detached from window
202 v8::Handle<v8::Context> context = V8Proxy::context(frame);
203 if (context.IsEmpty())
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());
211 setNamedHiddenReference(global, name, jsObject);
214 WrapperTypeInfo* V8DOMWrapper::domWrapperType(v8::Handle<v8::Object> object)
216 ASSERT(V8DOMWrapper::maybeDOMWrapper(object));
217 return static_cast<WrapperTypeInfo*>(object->GetPointerFromInternalField(v8DOMWrapperTypeIndex));
220 PassRefPtr<NodeFilter> V8DOMWrapper::wrapNativeNodeFilter(v8::Handle<v8::Value> filter)
222 // A NodeFilter is used when walking through a DOM tree or iterating tree
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));
233 static bool globalObjectPrototypeIsDOMWindow(v8::Handle<v8::Object> objectPrototype)
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.
239 COMPILE_ASSERT(V8DOMWindow::internalFieldCount != V8WorkerContext::internalFieldCount,
240 DOMWindowAndWorkerContextHaveUnequalFieldCounts);
241 COMPILE_ASSERT(V8DOMWindow::internalFieldCount != V8DedicatedWorkerContext::internalFieldCount,
242 DOMWindowAndDedicatedWorkerContextHaveUnequalFieldCounts);
244 #if ENABLE(SHARED_WORKERS)
245 COMPILE_ASSERT(V8DOMWindow::internalFieldCount != V8SharedWorkerContext::internalFieldCount,
246 DOMWindowAndSharedWorkerContextHaveUnequalFieldCounts);
248 return objectPrototype->InternalFieldCount() == V8DOMWindow::internalFieldCount;
251 v8::Local<v8::Object> V8DOMWrapper::instantiateV8Object(V8Proxy* proxy, WrapperTypeInfo* type, void* impl)
254 WorkerContext* workerContext = 0;
256 if (V8IsolatedContext::getEntered()) {
257 // This effectively disables the wrapper cache for isolated worlds.
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.
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());
270 workerContext = V8WorkerContext::toNative(lookupDOMWrapper(V8WorkerContext::GetTemplate(), context->Global()));
275 v8::Local<v8::Object> instance;
277 // FIXME: Fix this to work properly with isolated worlds (see above).
278 instance = proxy->windowShell()->createWrapperFromCache(type);
280 v8::Local<v8::Function> function;
283 function = getConstructor(type, workerContext);
286 function = type->getTemplate()->GetFunction();
287 instance = SafeAllocation::newInstance(function);
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));
299 bool V8DOMWrapper::maybeDOMWrapper(v8::Handle<v8::Value> value)
301 if (value.IsEmpty() || !value->IsObject())
304 v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(value);
305 if (!object->InternalFieldCount())
308 ASSERT(object->InternalFieldCount() >= v8DefaultWrapperInternalFieldCount);
310 v8::Handle<v8::Value> wrapper = object->GetInternalField(v8DOMWrapperObjectIndex);
311 ASSERT(wrapper->IsNumber() || wrapper->IsExternal());
317 bool V8DOMWrapper::isValidDOMObject(v8::Handle<v8::Value> value)
319 if (value.IsEmpty() || !value->IsObject())
321 return v8::Handle<v8::Object>::Cast(value)->InternalFieldCount();
324 bool V8DOMWrapper::isWrapperOfType(v8::Handle<v8::Value> value, WrapperTypeInfo* type)
326 if (!isValidDOMObject(value))
329 v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(value);
330 ASSERT(object->InternalFieldCount() >= v8DefaultWrapperInternalFieldCount);
332 v8::Handle<v8::Value> wrapper = object->GetInternalField(v8DOMWrapperObjectIndex);
333 ASSERT(wrapper->IsNumber() || wrapper->IsExternal());
335 WrapperTypeInfo* typeInfo = static_cast<WrapperTypeInfo*>(object->GetPointerFromInternalField(v8DOMWrapperTypeIndex));
336 return typeInfo == type;
339 v8::Handle<v8::Object> V8DOMWrapper::getWrapperSlow(Node* node)
341 V8IsolatedContext* context = V8IsolatedContext::getEntered();
342 if (LIKELY(!context)) {
343 v8::Persistent<v8::Object>* wrapper = node->wrapper();
345 return v8::Handle<v8::Object>();
348 DOMNodeMapping& domNodeMap = context->world()->domDataStore()->domNodeMap();
349 return domNodeMap.get(node);
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)
360 if (SVGElementInstance* instance = target->toSVGElementInstance())
361 return toV8(instance);
365 if (Worker* worker = target->toWorker())
368 if (DedicatedWorkerContext* workerContext = target->toDedicatedWorkerContext())
369 return toV8(workerContext);
372 #if ENABLE(SHARED_WORKERS)
373 if (SharedWorker* sharedWorker = target->toSharedWorker())
374 return toV8(sharedWorker);
376 if (SharedWorkerContext* sharedWorkerContext = target->toSharedWorkerContext())
377 return toV8(sharedWorkerContext);
378 #endif // SHARED_WORKERS
380 #if ENABLE(NOTIFICATIONS)
381 if (Notification* notification = target->toNotification())
382 return toV8(notification);
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);
394 #if ENABLE(WEB_SOCKETS)
395 if (WebSocket* webSocket = target->toWebSocket())
396 return toV8(webSocket);
399 if (Node* node = target->toNode())
402 if (DOMWindow* domWindow = target->toDOMWindow())
403 return toV8(domWindow);
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());
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());
419 if (XMLHttpRequestUpload* upload = target->toXMLHttpRequestUpload()) {
420 v8::Handle<v8::Object> wrapper = getDOMObjectMap().get(upload);
421 ASSERT(!wrapper.IsEmpty());
425 #if ENABLE(OFFLINE_WEB_APPLICATIONS)
426 if (DOMApplicationCache* domAppCache = target->toDOMApplicationCache())
427 return toV8(domAppCache);
430 #if ENABLE(EVENTSOURCE)
431 if (EventSource* eventSource = target->toEventSource())
432 return toV8(eventSource);
436 if (FileReader* fileReader = target->toFileReader())
437 return toV8(fileReader);
440 #if ENABLE(FILE_SYSTEM)
441 if (FileWriter* fileWriter = target->toFileWriter())
442 return toV8(fileWriter);
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);
452 #if ENABLE(MEDIA_STREAM)
453 if (LocalMediaStream* stream = target->toLocalMediaStream())
456 if (MediaStream* stream = target->toMediaStream())
459 if (PeerConnection* peerConnection = target->toPeerConnection())
460 return toV8(peerConnection);
464 return notHandledByInterceptor();
467 PassRefPtr<EventListener> V8DOMWrapper::getEventListener(v8::Local<v8::Value> value, bool isAttribute, ListenerLookupType lookup)
469 v8::Handle<v8::Context> context = v8::Context::GetCurrent();
470 if (context.IsEmpty())
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);
478 return V8EventListenerList::findOrCreateWrapper<V8WorkerContextEventListener>(value, isAttribute);
485 // XPath-related utilities
486 RefPtr<XPathNSResolver> V8DOMWrapper::getXPathNSResolver(v8::Handle<v8::Value> value, V8Proxy* proxy)
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());
497 } // namespace WebCore