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/LocalDOMWindow.h"
42 #include "core/frame/LocalFrame.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, RefCountedObject };
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 ScriptState* mainWorldScriptState(v8::Isolate* isolate, NPP npp, NPObject* npObject)
82 ASSERT(npObject->_class == &V8NPObjectClass);
83 V8NPObject* object = reinterpret_cast<V8NPObject*>(npObject);
84 LocalDOMWindow* window = object->rootObject;
85 if (!window || !window->isCurrentlyDisplayedInFrame())
87 v8::HandleScope handleScope(isolate);
88 v8::Handle<v8::Context> context = toV8Context(object->rootObject->frame(), DOMWrapperWorld::mainWorld());
89 return ScriptState::from(context);
92 static PassOwnPtr<v8::Handle<v8::Value>[]> createValueListFromVariantArgs(const NPVariant* arguments, uint32_t argumentCount, NPObject* owner, v8::Isolate* isolate)
94 OwnPtr<v8::Handle<v8::Value>[]> argv = adoptArrayPtr(new v8::Handle<v8::Value>[argumentCount]);
95 for (uint32_t index = 0; index < argumentCount; index++) {
96 const NPVariant* arg = &arguments[index];
97 argv[index] = convertNPVariantToV8Object(arg, owner, isolate);
99 return argv.release();
102 // Create an identifier (null terminated utf8 char*) from the NPIdentifier.
103 static v8::Local<v8::String> npIdentifierToV8Identifier(NPIdentifier name, v8::Isolate* isolate)
105 PrivateIdentifier* identifier = static_cast<PrivateIdentifier*>(name);
106 if (identifier->isString)
107 return v8AtomicString(isolate, static_cast<const char*>(identifier->value.string));
110 snprintf(buffer, sizeof(buffer), "%d", identifier->value.number);
111 return v8AtomicString(isolate, buffer);
114 NPObject* v8ObjectToNPObject(v8::Handle<v8::Object> object)
116 return reinterpret_cast<NPObject*>(object->GetAlignedPointerFromInternalField(v8DOMWrapperObjectIndex));
119 NPObject* npCreateV8ScriptObject(NPP npp, v8::Handle<v8::Object> object, LocalDOMWindow* root, v8::Isolate* isolate)
121 // Check to see if this object is already wrapped.
122 if (object->InternalFieldCount() == npObjectInternalFieldCount) {
123 const WrapperTypeInfo* typeInfo = static_cast<const WrapperTypeInfo*>(object->GetAlignedPointerFromInternalField(v8DOMWrapperTypeIndex));
124 if (typeInfo == npObjectTypeInfo()) {
125 NPObject* returnValue = v8ObjectToNPObject(object);
126 _NPN_RetainObject(returnValue);
131 V8NPObjectVector* objectVector = 0;
132 if (V8PerContextData* perContextData = V8PerContextData::from(object->CreationContext())) {
133 int v8ObjectHash = object->GetIdentityHash();
134 ASSERT(v8ObjectHash);
135 V8NPObjectMap* v8NPObjectMap = perContextData->v8NPObjectMap();
136 V8NPObjectMap::iterator iter = v8NPObjectMap->find(v8ObjectHash);
137 if (iter != v8NPObjectMap->end()) {
138 V8NPObjectVector& objects = iter->value;
139 for (size_t index = 0; index < objects.size(); ++index) {
140 V8NPObject* v8npObject = objects.at(index);
141 if (v8npObject->v8Object == object && v8npObject->rootObject == root) {
142 _NPN_RetainObject(&v8npObject->object);
143 return reinterpret_cast<NPObject*>(v8npObject);
146 objectVector = &iter->value;
148 objectVector = &v8NPObjectMap->set(v8ObjectHash, V8NPObjectVector()).storedValue->value;
152 V8NPObject* v8npObject = reinterpret_cast<V8NPObject*>(_NPN_CreateObject(npp, &V8NPObjectClass));
153 // This is uninitialized memory, we need to clear it so that
154 // Persistent::Reset won't try to Dispose anything bogus.
155 new (&v8npObject->v8Object) v8::Persistent<v8::Object>();
156 v8npObject->v8Object.Reset(isolate, object);
157 v8npObject->rootObject = root;
160 objectVector->append(v8npObject);
162 return reinterpret_cast<NPObject*>(v8npObject);
165 V8NPObject* npObjectToV8NPObject(NPObject* npObject)
167 if (npObject->_class != &V8NPObjectClass)
169 V8NPObject* v8NpObject = reinterpret_cast<V8NPObject*>(npObject);
170 if (v8NpObject->v8Object.IsEmpty())
175 void disposeUnderlyingV8Object(NPObject* npObject, v8::Isolate* isolate)
178 V8NPObject* v8NpObject = npObjectToV8NPObject(npObject);
181 v8::HandleScope scope(isolate);
182 v8::Handle<v8::Object> v8Object = v8::Local<v8::Object>::New(isolate, v8NpObject->v8Object);
183 ASSERT(!v8Object->CreationContext().IsEmpty());
184 if (V8PerContextData* perContextData = V8PerContextData::from(v8Object->CreationContext())) {
185 V8NPObjectMap* v8NPObjectMap = perContextData->v8NPObjectMap();
186 int v8ObjectHash = v8Object->GetIdentityHash();
187 ASSERT(v8ObjectHash);
188 V8NPObjectMap::iterator iter = v8NPObjectMap->find(v8ObjectHash);
189 if (iter != v8NPObjectMap->end()) {
190 V8NPObjectVector& objects = iter->value;
191 for (size_t index = 0; index < objects.size(); ++index) {
192 if (objects.at(index) == v8NpObject) {
193 objects.remove(index);
197 if (objects.isEmpty())
198 v8NPObjectMap->remove(v8ObjectHash);
201 v8NpObject->v8Object.Reset();
202 v8NpObject->rootObject = 0;
205 } // namespace WebCore
207 bool _NPN_Invoke(NPP npp, NPObject* npObject, NPIdentifier methodName, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result)
212 v8::Isolate* isolate = v8::Isolate::GetCurrent();
214 V8NPObject* v8NpObject = npObjectToV8NPObject(npObject);
216 if (npObject->_class->invoke)
217 return npObject->_class->invoke(npObject, methodName, arguments, argumentCount, result);
219 VOID_TO_NPVARIANT(*result);
223 PrivateIdentifier* identifier = static_cast<PrivateIdentifier*>(methodName);
224 if (!identifier->isString)
227 if (!strcmp(identifier->value.string, "eval")) {
228 if (argumentCount != 1)
230 if (arguments[0].type != NPVariantType_String)
232 return _NPN_Evaluate(npp, npObject, const_cast<NPString*>(&arguments[0].value.stringValue), result);
235 // FIXME: should use the plugin's owner frame as the security context.
236 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
240 ScriptState::Scope scope(scriptState);
241 ExceptionCatcher exceptionCatcher;
243 v8::Handle<v8::Object> v8Object = v8::Local<v8::Object>::New(isolate, v8NpObject->v8Object);
244 v8::Handle<v8::Value> functionObject = v8Object->Get(v8AtomicString(isolate, identifier->value.string));
245 if (functionObject.IsEmpty() || functionObject->IsNull()) {
246 NULL_TO_NPVARIANT(*result);
249 if (functionObject->IsUndefined()) {
250 VOID_TO_NPVARIANT(*result);
254 LocalFrame* frame = v8NpObject->rootObject->frame();
257 // Call the function object.
258 v8::Handle<v8::Function> function = v8::Handle<v8::Function>::Cast(functionObject);
259 OwnPtr<v8::Handle<v8::Value>[]> argv = createValueListFromVariantArgs(arguments, argumentCount, npObject, isolate);
260 v8::Local<v8::Value> resultObject = frame->script().callFunction(function, v8Object, argumentCount, argv.get());
262 // If we had an error, return false. The spec is a little unclear here, but says "Returns true if the method was
263 // successfully invoked". If we get an error return value, was that successfully invoked?
264 if (resultObject.IsEmpty())
267 convertV8ObjectToNPVariant(resultObject, npObject, result, isolate);
271 // FIXME: Fix it same as _NPN_Invoke (HandleScope and such).
272 bool _NPN_InvokeDefault(NPP npp, NPObject* npObject, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result)
277 v8::Isolate* isolate = v8::Isolate::GetCurrent();
279 V8NPObject* v8NpObject = npObjectToV8NPObject(npObject);
281 if (npObject->_class->invokeDefault)
282 return npObject->_class->invokeDefault(npObject, arguments, argumentCount, result);
284 VOID_TO_NPVARIANT(*result);
288 VOID_TO_NPVARIANT(*result);
290 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
294 ScriptState::Scope scope(scriptState);
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 LocalFrame* 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 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
342 ScriptState::Scope scope(scriptState);
343 ExceptionCatcher exceptionCatcher;
345 // FIXME: Is this branch still needed after switching to using UserGestureIndicator?
348 filename = "npscript";
350 LocalFrame* frame = v8NpObject->rootObject->frame();
353 String script = String::fromUTF8(npScript->UTF8Characters, npScript->UTF8Length);
355 UserGestureIndicator gestureIndicator(popupsAllowed ? DefinitelyProcessingNewUserGesture : PossiblyProcessingUserGesture);
356 v8::Local<v8::Value> v8result = frame->script().executeScriptAndReturnValue(scriptState->context(), ScriptSourceCode(script, KURL(ParsedURLString, filename)));
358 if (v8result.IsEmpty())
361 if (_NPN_IsAlive(npObject))
362 convertV8ObjectToNPVariant(v8result, npObject, result, isolate);
366 bool _NPN_GetProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName, NPVariant* result)
371 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
372 v8::Isolate* isolate = v8::Isolate::GetCurrent();
373 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
377 ScriptState::Scope scope(scriptState);
378 ExceptionCatcher exceptionCatcher;
380 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
381 v8::Local<v8::Value> v8result = obj->Get(npIdentifierToV8Identifier(propertyName, isolate));
383 if (v8result.IsEmpty())
386 convertV8ObjectToNPVariant(v8result, npObject, result, isolate);
390 if (npObject->_class->hasProperty && npObject->_class->getProperty) {
391 if (npObject->_class->hasProperty(npObject, propertyName))
392 return npObject->_class->getProperty(npObject, propertyName, result);
395 VOID_TO_NPVARIANT(*result);
399 bool _NPN_SetProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName, const NPVariant* value)
404 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
405 v8::Isolate* isolate = v8::Isolate::GetCurrent();
406 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
410 ScriptState::Scope scope(scriptState);
411 ExceptionCatcher exceptionCatcher;
413 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
414 obj->Set(npIdentifierToV8Identifier(propertyName, isolate), convertNPVariantToV8Object(value, object->rootObject->frame()->script().windowScriptNPObject(), isolate));
418 if (npObject->_class->setProperty)
419 return npObject->_class->setProperty(npObject, propertyName, value);
424 bool _NPN_RemoveProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName)
429 V8NPObject* object = npObjectToV8NPObject(npObject);
433 v8::Isolate* isolate = v8::Isolate::GetCurrent();
434 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
437 ScriptState::Scope scope(scriptState);
438 ExceptionCatcher exceptionCatcher;
440 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
441 // FIXME: Verify that setting to undefined is right.
442 obj->Set(npIdentifierToV8Identifier(propertyName, isolate), v8::Undefined(isolate));
446 bool _NPN_HasProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName)
451 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
452 v8::Isolate* isolate = v8::Isolate::GetCurrent();
453 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
456 ScriptState::Scope scope(scriptState);
457 ExceptionCatcher exceptionCatcher;
459 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
460 return obj->Has(npIdentifierToV8Identifier(propertyName, isolate));
463 if (npObject->_class->hasProperty)
464 return npObject->_class->hasProperty(npObject, propertyName);
468 bool _NPN_HasMethod(NPP npp, NPObject* npObject, NPIdentifier methodName)
473 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
474 v8::Isolate* isolate = v8::Isolate::GetCurrent();
475 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
478 ScriptState::Scope scope(scriptState);
479 ExceptionCatcher exceptionCatcher;
481 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
482 v8::Handle<v8::Value> prop = obj->Get(npIdentifierToV8Identifier(methodName, isolate));
483 return prop->IsFunction();
486 if (npObject->_class->hasMethod)
487 return npObject->_class->hasMethod(npObject, methodName);
491 void _NPN_SetException(NPObject* npObject, const NPUTF8 *message)
493 if (!npObject || !npObjectToV8NPObject(npObject)) {
494 // We won't be able to find a proper scope for this exception, so just throw it.
495 // This is consistent with JSC, which throws a global exception all the time.
496 throwError(v8GeneralError, message, v8::Isolate::GetCurrent());
500 v8::Isolate* isolate = v8::Isolate::GetCurrent();
501 ScriptState* scriptState = mainWorldScriptState(isolate, 0, npObject);
505 ScriptState::Scope scope(scriptState);
506 ExceptionCatcher exceptionCatcher;
508 throwError(v8GeneralError, message, isolate);
511 bool _NPN_Enumerate(NPP npp, NPObject* npObject, NPIdentifier** identifier, uint32_t* count)
516 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
517 v8::Isolate* isolate = v8::Isolate::GetCurrent();
518 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
521 ScriptState::Scope scope(scriptState);
522 ExceptionCatcher exceptionCatcher;
524 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
526 // FIXME: http://b/issue?id=1210340: Use a v8::Object::Keys() method when it exists, instead of evaluating javascript.
528 // FIXME: Figure out how to cache this helper function. Run a helper function that collects the properties
529 // on the object into an array.
530 const char enumeratorCode[] =
533 " for (var prop in obj) {"
534 " props[props.length] = prop;"
538 v8::Handle<v8::String> source = v8AtomicString(isolate, enumeratorCode);
539 v8::Handle<v8::Value> result = V8ScriptRunner::compileAndRunInternalScript(source, isolate);
540 ASSERT(!result.IsEmpty());
541 ASSERT(result->IsFunction());
542 v8::Handle<v8::Function> enumerator = v8::Handle<v8::Function>::Cast(result);
543 v8::Handle<v8::Value> argv[] = { obj };
544 v8::Local<v8::Value> propsObj = V8ScriptRunner::callInternalFunction(enumerator, v8::Handle<v8::Object>::Cast(result), WTF_ARRAY_LENGTH(argv), argv, isolate);
545 if (propsObj.IsEmpty())
548 // Convert the results into an array of NPIdentifiers.
549 v8::Handle<v8::Array> props = v8::Handle<v8::Array>::Cast(propsObj);
550 *count = props->Length();
551 *identifier = static_cast<NPIdentifier*>(calloc(*count, sizeof(NPIdentifier)));
552 for (uint32_t i = 0; i < *count; ++i) {
553 v8::Local<v8::Value> name = props->Get(v8::Integer::New(isolate, i));
554 (*identifier)[i] = getStringIdentifier(v8::Local<v8::String>::Cast(name));
559 if (NP_CLASS_STRUCT_VERSION_HAS_ENUM(npObject->_class) && npObject->_class->enumerate)
560 return npObject->_class->enumerate(npObject, identifier, count);
565 bool _NPN_Construct(NPP npp, NPObject* npObject, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result)
570 v8::Isolate* isolate = v8::Isolate::GetCurrent();
572 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
573 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
576 ScriptState::Scope scope(scriptState);
577 ExceptionCatcher exceptionCatcher;
579 // Lookup the constructor function.
580 v8::Handle<v8::Object> ctorObj = v8::Local<v8::Object>::New(isolate, object->v8Object);
581 if (!ctorObj->IsFunction())
584 // Call the constructor.
585 v8::Local<v8::Value> resultObject;
586 v8::Handle<v8::Function> ctor = v8::Handle<v8::Function>::Cast(ctorObj);
587 if (!ctor->IsNull()) {
588 LocalFrame* frame = object->rootObject->frame();
590 OwnPtr<v8::Handle<v8::Value>[]> argv = createValueListFromVariantArgs(arguments, argumentCount, npObject, isolate);
591 resultObject = V8ObjectConstructor::newInstanceInDocument(isolate, ctor, argumentCount, argv.get(), frame ? frame->document() : 0);
594 if (resultObject.IsEmpty())
597 convertV8ObjectToNPVariant(resultObject, npObject, result, isolate);
601 if (NP_CLASS_STRUCT_VERSION_HAS_CTOR(npObject->_class) && npObject->_class->construct)
602 return npObject->_class->construct(npObject, arguments, argumentCount, result);