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