blob: 1b45891118f757971a8f0d1709dbacfdc98fcad9 [file] [log] [blame]
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +01001/*
2* Copyright (C) 2006, 2007, 2008, 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
33#include "bindings/v8/V8NPObject.h"
34
35#include "V8HTMLAppletElement.h"
36#include "V8HTMLEmbedElement.h"
37#include "V8HTMLObjectElement.h"
38#include "bindings/v8/NPV8Object.h"
39#include "bindings/v8/V8Binding.h"
40#include "bindings/v8/V8NPUtils.h"
41#include "bindings/v8/V8ObjectConstructor.h"
42#include "bindings/v8/npruntime_impl.h"
43#include "bindings/v8/npruntime_priv.h"
44#include "core/html/HTMLPlugInElement.h"
45#include "wtf/OwnArrayPtr.h"
46
47namespace WebCore {
48
49enum InvokeFunctionType {
50 InvokeMethod = 1,
51 InvokeConstruct = 2,
52 InvokeDefault = 3
53};
54
55struct IdentifierRep {
56 int number() const { return m_isString ? 0 : m_value.m_number; }
57 const char* string() const { return m_isString ? m_value.m_string : 0; }
58
59 union {
60 const char* m_string;
61 int m_number;
62 } m_value;
63 bool m_isString;
64};
65
66// FIXME: need comments.
67// Params: holder could be HTMLEmbedElement or NPObject
68static v8::Handle<v8::Value> npObjectInvokeImpl(const v8::Arguments& args, InvokeFunctionType functionId)
69{
70 NPObject* npObject;
71
72 WrapperWorldType currentWorldType = worldType(args.GetIsolate());
73 // These three types are subtypes of HTMLPlugInElement.
74 if (V8HTMLAppletElement::HasInstance(args.Holder(), args.GetIsolate(), currentWorldType) || V8HTMLEmbedElement::HasInstance(args.Holder(), args.GetIsolate(), currentWorldType)
75 || V8HTMLObjectElement::HasInstance(args.Holder(), args.GetIsolate(), currentWorldType)) {
76 // The holder object is a subtype of HTMLPlugInElement.
77 HTMLPlugInElement* element;
78 if (V8HTMLAppletElement::HasInstance(args.Holder(), args.GetIsolate(), currentWorldType))
79 element = V8HTMLAppletElement::toNative(args.Holder());
80 else if (V8HTMLEmbedElement::HasInstance(args.Holder(), args.GetIsolate(), currentWorldType))
81 element = V8HTMLEmbedElement::toNative(args.Holder());
82 else
83 element = V8HTMLObjectElement::toNative(args.Holder());
84 ScriptInstance scriptInstance = element->getInstance();
85 if (scriptInstance)
86 npObject = v8ObjectToNPObject(scriptInstance->instance());
87 else
88 npObject = 0;
89 } else {
90 // The holder object is not a subtype of HTMLPlugInElement, it must be an NPObject which has three
91 // internal fields.
92 if (args.Holder()->InternalFieldCount() != npObjectInternalFieldCount)
93 return throwError(v8ReferenceError, "NPMethod called on non-NPObject", args.GetIsolate());
94
95 npObject = v8ObjectToNPObject(args.Holder());
96 }
97
98 // Verify that our wrapper wasn't using a NPObject which has already been deleted.
99 if (!npObject || !_NPN_IsAlive(npObject))
100 return throwError(v8ReferenceError, "NPObject deleted", args.GetIsolate());
101
102 // Wrap up parameters.
103 int numArgs = args.Length();
104 OwnArrayPtr<NPVariant> npArgs = adoptArrayPtr(new NPVariant[numArgs]);
105
106 for (int i = 0; i < numArgs; i++)
107 convertV8ObjectToNPVariant(args[i], npObject, &npArgs[i]);
108
109 NPVariant result;
110 VOID_TO_NPVARIANT(result);
111
112 bool retval = true;
113 switch (functionId) {
114 case InvokeMethod:
115 if (npObject->_class->invoke) {
116 v8::Handle<v8::String> functionName(v8::String::Cast(*args.Data()));
117 NPIdentifier identifier = getStringIdentifier(functionName);
118 retval = npObject->_class->invoke(npObject, identifier, npArgs.get(), numArgs, &result);
119 }
120 break;
121 case InvokeConstruct:
122 if (npObject->_class->construct)
123 retval = npObject->_class->construct(npObject, npArgs.get(), numArgs, &result);
124 break;
125 case InvokeDefault:
126 if (npObject->_class->invokeDefault)
127 retval = npObject->_class->invokeDefault(npObject, npArgs.get(), numArgs, &result);
128 break;
129 default:
130 break;
131 }
132
133 if (!retval)
134 throwError(v8GeneralError, "Error calling method on NPObject.", args.GetIsolate());
135
136 for (int i = 0; i < numArgs; i++)
137 _NPN_ReleaseVariantValue(&npArgs[i]);
138
139 // Unwrap return values.
140 v8::Handle<v8::Value> returnValue;
141 if (_NPN_IsAlive(npObject))
142 returnValue = convertNPVariantToV8Object(&result, npObject, args.GetIsolate());
143 _NPN_ReleaseVariantValue(&result);
144
145 return returnValue;
146}
147
148
149v8::Handle<v8::Value> npObjectMethodHandler(const v8::Arguments& args)
150{
151 return npObjectInvokeImpl(args, InvokeMethod);
152}
153
154
155v8::Handle<v8::Value> npObjectInvokeDefaultHandler(const v8::Arguments& args)
156{
157 if (args.IsConstructCall())
158 return npObjectInvokeImpl(args, InvokeConstruct);
159
160 return npObjectInvokeImpl(args, InvokeDefault);
161}
162
163class V8NPTemplateMap {
164 friend class WeakHandleListener<V8NPTemplateMap, PrivateIdentifier>;
165public:
166 // NPIdentifier is PrivateIdentifier*.
167 typedef HashMap<PrivateIdentifier*, v8::Persistent<v8::FunctionTemplate> > MapType;
168
169 v8::Persistent<v8::FunctionTemplate> get(PrivateIdentifier* key)
170 {
171 return m_map.get(key);
172 }
173
174 void set(PrivateIdentifier* key, v8::Persistent<v8::FunctionTemplate> wrapper)
175 {
176 ASSERT(!m_map.contains(key));
177 m_map.set(key, wrapper);
178 WeakHandleListener<V8NPTemplateMap, PrivateIdentifier>::makeWeak(m_isolate, wrapper, key);
179 }
180
181 static V8NPTemplateMap& sharedInstance(v8::Isolate* isolate)
182 {
183 DEFINE_STATIC_LOCAL(V8NPTemplateMap, map, (isolate));
184 ASSERT(isolate == map.m_isolate);
185 return map;
186 }
187
188private:
189 explicit V8NPTemplateMap(v8::Isolate* isolate)
190 : m_isolate(isolate)
191 {
192 }
193
194 void dispose(PrivateIdentifier* key)
195 {
196 MapType::iterator it = m_map.find(key);
197 ASSERT(it != m_map.end());
198 it->value.Dispose(m_isolate);
199 it->value.Clear();
200 m_map.remove(it);
201 }
202
203 MapType m_map;
204 v8::Isolate* m_isolate;
205};
206
207template<>
208void WeakHandleListener<V8NPTemplateMap, PrivateIdentifier>::callback(v8::Isolate* isolate, v8::Persistent<v8::Value>, PrivateIdentifier* key)
209{
210 V8NPTemplateMap::sharedInstance(isolate).dispose(key);
211}
212
213static v8::Handle<v8::Value> npObjectGetProperty(v8::Local<v8::Object> self, NPIdentifier identifier, v8::Local<v8::Value> key, v8::Isolate* isolate)
214{
215 NPObject* npObject = v8ObjectToNPObject(self);
216
217 // Verify that our wrapper wasn't using a NPObject which
218 // has already been deleted.
219 if (!npObject || !_NPN_IsAlive(npObject))
220 return throwError(v8ReferenceError, "NPObject deleted", isolate);
221
222
223 if (npObject->_class->hasProperty && npObject->_class->getProperty && npObject->_class->hasProperty(npObject, identifier)) {
224 if (!_NPN_IsAlive(npObject))
225 return throwError(v8ReferenceError, "NPObject deleted", isolate);
226
227 NPVariant result;
228 VOID_TO_NPVARIANT(result);
229 if (!npObject->_class->getProperty(npObject, identifier, &result))
230 return v8Undefined();
231
232 v8::Handle<v8::Value> returnValue;
233 if (_NPN_IsAlive(npObject))
234 returnValue = convertNPVariantToV8Object(&result, npObject, isolate);
235 _NPN_ReleaseVariantValue(&result);
236 return returnValue;
237
238 }
239
240 if (!_NPN_IsAlive(npObject))
241 return throwError(v8ReferenceError, "NPObject deleted", isolate);
242
243 if (key->IsString() && npObject->_class->hasMethod && npObject->_class->hasMethod(npObject, identifier)) {
244 if (!_NPN_IsAlive(npObject))
245 return throwError(v8ReferenceError, "NPObject deleted", isolate);
246
247 PrivateIdentifier* id = static_cast<PrivateIdentifier*>(identifier);
248 v8::Persistent<v8::FunctionTemplate> functionTemplate = V8NPTemplateMap::sharedInstance(isolate).get(id);
249 // Cache templates using identifier as the key.
250 if (functionTemplate.IsEmpty()) {
251 // Create a new template.
252 v8::Local<v8::FunctionTemplate> temp = v8::FunctionTemplate::New();
253 temp->SetCallHandler(npObjectMethodHandler, key);
Torne (Richard Coles)e5249552013-05-15 11:35:13 +0100254 functionTemplate.Reset(isolate, temp);
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100255 V8NPTemplateMap::sharedInstance(isolate).set(id, functionTemplate);
256 }
257
258 // FunctionTemplate caches function for each context.
259 v8::Local<v8::Function> v8Function = functionTemplate->GetFunction();
260 v8Function->SetName(v8::Handle<v8::String>::Cast(key));
261 return v8Function;
262 }
263
264 return v8Undefined();
265}
266
267v8::Handle<v8::Value> npObjectNamedPropertyGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info)
268{
269 NPIdentifier identifier = getStringIdentifier(name);
270 return npObjectGetProperty(info.Holder(), identifier, name, info.GetIsolate());
271}
272
273v8::Handle<v8::Value> npObjectIndexedPropertyGetter(uint32_t index, const v8::AccessorInfo& info)
274{
275 NPIdentifier identifier = _NPN_GetIntIdentifier(index);
276 return npObjectGetProperty(info.Holder(), identifier, v8::Number::New(index), info.GetIsolate());
277}
278
279v8::Handle<v8::Value> npObjectGetNamedProperty(v8::Local<v8::Object> self, v8::Local<v8::String> name, const v8::AccessorInfo& info)
280{
281 NPIdentifier identifier = getStringIdentifier(name);
282 return npObjectGetProperty(self, identifier, name, info.GetIsolate());
283}
284
285v8::Handle<v8::Value> npObjectGetIndexedProperty(v8::Local<v8::Object> self, uint32_t index, const v8::AccessorInfo& info)
286{
287 NPIdentifier identifier = _NPN_GetIntIdentifier(index);
288 return npObjectGetProperty(self, identifier, v8::Number::New(index), info.GetIsolate());
289}
290
291v8::Handle<v8::Integer> npObjectQueryProperty(v8::Local<v8::String> name, const v8::AccessorInfo& info)
292{
293 NPIdentifier identifier = getStringIdentifier(name);
294 return npObjectGetProperty(info.Holder(), identifier, name, info.GetIsolate()).IsEmpty() ? v8::Handle<v8::Integer>() : v8Integer(0, info.GetIsolate());
295}
296
297static v8::Handle<v8::Value> npObjectSetProperty(v8::Local<v8::Object> self, NPIdentifier identifier, v8::Local<v8::Value> value, v8::Isolate* isolate)
298{
299 NPObject* npObject = v8ObjectToNPObject(self);
300
301 // Verify that our wrapper wasn't using a NPObject which has already been deleted.
302 if (!npObject || !_NPN_IsAlive(npObject)) {
303 throwError(v8ReferenceError, "NPObject deleted", isolate);
304 return value; // Intercepted, but an exception was thrown.
305 }
306
307 if (npObject->_class->hasProperty && npObject->_class->setProperty && npObject->_class->hasProperty(npObject, identifier)) {
308 if (!_NPN_IsAlive(npObject))
309 return throwError(v8ReferenceError, "NPObject deleted", isolate);
310
311 NPVariant npValue;
312 VOID_TO_NPVARIANT(npValue);
313 convertV8ObjectToNPVariant(value, npObject, &npValue);
314 bool success = npObject->_class->setProperty(npObject, identifier, &npValue);
315 _NPN_ReleaseVariantValue(&npValue);
316 if (success)
317 return value; // Intercept the call.
318 }
319 return v8Undefined();
320}
321
322
323v8::Handle<v8::Value> npObjectNamedPropertySetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info)
324{
325 NPIdentifier identifier = getStringIdentifier(name);
326 return npObjectSetProperty(info.Holder(), identifier, value, info.GetIsolate());
327}
328
329
330v8::Handle<v8::Value> npObjectIndexedPropertySetter(uint32_t index, v8::Local<v8::Value> value, const v8::AccessorInfo& info)
331{
332 NPIdentifier identifier = _NPN_GetIntIdentifier(index);
333 return npObjectSetProperty(info.Holder(), identifier, value, info.GetIsolate());
334}
335
336v8::Handle<v8::Value> npObjectSetNamedProperty(v8::Local<v8::Object> self, v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info)
337{
338 NPIdentifier identifier = getStringIdentifier(name);
339 return npObjectSetProperty(self, identifier, value, info.GetIsolate());
340}
341
342v8::Handle<v8::Value> npObjectSetIndexedProperty(v8::Local<v8::Object> self, uint32_t index, v8::Local<v8::Value> value, const v8::AccessorInfo& info)
343{
344 NPIdentifier identifier = _NPN_GetIntIdentifier(index);
345 return npObjectSetProperty(self, identifier, value, info.GetIsolate());
346}
347
348v8::Handle<v8::Array> npObjectPropertyEnumerator(const v8::AccessorInfo& info, bool namedProperty)
349{
350 NPObject* npObject = v8ObjectToNPObject(info.Holder());
351
352 // Verify that our wrapper wasn't using a NPObject which
353 // has already been deleted.
354 if (!npObject || !_NPN_IsAlive(npObject))
355 throwError(v8ReferenceError, "NPObject deleted", info.GetIsolate());
356
357 if (NP_CLASS_STRUCT_VERSION_HAS_ENUM(npObject->_class) && npObject->_class->enumerate) {
358 uint32_t count;
359 NPIdentifier* identifiers;
360 if (npObject->_class->enumerate(npObject, &identifiers, &count)) {
361 v8::Handle<v8::Array> properties = v8::Array::New(count);
362 for (uint32_t i = 0; i < count; ++i) {
363 IdentifierRep* identifier = static_cast<IdentifierRep*>(identifiers[i]);
364 if (namedProperty)
365 properties->Set(v8Integer(i, info.GetIsolate()), v8::String::NewSymbol(identifier->string()));
366 else
367 properties->Set(v8Integer(i, info.GetIsolate()), v8Integer(identifier->number(), info.GetIsolate()));
368 }
369
370 return properties;
371 }
372 }
373
374 return v8::Handle<v8::Array>();
375}
376
377v8::Handle<v8::Array> npObjectNamedPropertyEnumerator(const v8::AccessorInfo& info)
378{
379 return npObjectPropertyEnumerator(info, true);
380}
381
382v8::Handle<v8::Array> npObjectIndexedPropertyEnumerator(const v8::AccessorInfo& info)
383{
384 return npObjectPropertyEnumerator(info, false);
385}
386
387static DOMWrapperMap<NPObject>& staticNPObjectMap()
388{
389 DEFINE_STATIC_LOCAL(DOMWrapperMap<NPObject>, npObjectMap, (v8::Isolate::GetCurrent()));
390 return npObjectMap;
391}
392
393template<>
394inline void WeakHandleListener<DOMWrapperMap<NPObject> >::callback(v8::Isolate* isolate, v8::Persistent<v8::Value> value, DOMWrapperMap<NPObject>*)
395{
396 ASSERT(value->IsObject());
397 v8::Persistent<v8::Object> wrapper = v8::Persistent<v8::Object>::Cast(value);
398 NPObject* npObject = static_cast<NPObject*>(toNative(wrapper));
399
400 ASSERT(npObject);
401 ASSERT(staticNPObjectMap().get(npObject) == wrapper);
402
403 // Must remove from our map before calling _NPN_ReleaseObject(). _NPN_ReleaseObject can
404 // call forgetV8ObjectForNPObject, which uses the table as well.
405 staticNPObjectMap().removeAndDispose(npObject, wrapper, isolate);
406
407 if (_NPN_IsAlive(npObject))
408 _NPN_ReleaseObject(npObject);
409}
410
411v8::Local<v8::Object> createV8ObjectForNPObject(NPObject* object, NPObject* root)
412{
413 static v8::Persistent<v8::FunctionTemplate> npObjectDesc;
414
415 ASSERT(v8::Context::InContext());
416
417 // If this is a v8 object, just return it.
418 if (object->_class == npScriptObjectClass) {
419 V8NPObject* v8NPObject = reinterpret_cast<V8NPObject*>(object);
420 return v8::Local<v8::Object>::New(v8NPObject->v8Object);
421 }
422
423 // If we've already wrapped this object, just return it.
424 v8::Handle<v8::Object> wrapper = staticNPObjectMap().get(object);
425 if (!wrapper.IsEmpty())
426 return v8::Local<v8::Object>::New(wrapper);
427
428 // FIXME: we should create a Wrapper type as a subclass of JSObject. It has two internal fields, field 0 is the wrapped
429 // pointer, and field 1 is the type. There should be an api function that returns unused type id. The same Wrapper type
430 // can be used by DOM bindings.
431 v8::Isolate* isolate = v8::Isolate::GetCurrent();
432 if (npObjectDesc.IsEmpty()) {
Torne (Richard Coles)e5249552013-05-15 11:35:13 +0100433 npObjectDesc.Reset(isolate, v8::FunctionTemplate::New());
Torne (Richard Coles)53e740f2013-05-09 18:38:43 +0100434 npObjectDesc->InstanceTemplate()->SetInternalFieldCount(npObjectInternalFieldCount);
435 npObjectDesc->InstanceTemplate()->SetNamedPropertyHandler(npObjectNamedPropertyGetter, npObjectNamedPropertySetter, npObjectQueryProperty, 0, npObjectNamedPropertyEnumerator);
436 npObjectDesc->InstanceTemplate()->SetIndexedPropertyHandler(npObjectIndexedPropertyGetter, npObjectIndexedPropertySetter, 0, 0, npObjectIndexedPropertyEnumerator);
437 npObjectDesc->InstanceTemplate()->SetCallAsFunctionHandler(npObjectInvokeDefaultHandler);
438 }
439
440 // FIXME: Move staticNPObjectMap() to DOMDataStore.
441 // Use V8DOMWrapper::createWrapper() and
442 // V8DOMWrapper::associateObjectWithWrapper()
443 // to create a wrapper object.
444 v8::Handle<v8::Function> v8Function = npObjectDesc->GetFunction();
445 v8::Local<v8::Object> value = V8ObjectConstructor::newInstance(v8Function);
446 if (value.IsEmpty())
447 return value;
448
449 V8DOMWrapper::setNativeInfo(value, npObjectTypeInfo(), object);
450
451 // KJS retains the object as part of its wrapper (see Bindings::CInstance).
452 _NPN_RetainObject(object);
453 _NPN_RegisterObject(object, root);
454
455 WrapperConfiguration configuration = buildWrapperConfiguration(object, WrapperConfiguration::Dependent);
456 staticNPObjectMap().set(object, value, configuration);
457 ASSERT(V8DOMWrapper::maybeDOMWrapper(value));
458 return value;
459}
460
461void forgetV8ObjectForNPObject(NPObject* object)
462{
463 v8::Handle<v8::Object> wrapper = staticNPObjectMap().get(object);
464 if (!wrapper.IsEmpty()) {
465 v8::HandleScope scope;
466 V8DOMWrapper::clearNativeInfo(wrapper, npObjectTypeInfo());
467 staticNPObjectMap().removeAndDispose(object, wrapper, v8::Isolate::GetCurrent());
468 _NPN_ReleaseObject(object);
469 }
470}
471
472} // namespace WebCore