2009-12-07 Victor Wang <victorw@chromium.org>
[WebKit-https.git] / WebCore / bindings / v8 / V8NPObject.cpp
1 /*
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 "V8NPObject.h"
34
35 #include "HTMLPlugInElement.h"
36 #include "IdentifierRep.h"
37 #include "NPV8Object.h"
38 #include "V8CustomBinding.h"
39 #include "V8DOMMap.h"
40 #include "V8HTMLAppletElement.h"
41 #include "V8HTMLEmbedElement.h"
42 #include "V8HTMLObjectElement.h"
43 #include "V8Helpers.h"
44 #include "V8NPUtils.h"
45 #include "V8Proxy.h"
46 #include "npruntime_impl.h"
47 #include "npruntime_priv.h"
48 #include <wtf/OwnArrayPtr.h>
49
50 using namespace WebCore;
51
52 enum InvokeFunctionType {
53     InvokeMethod = 1,
54     InvokeConstruct = 2,
55     InvokeDefault = 3
56 };
57
58 // FIXME: need comments.
59 // Params: holder could be HTMLEmbedElement or NPObject
60 static v8::Handle<v8::Value> npObjectInvokeImpl(const v8::Arguments& args, InvokeFunctionType functionId)
61 {
62     NPObject* npObject;
63
64     // These three types are subtypes of HTMLPlugInElement.
65     if (V8HTMLAppletElement::HasInstance(args.Holder()) || V8HTMLEmbedElement::HasInstance(args.Holder())
66         || V8HTMLObjectElement::HasInstance(args.Holder())) {
67         // The holder object is a subtype of HTMLPlugInElement.
68         HTMLPlugInElement* element = V8DOMWrapper::convertDOMWrapperToNode<HTMLPlugInElement>(args.Holder());
69         ScriptInstance scriptInstance = element->getInstance();
70         if (scriptInstance)
71             npObject = V8DOMWrapper::convertToNativeObject<NPObject>(V8ClassIndex::NPOBJECT, scriptInstance->instance());
72         else
73             npObject = 0;
74     } else {
75         // The holder object is not a subtype of HTMLPlugInElement, it must be an NPObject which has three
76         // internal fields.
77         if (args.Holder()->InternalFieldCount() != V8Custom::kNPObjectInternalFieldCount)
78           return throwError("NPMethod called on non-NPObject", V8Proxy::ReferenceError);
79
80         npObject = V8DOMWrapper::convertToNativeObject<NPObject>(V8ClassIndex::NPOBJECT, args.Holder());
81     }
82
83     // Verify that our wrapper wasn't using a NPObject which has already been deleted.
84     if (!npObject || !_NPN_IsAlive(npObject))
85         return throwError("NPObject deleted", V8Proxy::ReferenceError);
86
87     // Wrap up parameters.
88     int numArgs = args.Length();
89     OwnArrayPtr<NPVariant> npArgs(new NPVariant[numArgs]);
90
91     for (int i = 0; i < numArgs; i++)
92         convertV8ObjectToNPVariant(args[i], npObject, &npArgs[i]);
93
94     NPVariant result;
95     VOID_TO_NPVARIANT(result);
96
97     bool retval = true;
98     switch (functionId) {
99     case InvokeMethod:
100         if (npObject->_class->invoke) {
101             v8::Handle<v8::String> functionName(v8::String::Cast(*args.Data()));
102             NPIdentifier identifier = getStringIdentifier(functionName);
103             retval = npObject->_class->invoke(npObject, identifier, npArgs.get(), numArgs, &result);
104         }
105         break;
106     case InvokeConstruct:
107         if (npObject->_class->construct)
108             retval = npObject->_class->construct(npObject, npArgs.get(), numArgs, &result);
109         break;
110     case InvokeDefault:
111         if (npObject->_class->invokeDefault)
112             retval = npObject->_class->invokeDefault(npObject, npArgs.get(), numArgs, &result);
113         break;
114     default:
115         break;
116     }
117
118     if (!retval)
119         throwError("Error calling method on NPObject!", V8Proxy::GeneralError);
120
121     for (int i = 0; i < numArgs; i++)
122         _NPN_ReleaseVariantValue(&npArgs[i]);
123
124     // Unwrap return values.
125     v8::Handle<v8::Value> returnValue = convertNPVariantToV8Object(&result, npObject);
126     _NPN_ReleaseVariantValue(&result);
127
128     return returnValue;
129 }
130
131
132 v8::Handle<v8::Value> npObjectMethodHandler(const v8::Arguments& args)
133 {
134     return npObjectInvokeImpl(args, InvokeMethod);
135 }
136
137
138 v8::Handle<v8::Value> npObjectInvokeDefaultHandler(const v8::Arguments& args)
139 {
140     if (args.IsConstructCall())
141         return npObjectInvokeImpl(args, InvokeConstruct);
142
143     return npObjectInvokeImpl(args, InvokeDefault);
144 }
145
146
147 static void weakTemplateCallback(v8::Persistent<v8::Value>, void* parameter);
148
149 // NPIdentifier is PrivateIdentifier*.
150 static WeakReferenceMap<PrivateIdentifier, v8::FunctionTemplate> staticTemplateMap(&weakTemplateCallback);
151
152 static void weakTemplateCallback(v8::Persistent<v8::Value> object, void* parameter)
153 {
154     PrivateIdentifier* identifier = static_cast<PrivateIdentifier*>(parameter);
155     ASSERT(identifier);
156     ASSERT(staticTemplateMap.contains(identifier));
157
158     staticTemplateMap.forget(identifier);
159 }
160
161
162 static v8::Handle<v8::Value> npObjectGetProperty(v8::Local<v8::Object> self, NPIdentifier identifier, v8::Local<v8::Value> key)
163 {
164     NPObject* npObject = V8DOMWrapper::convertToNativeObject<NPObject>(V8ClassIndex::NPOBJECT, self);
165
166     // Verify that our wrapper wasn't using a NPObject which
167     // has already been deleted.
168     if (!npObject || !_NPN_IsAlive(npObject))
169         return throwError("NPObject deleted", V8Proxy::ReferenceError);
170
171
172     if (npObject->_class->hasProperty && npObject->_class->hasProperty(npObject, identifier)
173         && npObject->_class->getProperty) {
174
175         NPVariant result;
176         VOID_TO_NPVARIANT(result);
177         if (!npObject->_class->getProperty(npObject, identifier, &result))
178             return v8::Handle<v8::Value>();
179
180         v8::Handle<v8::Value> returnValue = convertNPVariantToV8Object(&result, npObject);
181         _NPN_ReleaseVariantValue(&result);
182         return returnValue;
183
184     }
185
186     if (key->IsString() && npObject->_class->hasMethod && npObject->_class->hasMethod(npObject, identifier)) {
187         PrivateIdentifier* id = static_cast<PrivateIdentifier*>(identifier);
188         v8::Persistent<v8::FunctionTemplate> functionTemplate = staticTemplateMap.get(id);
189         // Cache templates using identifier as the key.
190         if (functionTemplate.IsEmpty()) {
191             // Create a new template.
192             v8::Local<v8::FunctionTemplate> temp = v8::FunctionTemplate::New();
193             temp->SetCallHandler(npObjectMethodHandler, key);
194             functionTemplate = v8::Persistent<v8::FunctionTemplate>::New(temp);
195             staticTemplateMap.set(id, functionTemplate);
196         }
197
198         // FunctionTemplate caches function for each context.
199         v8::Local<v8::Function> v8Function = functionTemplate->GetFunction();
200         v8Function->SetName(v8::Handle<v8::String>::Cast(key));
201         return v8Function;
202     }
203
204     return v8::Handle<v8::Value>();
205 }
206
207 v8::Handle<v8::Value> npObjectNamedPropertyGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info)
208 {
209     NPIdentifier identifier = getStringIdentifier(name);
210     return npObjectGetProperty(info.Holder(), identifier, name);
211 }
212
213 v8::Handle<v8::Value> npObjectIndexedPropertyGetter(uint32_t index, const v8::AccessorInfo& info)
214 {
215     NPIdentifier identifier = _NPN_GetIntIdentifier(index);
216     return npObjectGetProperty(info.Holder(), identifier, v8::Number::New(index));
217 }
218
219 v8::Handle<v8::Value> npObjectGetNamedProperty(v8::Local<v8::Object> self, v8::Local<v8::String> name)
220 {
221     NPIdentifier identifier = getStringIdentifier(name);
222     return npObjectGetProperty(self, identifier, name);
223 }
224
225 v8::Handle<v8::Value> npObjectGetIndexedProperty(v8::Local<v8::Object> self, uint32_t index)
226 {
227     NPIdentifier identifier = _NPN_GetIntIdentifier(index);
228     return npObjectGetProperty(self, identifier, v8::Number::New(index));
229 }
230
231 static v8::Handle<v8::Value> npObjectSetProperty(v8::Local<v8::Object> self, NPIdentifier identifier, v8::Local<v8::Value> value)
232 {
233     NPObject* npObject = V8DOMWrapper::convertToNativeObject<NPObject>(V8ClassIndex::NPOBJECT, self);
234
235     // Verify that our wrapper wasn't using a NPObject which has already been deleted.
236     if (!npObject || !_NPN_IsAlive(npObject)) {
237         throwError("NPObject deleted", V8Proxy::ReferenceError);
238         return value;  // Intercepted, but an exception was thrown.
239     }
240
241     if (npObject->_class->hasProperty && npObject->_class->hasProperty(npObject, identifier)
242         && npObject->_class->setProperty) {
243
244         NPVariant npValue;
245         VOID_TO_NPVARIANT(npValue);
246         convertV8ObjectToNPVariant(value, npObject, &npValue);
247         bool success = npObject->_class->setProperty(npObject, identifier, &npValue);
248         _NPN_ReleaseVariantValue(&npValue);
249         if (success)
250             return value; // Intercept the call.
251     }
252     return notHandledByInterceptor();
253 }
254
255
256 v8::Handle<v8::Value> npObjectNamedPropertySetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info)
257 {
258     NPIdentifier identifier = getStringIdentifier(name);
259     return npObjectSetProperty(info.Holder(), identifier, value);
260 }
261
262
263 v8::Handle<v8::Value> npObjectIndexedPropertySetter(uint32_t index, v8::Local<v8::Value> value, const v8::AccessorInfo& info)
264 {
265     NPIdentifier identifier = _NPN_GetIntIdentifier(index);
266     return npObjectSetProperty(info.Holder(), identifier, value);
267 }
268
269 v8::Handle<v8::Value> npObjectSetNamedProperty(v8::Local<v8::Object> self, v8::Local<v8::String> name, v8::Local<v8::Value> value)
270 {
271     NPIdentifier identifier = getStringIdentifier(name);
272     return npObjectSetProperty(self, identifier, value);
273 }
274
275 v8::Handle<v8::Value> npObjectSetIndexedProperty(v8::Local<v8::Object> self, uint32_t index, v8::Local<v8::Value> value)
276 {
277     NPIdentifier identifier = _NPN_GetIntIdentifier(index);
278     return npObjectSetProperty(self, identifier, value);
279 }
280
281 v8::Handle<v8::Array> npObjectPropertyEnumerator(const v8::AccessorInfo& info, bool namedProperty)
282 {
283     NPObject* npObject = V8DOMWrapper::convertToNativeObject<NPObject>(V8ClassIndex::NPOBJECT, info.Holder());
284
285     // Verify that our wrapper wasn't using a NPObject which
286     // has already been deleted.
287     if (!npObject || !_NPN_IsAlive(npObject))
288         throwError("NPObject deleted", V8Proxy::ReferenceError);
289
290     if (NP_CLASS_STRUCT_VERSION_HAS_ENUM(npObject->_class) && npObject->_class->enumerate) {
291         uint32_t count;
292         NPIdentifier* identifiers;
293         if (npObject->_class->enumerate(npObject, &identifiers, &count)) {
294             v8::Handle<v8::Array> properties = v8::Array::New(count);
295             for (uint32_t i = 0; i < count; ++i) {
296                 IdentifierRep* identifier = static_cast<IdentifierRep*>(identifiers[i]);
297                 if (namedProperty)
298                     properties->Set(v8::Integer::New(i), v8::String::New(identifier->string()));
299                 else
300                     properties->Set(v8::Integer::New(i), v8::Integer::New(identifier->number()));
301             }
302
303             return properties;
304         }
305     }
306
307     return v8::Handle<v8::Array>();
308 }
309
310 v8::Handle<v8::Array> npObjectNamedPropertyEnumerator(const v8::AccessorInfo& info)
311 {
312     return npObjectPropertyEnumerator(info, true);
313 }
314
315 v8::Handle<v8::Array> npObjectIndexedPropertyEnumerator(const v8::AccessorInfo& info)
316 {
317     return npObjectPropertyEnumerator(info, false);
318 }
319
320 static void weakNPObjectCallback(v8::Persistent<v8::Value>, void* parameter);
321
322 static DOMWrapperMap<NPObject> staticNPObjectMap(&weakNPObjectCallback);
323
324 static void weakNPObjectCallback(v8::Persistent<v8::Value> object, void* parameter)
325 {
326     NPObject* npObject = static_cast<NPObject*>(parameter);
327     ASSERT(staticNPObjectMap.contains(npObject));
328     ASSERT(npObject);
329
330     // Must remove from our map before calling _NPN_ReleaseObject(). _NPN_ReleaseObject can call ForgetV8ObjectForNPObject, which
331     // uses the table as well.
332     staticNPObjectMap.forget(npObject);
333
334     if (_NPN_IsAlive(npObject))
335         _NPN_ReleaseObject(npObject);
336 }
337
338
339 v8::Local<v8::Object> createV8ObjectForNPObject(NPObject* object, NPObject* root)
340 {
341     static v8::Persistent<v8::FunctionTemplate> npObjectDesc;
342
343     ASSERT(v8::Context::InContext());
344
345     // If this is a v8 object, just return it.
346     if (object->_class == npScriptObjectClass) {
347         V8NPObject* v8NPObject = reinterpret_cast<V8NPObject*>(object);
348         return v8::Local<v8::Object>::New(v8NPObject->v8Object);
349     }
350
351     // If we've already wrapped this object, just return it.
352     if (staticNPObjectMap.contains(object))
353         return v8::Local<v8::Object>::New(staticNPObjectMap.get(object));
354
355     // FIXME: we should create a Wrapper type as a subclass of JSObject. It has two internal fields, field 0 is the wrapped
356     // pointer, and field 1 is the type. There should be an api function that returns unused type id. The same Wrapper type
357     // can be used by DOM bindings.
358     if (npObjectDesc.IsEmpty()) {
359         npObjectDesc = v8::Persistent<v8::FunctionTemplate>::New(v8::FunctionTemplate::New());
360         npObjectDesc->InstanceTemplate()->SetInternalFieldCount(V8Custom::kNPObjectInternalFieldCount);
361         npObjectDesc->InstanceTemplate()->SetNamedPropertyHandler(npObjectNamedPropertyGetter, npObjectNamedPropertySetter, 0, 0, npObjectNamedPropertyEnumerator);
362         npObjectDesc->InstanceTemplate()->SetIndexedPropertyHandler(npObjectIndexedPropertyGetter, npObjectIndexedPropertySetter, 0, 0, npObjectIndexedPropertyEnumerator);
363         npObjectDesc->InstanceTemplate()->SetCallAsFunctionHandler(npObjectInvokeDefaultHandler);
364     }
365
366     v8::Handle<v8::Function> v8Function = npObjectDesc->GetFunction();
367     v8::Local<v8::Object> value = SafeAllocation::newInstance(v8Function);
368
369     // If we were unable to allocate the instance, we avoid wrapping and registering the NP object.
370     if (value.IsEmpty())
371         return value;
372
373     wrapNPObject(value, object);
374
375     // KJS retains the object as part of its wrapper (see Bindings::CInstance).
376     _NPN_RetainObject(object);
377
378     _NPN_RegisterObject(object, root);
379
380     // Maintain a weak pointer for v8 so we can cleanup the object.
381     v8::Persistent<v8::Object> weakRef = v8::Persistent<v8::Object>::New(value);
382     staticNPObjectMap.set(object, weakRef);
383
384     return value;
385 }
386
387 void forgetV8ObjectForNPObject(NPObject* object)
388 {
389     if (staticNPObjectMap.contains(object)) {
390         v8::HandleScope scope;
391         v8::Persistent<v8::Object> handle(staticNPObjectMap.get(object));
392         V8DOMWrapper::setDOMWrapper(handle, WebCore::V8ClassIndex::NPOBJECT, 0);
393         staticNPObjectMap.forget(object);
394         _NPN_ReleaseObject(object);
395     }
396 }