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 "PlatformBridge.h"
32#include "DOMWindow.h"
33#include "Frame.h"
34#include "OwnArrayPtr.h"
35#include "PlatformString.h"
36#include "ScriptController.h"
37#include "V8GCController.h"
38#include "V8Helpers.h"
39#include "V8Index.h"
40#include "V8NPUtils.h"
41#include "V8Proxy.h"
42#include "npruntime_impl.h"
43#include "npruntime_priv.h"
44
45#if PLATFORM(CHROMIUM)
46#include <bindings/npruntime.h>
47#else
48#include "npruntime.h"
49#endif
50
51#include <stdio.h>
52#include <v8.h>
53#include <wtf/StringExtras.h>
54
55using WebCore::npObjectInternalFieldCount;
56using WebCore::toV8Context;
57using WebCore::toV8Proxy;
58using WebCore::V8ClassIndex;
59using WebCore::V8DOMWrapper;
60using WebCore::V8GCController;
61using WebCore::V8Proxy;
62
63// FIXME: Comments on why use malloc and free.
64static NPObject* allocV8NPObject(NPP, NPClass*)
65{
66    return static_cast<NPObject*>(malloc(sizeof(V8NPObject)));
67}
68
69static void freeV8NPObject(NPObject* npObject)
70{
71    V8NPObject* v8NpObject = reinterpret_cast<V8NPObject*>(npObject);
72#ifndef NDEBUG
73    V8GCController::unregisterGlobalHandle(v8NpObject, v8NpObject->v8Object);
74#endif
75    v8NpObject->v8Object.Dispose();
76    free(v8NpObject);
77}
78
79static v8::Handle<v8::Value>* createValueListFromVariantArgs(const NPVariant* arguments, uint32_t argumentCount, NPObject* owner)
80{
81    v8::Handle<v8::Value>* argv = new v8::Handle<v8::Value>[argumentCount];
82    for (uint32_t index = 0; index < argumentCount; index++) {
83        const NPVariant* arg = &arguments[index];
84        argv[index] = convertNPVariantToV8Object(arg, owner);
85    }
86    return argv;
87}
88
89// Create an identifier (null terminated utf8 char*) from the NPIdentifier.
90static v8::Local<v8::String> npIdentifierToV8Identifier(NPIdentifier name)
91{
92    PrivateIdentifier* identifier = static_cast<PrivateIdentifier*>(name);
93    if (identifier->isString)
94        return v8::String::New(static_cast<const char*>(identifier->value.string));
95
96    char buffer[32];
97    snprintf(buffer, sizeof(buffer), "%d", identifier->value.number);
98    return v8::String::New(buffer);
99}
100
101NPObject* v8ObjectToNPObject(v8::Handle<v8::Object> object)
102{
103    return reinterpret_cast<NPObject*>(object->GetPointerFromInternalField(WebCore::v8DOMWrapperObjectIndex));
104}
105
106static NPClass V8NPObjectClass = { NP_CLASS_STRUCT_VERSION,
107                                   allocV8NPObject,
108                                   freeV8NPObject,
109                                   0, 0, 0, 0, 0, 0, 0, 0, 0 };
110
111// NPAPI's npruntime functions.
112NPClass* npScriptObjectClass = &V8NPObjectClass;
113
114NPObject* npCreateV8ScriptObject(NPP npp, v8::Handle<v8::Object> object, WebCore::DOMWindow* root)
115{
116    // Check to see if this object is already wrapped.
117    if (object->InternalFieldCount() == npObjectInternalFieldCount) {
118        v8::Local<v8::Value> typeIndex = object->GetInternalField(WebCore::v8DOMWrapperTypeIndex);
119        if (typeIndex->IsNumber() && typeIndex->Uint32Value() == V8ClassIndex::NPOBJECT) {
120
121            NPObject* returnValue = v8ObjectToNPObject(object);
122            _NPN_RetainObject(returnValue);
123            return returnValue;
124        }
125    }
126
127    V8NPObject* v8npObject = reinterpret_cast<V8NPObject*>(_NPN_CreateObject(npp, &V8NPObjectClass));
128    v8npObject->v8Object = v8::Persistent<v8::Object>::New(object);
129#ifndef NDEBUG
130    V8GCController::registerGlobalHandle(WebCore::NPOBJECT, v8npObject, v8npObject->v8Object);
131#endif
132    v8npObject->rootObject = root;
133    return reinterpret_cast<NPObject*>(v8npObject);
134}
135
136bool _NPN_Invoke(NPP npp, NPObject* npObject, NPIdentifier methodName, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result)
137{
138    if (!npObject)
139        return false;
140
141    if (npObject->_class != npScriptObjectClass) {
142        if (npObject->_class->invoke)
143            return npObject->_class->invoke(npObject, methodName, arguments, argumentCount, result);
144
145        VOID_TO_NPVARIANT(*result);
146        return true;
147    }
148
149    V8NPObject* v8NpObject = reinterpret_cast<V8NPObject*>(npObject);
150
151    PrivateIdentifier* identifier = static_cast<PrivateIdentifier*>(methodName);
152    if (!identifier->isString)
153        return false;
154
155    v8::HandleScope handleScope;
156    // FIXME: should use the plugin's owner frame as the security context.
157    v8::Handle<v8::Context> context = toV8Context(npp, npObject);
158    if (context.IsEmpty())
159        return false;
160
161    v8::Context::Scope scope(context);
162
163    if (methodName == _NPN_GetStringIdentifier("eval")) {
164        if (argumentCount != 1)
165            return false;
166        if (arguments[0].type != NPVariantType_String)
167            return false;
168        return _NPN_Evaluate(npp, npObject, const_cast<NPString*>(&arguments[0].value.stringValue), result);
169    }
170
171    v8::Handle<v8::Value> functionObject = v8NpObject->v8Object->Get(v8::String::New(identifier->value.string));
172    if (functionObject.IsEmpty() || functionObject->IsNull()) {
173        NULL_TO_NPVARIANT(*result);
174        return false;
175    }
176    if (functionObject->IsUndefined()) {
177        VOID_TO_NPVARIANT(*result);
178        return false;
179    }
180
181    V8Proxy* proxy = toV8Proxy(npObject);
182    ASSERT(proxy);
183
184    // Call the function object.
185    v8::Handle<v8::Function> function = v8::Handle<v8::Function>::Cast(functionObject);
186    OwnArrayPtr<v8::Handle<v8::Value> > argv(createValueListFromVariantArgs(arguments, argumentCount, npObject));
187    v8::Local<v8::Value> resultObject = proxy->callFunction(function, v8NpObject->v8Object, argumentCount, argv.get());
188
189    // If we had an error, return false.  The spec is a little unclear here, but says "Returns true if the method was
190    // successfully invoked".  If we get an error return value, was that successfully invoked?
191    if (resultObject.IsEmpty())
192        return false;
193
194    convertV8ObjectToNPVariant(resultObject, npObject, result);
195    return true;
196}
197
198// FIXME: Fix it same as _NPN_Invoke (HandleScope and such).
199bool _NPN_InvokeDefault(NPP npp, NPObject* npObject, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result)
200{
201    if (!npObject)
202        return false;
203
204    if (npObject->_class != npScriptObjectClass) {
205        if (npObject->_class->invokeDefault)
206            return npObject->_class->invokeDefault(npObject, arguments, argumentCount, result);
207
208        VOID_TO_NPVARIANT(*result);
209        return true;
210    }
211
212    V8NPObject* v8NpObject = reinterpret_cast<V8NPObject*>(npObject);
213
214    VOID_TO_NPVARIANT(*result);
215
216    v8::HandleScope handleScope;
217    v8::Handle<v8::Context> context = toV8Context(npp, npObject);
218    if (context.IsEmpty())
219        return false;
220
221    v8::Context::Scope scope(context);
222
223    // Lookup the function object and call it.
224    v8::Handle<v8::Object> functionObject(v8NpObject->v8Object);
225    if (!functionObject->IsFunction())
226        return false;
227
228    v8::Local<v8::Value> resultObject;
229    v8::Handle<v8::Function> function(v8::Function::Cast(*functionObject));
230    if (!function->IsNull()) {
231        V8Proxy* proxy = toV8Proxy(npObject);
232        ASSERT(proxy);
233
234        OwnArrayPtr<v8::Handle<v8::Value> > argv(createValueListFromVariantArgs(arguments, argumentCount, npObject));
235        resultObject = proxy->callFunction(function, functionObject, argumentCount, argv.get());
236    }
237    // If we had an error, return false.  The spec is a little unclear here, but says "Returns true if the method was
238    // successfully invoked".  If we get an error return value, was that successfully invoked?
239    if (resultObject.IsEmpty())
240        return false;
241
242    convertV8ObjectToNPVariant(resultObject, npObject, result);
243    return true;
244}
245
246bool _NPN_Evaluate(NPP npp, NPObject* npObject, NPString* npScript, NPVariant* result)
247{
248    bool popupsAllowed = WebCore::PlatformBridge::popupsAllowed(npp);
249    return _NPN_EvaluateHelper(npp, popupsAllowed, npObject, npScript, result);
250}
251
252bool _NPN_EvaluateHelper(NPP npp, bool popupsAllowed, NPObject* npObject, NPString* npScript, NPVariant* result)
253{
254    VOID_TO_NPVARIANT(*result);
255    if (!npObject)
256        return false;
257
258    if (npObject->_class != npScriptObjectClass)
259        return false;
260
261    v8::HandleScope handleScope;
262    v8::Handle<v8::Context> context = toV8Context(npp, npObject);
263    if (context.IsEmpty())
264        return false;
265
266    V8Proxy* proxy = toV8Proxy(npObject);
267    ASSERT(proxy);
268
269    v8::Context::Scope scope(context);
270
271    WebCore::String filename;
272    if (!popupsAllowed)
273        filename = "npscript";
274
275    WebCore::String script = WebCore::String::fromUTF8(npScript->UTF8Characters, npScript->UTF8Length);
276    v8::Local<v8::Value> v8result = proxy->evaluate(WebCore::ScriptSourceCode(script, WebCore::KURL(WebCore::ParsedURLString, filename)), 0);
277
278    if (v8result.IsEmpty())
279        return false;
280
281    convertV8ObjectToNPVariant(v8result, npObject, result);
282    return true;
283}
284
285bool _NPN_GetProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName, NPVariant* result)
286{
287    if (!npObject)
288        return false;
289
290    if (npObject->_class == npScriptObjectClass) {
291        V8NPObject* object = reinterpret_cast<V8NPObject*>(npObject);
292
293        v8::HandleScope handleScope;
294        v8::Handle<v8::Context> context = toV8Context(npp, npObject);
295        if (context.IsEmpty())
296            return false;
297
298        v8::Context::Scope scope(context);
299
300        v8::Handle<v8::Object> obj(object->v8Object);
301        v8::Local<v8::Value> v8result = obj->Get(npIdentifierToV8Identifier(propertyName));
302
303        convertV8ObjectToNPVariant(v8result, npObject, result);
304        return true;
305    }
306
307    if (npObject->_class->hasProperty && npObject->_class->getProperty) {
308        if (npObject->_class->hasProperty(npObject, propertyName))
309            return npObject->_class->getProperty(npObject, propertyName, result);
310    }
311
312    VOID_TO_NPVARIANT(*result);
313    return false;
314}
315
316bool _NPN_SetProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName, const NPVariant* value)
317{
318    if (!npObject)
319        return false;
320
321    if (npObject->_class == npScriptObjectClass) {
322        V8NPObject* object = reinterpret_cast<V8NPObject*>(npObject);
323
324        v8::HandleScope handleScope;
325        v8::Handle<v8::Context> context = toV8Context(npp, npObject);
326        if (context.IsEmpty())
327            return false;
328
329        v8::Context::Scope scope(context);
330
331        v8::Handle<v8::Object> obj(object->v8Object);
332        obj->Set(npIdentifierToV8Identifier(propertyName),
333                 convertNPVariantToV8Object(value, object->rootObject->frame()->script()->windowScriptNPObject()));
334        return true;
335    }
336
337    if (npObject->_class->setProperty)
338        return npObject->_class->setProperty(npObject, propertyName, value);
339
340    return false;
341}
342
343bool _NPN_RemoveProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName)
344{
345    if (!npObject)
346        return false;
347    if (npObject->_class != npScriptObjectClass)
348        return false;
349
350    V8NPObject* object = reinterpret_cast<V8NPObject*>(npObject);
351
352    v8::HandleScope handleScope;
353    v8::Handle<v8::Context> context = toV8Context(npp, npObject);
354    if (context.IsEmpty())
355        return false;
356    v8::Context::Scope scope(context);
357
358    v8::Handle<v8::Object> obj(object->v8Object);
359    // FIXME: Verify that setting to undefined is right.
360    obj->Set(npIdentifierToV8Identifier(propertyName), v8::Undefined());
361    return true;
362}
363
364bool _NPN_HasProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName)
365{
366    if (!npObject)
367        return false;
368
369    if (npObject->_class == npScriptObjectClass) {
370        V8NPObject* object = reinterpret_cast<V8NPObject*>(npObject);
371
372        v8::HandleScope handleScope;
373        v8::Handle<v8::Context> context = toV8Context(npp, npObject);
374        if (context.IsEmpty())
375            return false;
376        v8::Context::Scope scope(context);
377
378        v8::Handle<v8::Object> obj(object->v8Object);
379        return obj->Has(npIdentifierToV8Identifier(propertyName));
380    }
381
382    if (npObject->_class->hasProperty)
383        return npObject->_class->hasProperty(npObject, propertyName);
384    return false;
385}
386
387bool _NPN_HasMethod(NPP npp, NPObject* npObject, NPIdentifier methodName)
388{
389    if (!npObject)
390        return false;
391
392    if (npObject->_class == npScriptObjectClass) {
393        V8NPObject* object = reinterpret_cast<V8NPObject*>(npObject);
394
395        v8::HandleScope handleScope;
396        v8::Handle<v8::Context> context = toV8Context(npp, npObject);
397        if (context.IsEmpty())
398            return false;
399        v8::Context::Scope scope(context);
400
401        v8::Handle<v8::Object> obj(object->v8Object);
402        v8::Handle<v8::Value> prop = obj->Get(npIdentifierToV8Identifier(methodName));
403        return prop->IsFunction();
404    }
405
406    if (npObject->_class->hasMethod)
407        return npObject->_class->hasMethod(npObject, methodName);
408    return false;
409}
410
411void _NPN_SetException(NPObject* npObject, const NPUTF8 *message)
412{
413    if (!npObject || npObject->_class != npScriptObjectClass) {
414        // We won't be able to find a proper scope for this exception, so just throw it.
415        // This is consistent with JSC, which throws a global exception all the time.
416#if PLATFORM(ANDROID)
417        // However, if there isn't a v8 context, throw the error away as there really isn't anything useful to do with it.
418        if (v8::Context::InContext())
419            V8Proxy::throwError(V8Proxy::GeneralError, message);
420#endif
421        return;
422    }
423    v8::HandleScope handleScope;
424    v8::Handle<v8::Context> context = toV8Context(0, npObject);
425    if (context.IsEmpty())
426        return;
427
428    v8::Context::Scope scope(context);
429    V8Proxy::throwError(V8Proxy::GeneralError, message);
430}
431
432bool _NPN_Enumerate(NPP npp, NPObject* npObject, NPIdentifier** identifier, uint32_t* count)
433{
434    if (!npObject)
435        return false;
436
437    if (npObject->_class == npScriptObjectClass) {
438        V8NPObject* object = reinterpret_cast<V8NPObject*>(npObject);
439
440        v8::HandleScope handleScope;
441        v8::Handle<v8::Context> context = toV8Context(npp, npObject);
442        if (context.IsEmpty())
443            return false;
444        v8::Context::Scope scope(context);
445
446        v8::Handle<v8::Object> obj(object->v8Object);
447
448        // FIXME: http://b/issue?id=1210340: Use a v8::Object::Keys() method when it exists, instead of evaluating javascript.
449
450        // FIXME: Figure out how to cache this helper function.  Run a helper function that collects the properties
451        // on the object into an array.
452        const char enumeratorCode[] =
453            "(function (obj) {"
454            "  var props = [];"
455            "  for (var prop in obj) {"
456            "    props[props.length] = prop;"
457            "  }"
458            "  return props;"
459            "});";
460        v8::Handle<v8::String> source = v8::String::New(enumeratorCode);
461        v8::Handle<v8::Script> script = v8::Script::Compile(source, 0);
462        v8::Handle<v8::Value> enumeratorObj = script->Run();
463        v8::Handle<v8::Function> enumerator = v8::Handle<v8::Function>::Cast(enumeratorObj);
464        v8::Handle<v8::Value> argv[] = { obj };
465        v8::Local<v8::Value> propsObj = enumerator->Call(v8::Handle<v8::Object>::Cast(enumeratorObj), ARRAYSIZE_UNSAFE(argv), argv);
466        if (propsObj.IsEmpty())
467            return false;
468
469        // Convert the results into an array of NPIdentifiers.
470        v8::Handle<v8::Array> props = v8::Handle<v8::Array>::Cast(propsObj);
471        *count = props->Length();
472        *identifier = static_cast<NPIdentifier*>(malloc(sizeof(NPIdentifier*) * *count));
473        for (uint32_t i = 0; i < *count; ++i) {
474            v8::Local<v8::Value> name = props->Get(v8::Integer::New(i));
475            (*identifier)[i] = getStringIdentifier(v8::Local<v8::String>::Cast(name));
476        }
477        return true;
478    }
479
480    if (NP_CLASS_STRUCT_VERSION_HAS_ENUM(npObject->_class) && npObject->_class->enumerate)
481       return npObject->_class->enumerate(npObject, identifier, count);
482
483    return false;
484}
485
486bool _NPN_Construct(NPP npp, NPObject* npObject, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result)
487{
488    if (!npObject)
489        return false;
490
491    if (npObject->_class == npScriptObjectClass) {
492        V8NPObject* object = reinterpret_cast<V8NPObject*>(npObject);
493
494        v8::HandleScope handleScope;
495        v8::Handle<v8::Context> context = toV8Context(npp, npObject);
496        if (context.IsEmpty())
497            return false;
498        v8::Context::Scope scope(context);
499
500        // Lookup the constructor function.
501        v8::Handle<v8::Object> ctorObj(object->v8Object);
502        if (!ctorObj->IsFunction())
503            return false;
504
505        // Call the constructor.
506        v8::Local<v8::Value> resultObject;
507        v8::Handle<v8::Function> ctor(v8::Function::Cast(*ctorObj));
508        if (!ctor->IsNull()) {
509            V8Proxy* proxy = toV8Proxy(npObject);
510            ASSERT(proxy);
511
512            OwnArrayPtr<v8::Handle<v8::Value> > argv(createValueListFromVariantArgs(arguments, argumentCount, npObject));
513            resultObject = proxy->newInstance(ctor, argumentCount, argv.get());
514        }
515
516        if (resultObject.IsEmpty())
517            return false;
518
519        convertV8ObjectToNPVariant(resultObject, npObject, result);
520        return true;
521    }
522
523    if (NP_CLASS_STRUCT_VERSION_HAS_CTOR(npObject->_class) && npObject->_class->construct)
524        return npObject->_class->construct(npObject, arguments, argumentCount, result);
525
526    return false;
527}
528