2 * Copyright (C) 2004, 2006 Apple Computer, Inc. All rights reserved.
3 * Copyright (C) 2007, 2008, 2009 Google, Inc. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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.
29 #include "bindings/v8/NPV8Object.h"
31 #include "bindings/v8/ScriptController.h"
32 #include "bindings/v8/ScriptSourceCode.h"
33 #include "bindings/v8/V8Binding.h"
34 #include "bindings/v8/V8GCController.h"
35 #include "bindings/v8/V8NPUtils.h"
36 #include "bindings/v8/V8ObjectConstructor.h"
37 #include "bindings/v8/V8ScriptRunner.h"
38 #include "bindings/v8/WrapperTypeInfo.h"
39 #include "bindings/v8/npruntime_impl.h"
40 #include "bindings/v8/npruntime_priv.h"
41 #include "core/frame/DOMWindow.h"
42 #include "core/frame/Frame.h"
43 #include "platform/UserGestureIndicator.h"
44 #include "wtf/OwnPtr.h"
47 #include "wtf/StringExtras.h"
48 #include "wtf/text/WTFString.h"
50 using namespace WebCore;
54 const WrapperTypeInfo* npObjectTypeInfo()
56 static const WrapperTypeInfo typeInfo = { gin::kEmbedderBlink, 0, 0, 0, 0, 0, 0, 0, WrapperTypeObjectPrototype };
60 // FIXME: Comments on why use malloc and free.
61 static NPObject* allocV8NPObject(NPP, NPClass*)
63 return static_cast<NPObject*>(malloc(sizeof(V8NPObject)));
66 static void freeV8NPObject(NPObject* npObject)
68 V8NPObject* v8NpObject = reinterpret_cast<V8NPObject*>(npObject);
69 disposeUnderlyingV8Object(npObject, v8::Isolate::GetCurrent());
73 static NPClass V8NPObjectClass = {
74 NP_CLASS_STRUCT_VERSION,
77 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
80 static v8::Local<v8::Context> toV8Context(NPP npp, NPObject* npObject)
82 ASSERT(npObject->_class == &V8NPObjectClass);
83 V8NPObject* object = reinterpret_cast<V8NPObject*>(npObject);
84 DOMWindow* window = object->rootObject;
85 if (!window || !window->isCurrentlyDisplayedInFrame())
86 return v8::Local<v8::Context>();
87 return ScriptController::mainWorldContext(object->rootObject->frame());
90 static PassOwnPtr<v8::Handle<v8::Value>[]> createValueListFromVariantArgs(const NPVariant* arguments, uint32_t argumentCount, NPObject* owner, v8::Isolate* isolate)
92 OwnPtr<v8::Handle<v8::Value>[]> argv = adoptArrayPtr(new v8::Handle<v8::Value>[argumentCount]);
93 for (uint32_t index = 0; index < argumentCount; index++) {
94 const NPVariant* arg = &arguments[index];
95 argv[index] = convertNPVariantToV8Object(arg, owner, isolate);
97 return argv.release();
100 // Create an identifier (null terminated utf8 char*) from the NPIdentifier.
101 static v8::Local<v8::String> npIdentifierToV8Identifier(NPIdentifier name, v8::Isolate* isolate)
103 PrivateIdentifier* identifier = static_cast<PrivateIdentifier*>(name);
104 if (identifier->isString)
105 return v8AtomicString(isolate, static_cast<const char*>(identifier->value.string));
108 snprintf(buffer, sizeof(buffer), "%d", identifier->value.number);
109 return v8AtomicString(isolate, buffer);
112 NPObject* v8ObjectToNPObject(v8::Handle<v8::Object> object)
114 return reinterpret_cast<NPObject*>(object->GetAlignedPointerFromInternalField(v8DOMWrapperObjectIndex));
117 NPObject* npCreateV8ScriptObject(NPP npp, v8::Handle<v8::Object> object, DOMWindow* root, v8::Isolate* isolate)
119 // Check to see if this object is already wrapped.
120 if (object->InternalFieldCount() == npObjectInternalFieldCount) {
121 const WrapperTypeInfo* typeInfo = static_cast<const WrapperTypeInfo*>(object->GetAlignedPointerFromInternalField(v8DOMWrapperTypeIndex));
122 if (typeInfo == npObjectTypeInfo()) {
123 NPObject* returnValue = v8ObjectToNPObject(object);
124 _NPN_RetainObject(returnValue);
129 V8NPObjectVector* objectVector = 0;
130 if (V8PerContextData* perContextData = V8PerContextData::from(object->CreationContext())) {
131 int v8ObjectHash = object->GetIdentityHash();
132 ASSERT(v8ObjectHash);
133 V8NPObjectMap* v8NPObjectMap = perContextData->v8NPObjectMap();
134 V8NPObjectMap::iterator iter = v8NPObjectMap->find(v8ObjectHash);
135 if (iter != v8NPObjectMap->end()) {
136 V8NPObjectVector& objects = iter->value;
137 for (size_t index = 0; index < objects.size(); ++index) {
138 V8NPObject* v8npObject = objects.at(index);
139 if (v8npObject->v8Object == object && v8npObject->rootObject == root) {
140 _NPN_RetainObject(&v8npObject->object);
141 return reinterpret_cast<NPObject*>(v8npObject);
145 iter = v8NPObjectMap->set(v8ObjectHash, V8NPObjectVector()).iterator;
147 objectVector = &iter->value;
150 V8NPObject* v8npObject = reinterpret_cast<V8NPObject*>(_NPN_CreateObject(npp, &V8NPObjectClass));
151 // This is uninitialized memory, we need to clear it so that
152 // Persistent::Reset won't try to Dispose anything bogus.
153 new (&v8npObject->v8Object) v8::Persistent<v8::Object>();
154 v8npObject->v8Object.Reset(isolate, object);
155 v8npObject->rootObject = root;
158 objectVector->append(v8npObject);
160 return reinterpret_cast<NPObject*>(v8npObject);
163 V8NPObject* npObjectToV8NPObject(NPObject* npObject)
165 if (npObject->_class != &V8NPObjectClass)
167 V8NPObject* v8NpObject = reinterpret_cast<V8NPObject*>(npObject);
168 if (v8NpObject->v8Object.IsEmpty())
173 void disposeUnderlyingV8Object(NPObject* npObject, v8::Isolate* isolate)
176 V8NPObject* v8NpObject = npObjectToV8NPObject(npObject);
179 v8::HandleScope scope(isolate);
180 v8::Handle<v8::Object> v8Object = v8::Local<v8::Object>::New(isolate, v8NpObject->v8Object);
181 ASSERT(!v8Object->CreationContext().IsEmpty());
182 if (V8PerContextData* perContextData = V8PerContextData::from(v8Object->CreationContext())) {
183 V8NPObjectMap* v8NPObjectMap = perContextData->v8NPObjectMap();
184 int v8ObjectHash = v8Object->GetIdentityHash();
185 ASSERT(v8ObjectHash);
186 V8NPObjectMap::iterator iter = v8NPObjectMap->find(v8ObjectHash);
187 if (iter != v8NPObjectMap->end()) {
188 V8NPObjectVector& objects = iter->value;
189 for (size_t index = 0; index < objects.size(); ++index) {
190 if (objects.at(index) == v8NpObject) {
191 objects.remove(index);
195 if (objects.isEmpty())
196 v8NPObjectMap->remove(v8ObjectHash);
199 v8NpObject->v8Object.Reset();
200 v8NpObject->rootObject = 0;
203 } // namespace WebCore
205 bool _NPN_Invoke(NPP npp, NPObject* npObject, NPIdentifier methodName, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result)
210 v8::Isolate* isolate = v8::Isolate::GetCurrent();
212 V8NPObject* v8NpObject = npObjectToV8NPObject(npObject);
214 if (npObject->_class->invoke)
215 return npObject->_class->invoke(npObject, methodName, arguments, argumentCount, result);
217 VOID_TO_NPVARIANT(*result);
221 PrivateIdentifier* identifier = static_cast<PrivateIdentifier*>(methodName);
222 if (!identifier->isString)
225 if (!strcmp(identifier->value.string, "eval")) {
226 if (argumentCount != 1)
228 if (arguments[0].type != NPVariantType_String)
230 return _NPN_Evaluate(npp, npObject, const_cast<NPString*>(&arguments[0].value.stringValue), result);
233 v8::HandleScope handleScope(isolate);
234 // FIXME: should use the plugin's owner frame as the security context.
235 v8::Handle<v8::Context> context = toV8Context(npp, npObject);
236 if (context.IsEmpty())
239 v8::Context::Scope scope(context);
240 ExceptionCatcher exceptionCatcher;
242 v8::Handle<v8::Object> v8Object = v8::Local<v8::Object>::New(isolate, v8NpObject->v8Object);
243 v8::Handle<v8::Value> functionObject = v8Object->Get(v8AtomicString(isolate, identifier->value.string));
244 if (functionObject.IsEmpty() || functionObject->IsNull()) {
245 NULL_TO_NPVARIANT(*result);
248 if (functionObject->IsUndefined()) {
249 VOID_TO_NPVARIANT(*result);
253 Frame* frame = v8NpObject->rootObject->frame();
256 // Call the function object.
257 v8::Handle<v8::Function> function = v8::Handle<v8::Function>::Cast(functionObject);
258 OwnPtr<v8::Handle<v8::Value>[]> argv = createValueListFromVariantArgs(arguments, argumentCount, npObject, isolate);
259 v8::Local<v8::Value> resultObject = frame->script().callFunction(function, v8Object, argumentCount, argv.get());
261 // If we had an error, return false. The spec is a little unclear here, but says "Returns true if the method was
262 // successfully invoked". If we get an error return value, was that successfully invoked?
263 if (resultObject.IsEmpty())
266 convertV8ObjectToNPVariant(resultObject, npObject, result, isolate);
270 // FIXME: Fix it same as _NPN_Invoke (HandleScope and such).
271 bool _NPN_InvokeDefault(NPP npp, NPObject* npObject, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result)
276 v8::Isolate* isolate = v8::Isolate::GetCurrent();
278 V8NPObject* v8NpObject = npObjectToV8NPObject(npObject);
280 if (npObject->_class->invokeDefault)
281 return npObject->_class->invokeDefault(npObject, arguments, argumentCount, result);
283 VOID_TO_NPVARIANT(*result);
287 VOID_TO_NPVARIANT(*result);
289 v8::HandleScope handleScope(isolate);
290 v8::Handle<v8::Context> context = toV8Context(npp, npObject);
291 if (context.IsEmpty())
294 v8::Context::Scope scope(context);
295 ExceptionCatcher exceptionCatcher;
297 // Lookup the function object and call it.
298 v8::Local<v8::Object> functionObject = v8::Local<v8::Object>::New(isolate, v8NpObject->v8Object);
299 if (!functionObject->IsFunction())
302 v8::Local<v8::Value> resultObject;
303 v8::Handle<v8::Function> function = v8::Local<v8::Function>::Cast(functionObject);
304 if (!function->IsNull()) {
305 Frame* frame = v8NpObject->rootObject->frame();
308 OwnPtr<v8::Handle<v8::Value>[]> argv = createValueListFromVariantArgs(arguments, argumentCount, npObject, isolate);
309 resultObject = frame->script().callFunction(function, functionObject, argumentCount, argv.get());
311 // If we had an error, return false. The spec is a little unclear here, but says "Returns true if the method was
312 // successfully invoked". If we get an error return value, was that successfully invoked?
313 if (resultObject.IsEmpty())
316 convertV8ObjectToNPVariant(resultObject, npObject, result, isolate);
320 bool _NPN_Evaluate(NPP npp, NPObject* npObject, NPString* npScript, NPVariant* result)
322 // FIXME: Give the embedder a way to control this.
323 bool popupsAllowed = false;
324 return _NPN_EvaluateHelper(npp, popupsAllowed, npObject, npScript, result);
327 bool _NPN_EvaluateHelper(NPP npp, bool popupsAllowed, NPObject* npObject, NPString* npScript, NPVariant* result)
329 VOID_TO_NPVARIANT(*result);
333 V8NPObject* v8NpObject = npObjectToV8NPObject(npObject);
337 v8::Isolate* isolate = v8::Isolate::GetCurrent();
338 v8::HandleScope handleScope(isolate);
339 v8::Handle<v8::Context> context = toV8Context(npp, npObject);
340 if (context.IsEmpty())
343 v8::Context::Scope scope(context);
344 ExceptionCatcher exceptionCatcher;
346 // FIXME: Is this branch still needed after switching to using UserGestureIndicator?
349 filename = "npscript";
351 Frame* frame = v8NpObject->rootObject->frame();
354 String script = String::fromUTF8(npScript->UTF8Characters, npScript->UTF8Length);
356 UserGestureIndicator gestureIndicator(popupsAllowed ? DefinitelyProcessingNewUserGesture : PossiblyProcessingUserGesture);
357 v8::Local<v8::Value> v8result = frame->script().executeScriptAndReturnValue(context, ScriptSourceCode(script, KURL(ParsedURLString, filename)));
359 if (v8result.IsEmpty())
362 if (_NPN_IsAlive(npObject))
363 convertV8ObjectToNPVariant(v8result, npObject, result, isolate);
367 bool _NPN_GetProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName, NPVariant* result)
372 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
373 v8::Isolate* isolate = v8::Isolate::GetCurrent();
374 v8::HandleScope handleScope(isolate);
375 v8::Handle<v8::Context> context = toV8Context(npp, npObject);
376 if (context.IsEmpty())
379 v8::Context::Scope scope(context);
380 ExceptionCatcher exceptionCatcher;
382 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
383 v8::Local<v8::Value> v8result = obj->Get(npIdentifierToV8Identifier(propertyName, isolate));
385 if (v8result.IsEmpty())
388 convertV8ObjectToNPVariant(v8result, npObject, result, isolate);
392 if (npObject->_class->hasProperty && npObject->_class->getProperty) {
393 if (npObject->_class->hasProperty(npObject, propertyName))
394 return npObject->_class->getProperty(npObject, propertyName, result);
397 VOID_TO_NPVARIANT(*result);
401 bool _NPN_SetProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName, const NPVariant* value)
406 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
407 v8::Isolate* isolate = v8::Isolate::GetCurrent();
408 v8::HandleScope handleScope(isolate);
409 v8::Handle<v8::Context> context = toV8Context(npp, npObject);
410 if (context.IsEmpty())
413 v8::Context::Scope scope(context);
414 ExceptionCatcher exceptionCatcher;
416 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
417 obj->Set(npIdentifierToV8Identifier(propertyName, context->GetIsolate()), convertNPVariantToV8Object(value, object->rootObject->frame()->script().windowScriptNPObject(), context->GetIsolate()));
421 if (npObject->_class->setProperty)
422 return npObject->_class->setProperty(npObject, propertyName, value);
427 bool _NPN_RemoveProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName)
432 V8NPObject* object = npObjectToV8NPObject(npObject);
436 v8::Isolate* isolate = v8::Isolate::GetCurrent();
437 v8::HandleScope handleScope(isolate);
438 v8::Handle<v8::Context> context = toV8Context(npp, npObject);
439 if (context.IsEmpty())
441 v8::Context::Scope scope(context);
442 ExceptionCatcher exceptionCatcher;
444 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
445 // FIXME: Verify that setting to undefined is right.
446 obj->Set(npIdentifierToV8Identifier(propertyName, isolate), v8::Undefined(isolate));
450 bool _NPN_HasProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName)
455 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
456 v8::Isolate* isolate = v8::Isolate::GetCurrent();
457 v8::HandleScope handleScope(isolate);
458 v8::Handle<v8::Context> context = toV8Context(npp, npObject);
459 if (context.IsEmpty())
461 v8::Context::Scope scope(context);
462 ExceptionCatcher exceptionCatcher;
464 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
465 return obj->Has(npIdentifierToV8Identifier(propertyName, isolate));
468 if (npObject->_class->hasProperty)
469 return npObject->_class->hasProperty(npObject, propertyName);
473 bool _NPN_HasMethod(NPP npp, NPObject* npObject, NPIdentifier methodName)
478 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
479 v8::Isolate* isolate = v8::Isolate::GetCurrent();
480 v8::HandleScope handleScope(isolate);
481 v8::Handle<v8::Context> context = toV8Context(npp, npObject);
482 if (context.IsEmpty())
484 v8::Context::Scope scope(context);
485 ExceptionCatcher exceptionCatcher;
487 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
488 v8::Handle<v8::Value> prop = obj->Get(npIdentifierToV8Identifier(methodName, isolate));
489 return prop->IsFunction();
492 if (npObject->_class->hasMethod)
493 return npObject->_class->hasMethod(npObject, methodName);
497 void _NPN_SetException(NPObject* npObject, const NPUTF8 *message)
499 if (!npObject || !npObjectToV8NPObject(npObject)) {
500 // We won't be able to find a proper scope for this exception, so just throw it.
501 // This is consistent with JSC, which throws a global exception all the time.
502 throwError(v8GeneralError, message, v8::Isolate::GetCurrent());
506 v8::HandleScope handleScope(v8::Isolate::GetCurrent());
507 v8::Handle<v8::Context> context = toV8Context(0, npObject);
508 if (context.IsEmpty())
511 v8::Context::Scope scope(context);
512 ExceptionCatcher exceptionCatcher;
514 throwError(v8GeneralError, message, context->GetIsolate());
517 bool _NPN_Enumerate(NPP npp, NPObject* npObject, NPIdentifier** identifier, uint32_t* count)
522 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
523 v8::Isolate* isolate = v8::Isolate::GetCurrent();
524 v8::HandleScope handleScope(isolate);
525 v8::Local<v8::Context> context = toV8Context(npp, npObject);
526 if (context.IsEmpty())
528 v8::Context::Scope scope(context);
529 ExceptionCatcher exceptionCatcher;
531 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
533 // FIXME: http://b/issue?id=1210340: Use a v8::Object::Keys() method when it exists, instead of evaluating javascript.
535 // FIXME: Figure out how to cache this helper function. Run a helper function that collects the properties
536 // on the object into an array.
537 const char enumeratorCode[] =
540 " for (var prop in obj) {"
541 " props[props.length] = prop;"
545 v8::Handle<v8::String> source = v8AtomicString(isolate, enumeratorCode);
546 v8::Handle<v8::Value> result = V8ScriptRunner::compileAndRunInternalScript(source, context->GetIsolate());
547 ASSERT(!result.IsEmpty());
548 ASSERT(result->IsFunction());
549 v8::Handle<v8::Function> enumerator = v8::Handle<v8::Function>::Cast(result);
550 v8::Handle<v8::Value> argv[] = { obj };
551 v8::Local<v8::Value> propsObj = V8ScriptRunner::callInternalFunction(enumerator, v8::Handle<v8::Object>::Cast(result), WTF_ARRAY_LENGTH(argv), argv, context->GetIsolate());
552 if (propsObj.IsEmpty())
555 // Convert the results into an array of NPIdentifiers.
556 v8::Handle<v8::Array> props = v8::Handle<v8::Array>::Cast(propsObj);
557 *count = props->Length();
558 *identifier = static_cast<NPIdentifier*>(malloc(sizeof(NPIdentifier*) * *count));
559 for (uint32_t i = 0; i < *count; ++i) {
560 v8::Local<v8::Value> name = props->Get(v8::Integer::New(context->GetIsolate(), i));
561 (*identifier)[i] = getStringIdentifier(v8::Local<v8::String>::Cast(name));
566 if (NP_CLASS_STRUCT_VERSION_HAS_ENUM(npObject->_class) && npObject->_class->enumerate)
567 return npObject->_class->enumerate(npObject, identifier, count);
572 bool _NPN_Construct(NPP npp, NPObject* npObject, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result)
577 v8::Isolate* isolate = v8::Isolate::GetCurrent();
579 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
580 v8::HandleScope handleScope(isolate);
581 v8::Handle<v8::Context> context = toV8Context(npp, npObject);
582 if (context.IsEmpty())
584 v8::Context::Scope scope(context);
585 ExceptionCatcher exceptionCatcher;
587 // Lookup the constructor function.
588 v8::Handle<v8::Object> ctorObj = v8::Local<v8::Object>::New(isolate, object->v8Object);
589 if (!ctorObj->IsFunction())
592 // Call the constructor.
593 v8::Local<v8::Value> resultObject;
594 v8::Handle<v8::Function> ctor = v8::Handle<v8::Function>::Cast(ctorObj);
595 if (!ctor->IsNull()) {
596 Frame* frame = object->rootObject->frame();
598 OwnPtr<v8::Handle<v8::Value>[]> argv = createValueListFromVariantArgs(arguments, argumentCount, npObject, isolate);
599 resultObject = V8ObjectConstructor::newInstanceInDocument(ctor, argumentCount, argv.get(), frame ? frame->document() : 0);
602 if (resultObject.IsEmpty())
605 convertV8ObjectToNPVariant(resultObject, npObject, result, isolate);
609 if (NP_CLASS_STRUCT_VERSION_HAS_CTOR(npObject->_class) && npObject->_class->construct)
610 return npObject->_class->construct(npObject, arguments, argumentCount, result);