initial import
[vuplus_webkit] / Source / WebCore / bindings / v8 / NPV8Object.cpp
1 /*
2  * Copyright (C) 2004, 2006 Apple Computer, Inc.  All rights reserved.
3  * Copyright (C) 2007, 2008, 2009 Google, Inc.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
18  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "config.h"
28
29 #include "NPV8Object.h"
30
31 #include "PlatformSupport.h"
32 #include "DOMWindow.h"
33 #include "Frame.h"
34 #include "OwnArrayPtr.h"
35 #include "PlatformString.h"
36 #include "ScriptSourceCode.h"
37 #include "UserGestureIndicator.h"
38 #include "V8GCController.h"
39 #include "V8Helpers.h"
40 #include "V8NPUtils.h"
41 #include "V8Proxy.h"
42 #include "WrapperTypeInfo.h"
43 #include "npruntime_impl.h"
44 #include "npruntime_priv.h"
45
46 #include <stdio.h>
47 #include <wtf/StringExtras.h>
48
49 using namespace WebCore;
50
51 namespace WebCore {
52
53 WrapperTypeInfo* npObjectTypeInfo()
54 {
55     static WrapperTypeInfo typeInfo = { 0, 0, 0, 0 };
56     return &typeInfo;
57 }
58
59 typedef HashMap<int, V8NPObject*> V8NPObjectMap;
60
61 static V8NPObjectMap* staticV8NPObjectMap()
62 {
63     DEFINE_STATIC_LOCAL(V8NPObjectMap, v8npObjectMap, ());
64     return &v8npObjectMap;
65 }
66
67 // FIXME: Comments on why use malloc and free.
68 static NPObject* allocV8NPObject(NPP, NPClass*)
69 {
70     return static_cast<NPObject*>(malloc(sizeof(V8NPObject)));
71 }
72
73 static void freeV8NPObject(NPObject* npObject)
74 {
75     V8NPObject* v8NpObject = reinterpret_cast<V8NPObject*>(npObject);
76     if (int v8ObjectHash = v8NpObject->v8Object->GetIdentityHash()) {
77         ASSERT(staticV8NPObjectMap()->contains(v8ObjectHash));
78         staticV8NPObjectMap()->remove(v8ObjectHash);
79     } else {
80         ASSERT(!v8::Context::InContext());
81         staticV8NPObjectMap()->clear();
82     }
83
84 #ifndef NDEBUG
85     V8GCController::unregisterGlobalHandle(v8NpObject, v8NpObject->v8Object);
86 #endif
87     v8NpObject->v8Object.Dispose();
88     free(v8NpObject);
89 }
90
91 static PassOwnArrayPtr<v8::Handle<v8::Value> > createValueListFromVariantArgs(const NPVariant* arguments, uint32_t argumentCount, NPObject* owner)
92 {
93     OwnArrayPtr<v8::Handle<v8::Value> > argv = adoptArrayPtr(new v8::Handle<v8::Value>[argumentCount]);
94     for (uint32_t index = 0; index < argumentCount; index++) {
95         const NPVariant* arg = &arguments[index];
96         argv[index] = convertNPVariantToV8Object(arg, owner);
97     }
98     return argv.release();
99 }
100
101 // Create an identifier (null terminated utf8 char*) from the NPIdentifier.
102 static v8::Local<v8::String> npIdentifierToV8Identifier(NPIdentifier name)
103 {
104     PrivateIdentifier* identifier = static_cast<PrivateIdentifier*>(name);
105     if (identifier->isString)
106         return v8::String::New(static_cast<const char*>(identifier->value.string));
107
108     char buffer[32];
109     snprintf(buffer, sizeof(buffer), "%d", identifier->value.number);
110     return v8::String::New(buffer);
111 }
112
113 NPObject* v8ObjectToNPObject(v8::Handle<v8::Object> object)
114 {
115     return reinterpret_cast<NPObject*>(object->GetPointerFromInternalField(v8DOMWrapperObjectIndex)); 
116 }
117
118 static NPClass V8NPObjectClass = { NP_CLASS_STRUCT_VERSION,
119                                    allocV8NPObject,
120                                    freeV8NPObject,
121                                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
122
123 // NPAPI's npruntime functions.
124 NPClass* npScriptObjectClass = &V8NPObjectClass;
125
126 NPObject* npCreateV8ScriptObject(NPP npp, v8::Handle<v8::Object> object, DOMWindow* root)
127 {
128     // Check to see if this object is already wrapped.
129     if (object->InternalFieldCount() == npObjectInternalFieldCount) {
130         WrapperTypeInfo* typeInfo = static_cast<WrapperTypeInfo*>(object->GetPointerFromInternalField(v8DOMWrapperTypeIndex));
131         if (typeInfo == npObjectTypeInfo()) {
132
133             NPObject* returnValue = v8ObjectToNPObject(object);
134             _NPN_RetainObject(returnValue);
135             return returnValue;
136         }
137     }
138
139     int v8ObjectHash = object->GetIdentityHash();
140     ASSERT(v8ObjectHash);
141     if (staticV8NPObjectMap()->contains(v8ObjectHash)) {
142         V8NPObject* v8npObject = staticV8NPObjectMap()->get(v8ObjectHash);
143         ASSERT(v8npObject->v8Object == object);
144         _NPN_RetainObject(&v8npObject->object);
145         return reinterpret_cast<NPObject*>(v8npObject);
146     }
147
148     V8NPObject* v8npObject = reinterpret_cast<V8NPObject*>(_NPN_CreateObject(npp, &V8NPObjectClass));
149     v8npObject->v8Object = v8::Persistent<v8::Object>::New(object);
150 #ifndef NDEBUG
151     V8GCController::registerGlobalHandle(NPOBJECT, v8npObject, v8npObject->v8Object);
152 #endif
153     v8npObject->rootObject = root;
154
155     staticV8NPObjectMap()->set(v8ObjectHash, v8npObject);
156
157     return reinterpret_cast<NPObject*>(v8npObject);
158 }
159
160 } // namespace WebCore
161
162 bool _NPN_Invoke(NPP npp, NPObject* npObject, NPIdentifier methodName, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result)
163 {
164     if (!npObject)
165         return false;
166
167     if (npObject->_class != npScriptObjectClass) {
168         if (npObject->_class->invoke)
169             return npObject->_class->invoke(npObject, methodName, arguments, argumentCount, result);
170
171         VOID_TO_NPVARIANT(*result);
172         return true;
173     }
174
175     V8NPObject* v8NpObject = reinterpret_cast<V8NPObject*>(npObject);
176
177     PrivateIdentifier* identifier = static_cast<PrivateIdentifier*>(methodName);
178     if (!identifier->isString)
179         return false;
180
181     if (!strcmp(identifier->value.string, "eval")) {
182         if (argumentCount != 1)
183             return false;
184         if (arguments[0].type != NPVariantType_String)
185             return false;
186         return _NPN_Evaluate(npp, npObject, const_cast<NPString*>(&arguments[0].value.stringValue), result);
187     }
188
189     v8::HandleScope handleScope;
190     // FIXME: should use the plugin's owner frame as the security context.
191     v8::Handle<v8::Context> context = toV8Context(npp, npObject);
192     if (context.IsEmpty())
193         return false;
194
195     v8::Context::Scope scope(context);
196     ExceptionCatcher exceptionCatcher;
197
198     v8::Handle<v8::Value> functionObject = v8NpObject->v8Object->Get(v8::String::New(identifier->value.string));
199     if (functionObject.IsEmpty() || functionObject->IsNull()) {
200         NULL_TO_NPVARIANT(*result);
201         return false;
202     }
203     if (functionObject->IsUndefined()) {
204         VOID_TO_NPVARIANT(*result);
205         return false;
206     }
207
208     V8Proxy* proxy = toV8Proxy(npObject);
209     ASSERT(proxy);
210
211     // Call the function object.
212     v8::Handle<v8::Function> function = v8::Handle<v8::Function>::Cast(functionObject);
213     OwnArrayPtr<v8::Handle<v8::Value> > argv = createValueListFromVariantArgs(arguments, argumentCount, npObject);
214     v8::Local<v8::Value> resultObject = proxy->callFunction(function, v8NpObject->v8Object, argumentCount, argv.get());
215
216     // If we had an error, return false.  The spec is a little unclear here, but says "Returns true if the method was
217     // successfully invoked".  If we get an error return value, was that successfully invoked?
218     if (resultObject.IsEmpty())
219         return false;
220
221     convertV8ObjectToNPVariant(resultObject, npObject, result);
222     return true;
223 }
224
225 // FIXME: Fix it same as _NPN_Invoke (HandleScope and such).
226 bool _NPN_InvokeDefault(NPP npp, NPObject* npObject, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result)
227 {
228     if (!npObject)
229         return false;
230
231     if (npObject->_class != npScriptObjectClass) {
232         if (npObject->_class->invokeDefault)
233             return npObject->_class->invokeDefault(npObject, arguments, argumentCount, result);
234
235         VOID_TO_NPVARIANT(*result);
236         return true;
237     }
238
239     V8NPObject* v8NpObject = reinterpret_cast<V8NPObject*>(npObject);
240
241     VOID_TO_NPVARIANT(*result);
242
243     v8::HandleScope handleScope;
244     v8::Handle<v8::Context> context = toV8Context(npp, npObject);
245     if (context.IsEmpty())
246         return false;
247
248     v8::Context::Scope scope(context);
249     ExceptionCatcher exceptionCatcher;
250
251     // Lookup the function object and call it.
252     v8::Handle<v8::Object> functionObject(v8NpObject->v8Object);
253     if (!functionObject->IsFunction())
254         return false;
255
256     v8::Local<v8::Value> resultObject;
257     v8::Handle<v8::Function> function(v8::Function::Cast(*functionObject));
258     if (!function->IsNull()) {
259         V8Proxy* proxy = toV8Proxy(npObject);
260         ASSERT(proxy);
261
262         OwnArrayPtr<v8::Handle<v8::Value> > argv = createValueListFromVariantArgs(arguments, argumentCount, npObject);
263         resultObject = proxy->callFunction(function, functionObject, argumentCount, argv.get());
264     }
265     // If we had an error, return false.  The spec is a little unclear here, but says "Returns true if the method was
266     // successfully invoked".  If we get an error return value, was that successfully invoked?
267     if (resultObject.IsEmpty())
268         return false;
269
270     convertV8ObjectToNPVariant(resultObject, npObject, result);
271     return true;
272 }
273
274 bool _NPN_Evaluate(NPP npp, NPObject* npObject, NPString* npScript, NPVariant* result)
275 {
276     bool popupsAllowed = PlatformSupport::popupsAllowed(npp);
277     return _NPN_EvaluateHelper(npp, popupsAllowed, npObject, npScript, result);
278 }
279
280 bool _NPN_EvaluateHelper(NPP npp, bool popupsAllowed, NPObject* npObject, NPString* npScript, NPVariant* result)
281 {
282     VOID_TO_NPVARIANT(*result);
283     if (!npObject)
284         return false;
285
286     if (npObject->_class != npScriptObjectClass)
287         return false;
288
289     v8::HandleScope handleScope;
290     v8::Handle<v8::Context> context = toV8Context(npp, npObject);
291     if (context.IsEmpty())
292         return false;
293
294     V8Proxy* proxy = toV8Proxy(npObject);
295     ASSERT(proxy);
296
297     v8::Context::Scope scope(context);
298     ExceptionCatcher exceptionCatcher;
299
300     // FIXME: Is this branch still needed after switching to using UserGestureIndicator?
301     String filename;
302     if (!popupsAllowed)
303         filename = "npscript";
304
305     String script = String::fromUTF8(npScript->UTF8Characters, npScript->UTF8Length);
306
307     UserGestureIndicator gestureIndicator(popupsAllowed ? DefinitelyProcessingUserGesture : PossiblyProcessingUserGesture);
308     v8::Local<v8::Value> v8result = proxy->evaluate(ScriptSourceCode(script, KURL(ParsedURLString, filename)), 0);
309
310     if (v8result.IsEmpty())
311         return false;
312
313     convertV8ObjectToNPVariant(v8result, npObject, result);
314     return true;
315 }
316
317 bool _NPN_GetProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName, NPVariant* result)
318 {
319     if (!npObject)
320         return false;
321
322     if (npObject->_class == npScriptObjectClass) {
323         V8NPObject* object = reinterpret_cast<V8NPObject*>(npObject);
324
325         v8::HandleScope handleScope;
326         v8::Handle<v8::Context> context = toV8Context(npp, npObject);
327         if (context.IsEmpty())
328             return false;
329
330         v8::Context::Scope scope(context);
331         ExceptionCatcher exceptionCatcher;
332
333         v8::Handle<v8::Object> obj(object->v8Object);
334         v8::Local<v8::Value> v8result = obj->Get(npIdentifierToV8Identifier(propertyName));
335         
336         if (v8result.IsEmpty())
337             return false;
338
339         convertV8ObjectToNPVariant(v8result, npObject, result);
340         return true;
341     }
342
343     if (npObject->_class->hasProperty && npObject->_class->getProperty) {
344         if (npObject->_class->hasProperty(npObject, propertyName))
345             return npObject->_class->getProperty(npObject, propertyName, result);
346     }
347
348     VOID_TO_NPVARIANT(*result);
349     return false;
350 }
351
352 bool _NPN_SetProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName, const NPVariant* value)
353 {
354     if (!npObject)
355         return false;
356
357     if (npObject->_class == npScriptObjectClass) {
358         V8NPObject* object = reinterpret_cast<V8NPObject*>(npObject);
359
360         v8::HandleScope handleScope;
361         v8::Handle<v8::Context> context = toV8Context(npp, npObject);
362         if (context.IsEmpty())
363             return false;
364
365         v8::Context::Scope scope(context);
366         ExceptionCatcher exceptionCatcher;
367
368         v8::Handle<v8::Object> obj(object->v8Object);
369         obj->Set(npIdentifierToV8Identifier(propertyName),
370                  convertNPVariantToV8Object(value, object->rootObject->frame()->script()->windowScriptNPObject()));
371         return true;
372     }
373
374     if (npObject->_class->setProperty)
375         return npObject->_class->setProperty(npObject, propertyName, value);
376
377     return false;
378 }
379
380 bool _NPN_RemoveProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName)
381 {
382     if (!npObject)
383         return false;
384     if (npObject->_class != npScriptObjectClass)
385         return false;
386
387     V8NPObject* object = reinterpret_cast<V8NPObject*>(npObject);
388
389     v8::HandleScope handleScope;
390     v8::Handle<v8::Context> context = toV8Context(npp, npObject);
391     if (context.IsEmpty())
392         return false;
393     v8::Context::Scope scope(context);
394     ExceptionCatcher exceptionCatcher;
395
396     v8::Handle<v8::Object> obj(object->v8Object);
397     // FIXME: Verify that setting to undefined is right.
398     obj->Set(npIdentifierToV8Identifier(propertyName), v8::Undefined());
399     return true;
400 }
401
402 bool _NPN_HasProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName)
403 {
404     if (!npObject)
405         return false;
406
407     if (npObject->_class == npScriptObjectClass) {
408         V8NPObject* object = reinterpret_cast<V8NPObject*>(npObject);
409
410         v8::HandleScope handleScope;
411         v8::Handle<v8::Context> context = toV8Context(npp, npObject);
412         if (context.IsEmpty())
413             return false;
414         v8::Context::Scope scope(context);
415         ExceptionCatcher exceptionCatcher;
416
417         v8::Handle<v8::Object> obj(object->v8Object);
418         return obj->Has(npIdentifierToV8Identifier(propertyName));
419     }
420
421     if (npObject->_class->hasProperty)
422         return npObject->_class->hasProperty(npObject, propertyName);
423     return false;
424 }
425
426 bool _NPN_HasMethod(NPP npp, NPObject* npObject, NPIdentifier methodName)
427 {
428     if (!npObject)
429         return false;
430
431     if (npObject->_class == npScriptObjectClass) {
432         V8NPObject* object = reinterpret_cast<V8NPObject*>(npObject);
433
434         v8::HandleScope handleScope;
435         v8::Handle<v8::Context> context = toV8Context(npp, npObject);
436         if (context.IsEmpty())
437             return false;
438         v8::Context::Scope scope(context);
439         ExceptionCatcher exceptionCatcher;
440
441         v8::Handle<v8::Object> obj(object->v8Object);
442         v8::Handle<v8::Value> prop = obj->Get(npIdentifierToV8Identifier(methodName));
443         return prop->IsFunction();
444     }
445
446     if (npObject->_class->hasMethod)
447         return npObject->_class->hasMethod(npObject, methodName);
448     return false;
449 }
450
451 void _NPN_SetException(NPObject* npObject, const NPUTF8 *message)
452 {
453     if (!npObject || npObject->_class != npScriptObjectClass) {
454         // We won't be able to find a proper scope for this exception, so just throw it.
455         // This is consistent with JSC, which throws a global exception all the time.
456         V8Proxy::throwError(V8Proxy::GeneralError, message);
457         return;
458     }
459     v8::HandleScope handleScope;
460     v8::Handle<v8::Context> context = toV8Context(0, npObject);
461     if (context.IsEmpty())
462         return;
463
464     v8::Context::Scope scope(context);
465     ExceptionCatcher exceptionCatcher;
466
467     V8Proxy::throwError(V8Proxy::GeneralError, message);
468 }
469
470 bool _NPN_Enumerate(NPP npp, NPObject* npObject, NPIdentifier** identifier, uint32_t* count)
471 {
472     if (!npObject)
473         return false;
474
475     if (npObject->_class == npScriptObjectClass) {
476         V8NPObject* object = reinterpret_cast<V8NPObject*>(npObject);
477
478         v8::HandleScope handleScope;
479         v8::Handle<v8::Context> context = toV8Context(npp, npObject);
480         if (context.IsEmpty())
481             return false;
482         v8::Context::Scope scope(context);
483         ExceptionCatcher exceptionCatcher;
484
485         v8::Handle<v8::Object> obj(object->v8Object);
486
487         // FIXME: http://b/issue?id=1210340: Use a v8::Object::Keys() method when it exists, instead of evaluating javascript.
488
489         // FIXME: Figure out how to cache this helper function.  Run a helper function that collects the properties
490         // on the object into an array.
491         const char enumeratorCode[] =
492             "(function (obj) {"
493             "  var props = [];"
494             "  for (var prop in obj) {"
495             "    props[props.length] = prop;"
496             "  }"
497             "  return props;"
498             "});";
499         v8::Handle<v8::String> source = v8::String::New(enumeratorCode);
500         v8::Handle<v8::Script> script = v8::Script::Compile(source, 0);
501         v8::Handle<v8::Value> enumeratorObj = script->Run();
502         v8::Handle<v8::Function> enumerator = v8::Handle<v8::Function>::Cast(enumeratorObj);
503         v8::Handle<v8::Value> argv[] = { obj };
504         v8::Local<v8::Value> propsObj = enumerator->Call(v8::Handle<v8::Object>::Cast(enumeratorObj), ARRAYSIZE_UNSAFE(argv), argv);
505         if (propsObj.IsEmpty())
506             return false;
507
508         // Convert the results into an array of NPIdentifiers.
509         v8::Handle<v8::Array> props = v8::Handle<v8::Array>::Cast(propsObj);
510         *count = props->Length();
511         *identifier = static_cast<NPIdentifier*>(malloc(sizeof(NPIdentifier*) * *count));
512         for (uint32_t i = 0; i < *count; ++i) {
513             v8::Local<v8::Value> name = props->Get(v8::Integer::New(i));
514             (*identifier)[i] = getStringIdentifier(v8::Local<v8::String>::Cast(name));
515         }
516         return true;
517     }
518
519     if (NP_CLASS_STRUCT_VERSION_HAS_ENUM(npObject->_class) && npObject->_class->enumerate)
520        return npObject->_class->enumerate(npObject, identifier, count);
521
522     return false;
523 }
524
525 bool _NPN_Construct(NPP npp, NPObject* npObject, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result)
526 {
527     if (!npObject)
528         return false;
529
530     if (npObject->_class == npScriptObjectClass) {
531         V8NPObject* object = reinterpret_cast<V8NPObject*>(npObject);
532
533         v8::HandleScope handleScope;
534         v8::Handle<v8::Context> context = toV8Context(npp, npObject);
535         if (context.IsEmpty())
536             return false;
537         v8::Context::Scope scope(context);
538         ExceptionCatcher exceptionCatcher;
539
540         // Lookup the constructor function.
541         v8::Handle<v8::Object> ctorObj(object->v8Object);
542         if (!ctorObj->IsFunction())
543             return false;
544
545         // Call the constructor.
546         v8::Local<v8::Value> resultObject;
547         v8::Handle<v8::Function> ctor(v8::Function::Cast(*ctorObj));
548         if (!ctor->IsNull()) {
549             V8Proxy* proxy = toV8Proxy(npObject);
550             ASSERT(proxy);
551
552             OwnArrayPtr<v8::Handle<v8::Value> > argv = createValueListFromVariantArgs(arguments, argumentCount, npObject);
553             resultObject = proxy->newInstance(ctor, argumentCount, argv.get());
554         }
555
556         if (resultObject.IsEmpty())
557             return false;
558
559         convertV8ObjectToNPVariant(resultObject, npObject, result);
560         return true;
561     }
562
563     if (NP_CLASS_STRUCT_VERSION_HAS_CTOR(npObject->_class) && npObject->_class->construct)
564         return npObject->_class->construct(npObject, arguments, argumentCount, result);
565
566     return false;
567 }