2 * Copyright (C) 2004, 2006 Apple Computer, Inc. All rights reserved.
3 * Copyright (C) 2007, 2008, 2009 Google, Inc. All rights reserved.
4 * Copyright (C) 2014 Opera Software ASA. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
16 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
19 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
23 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #include "bindings/core/v8/NPV8Object.h"
31 #include "bindings/core/v8/ScriptController.h"
32 #include "bindings/core/v8/ScriptSourceCode.h"
33 #include "bindings/core/v8/V8Binding.h"
34 #include "bindings/core/v8/V8GCController.h"
35 #include "bindings/core/v8/V8NPUtils.h"
36 #include "bindings/core/v8/V8ObjectConstructor.h"
37 #include "bindings/core/v8/V8ScriptRunner.h"
38 #include "bindings/core/v8/WrapperTypeInfo.h"
39 #include "bindings/core/v8/npruntime_impl.h"
40 #include "bindings/core/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"
45 #include "wtf/StringExtras.h"
46 #include "wtf/text/WTFString.h"
49 using namespace blink;
53 void trace(Visitor*, ScriptWrappableBase*)
61 const WrapperTypeInfo* npObjectTypeInfo()
63 static const WrapperTypeInfo typeInfo = { gin::kEmbedderBlink, 0, 0, 0, trace, 0, 0, 0, 0, 0, 0, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::Dependent, WrapperTypeInfo::RefCountedObject };
67 // FIXME: Comments on why use malloc and free.
68 static NPObject* allocV8NPObject(NPP, NPClass*)
70 return static_cast<NPObject*>(malloc(sizeof(V8NPObject)));
73 static void freeV8NPObject(NPObject* npObject)
75 V8NPObject* v8NpObject = reinterpret_cast<V8NPObject*>(npObject);
76 disposeUnderlyingV8Object(v8::Isolate::GetCurrent(), npObject);
80 static NPClass V8NPObjectClass = {
81 NP_CLASS_STRUCT_VERSION,
84 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
87 static ScriptState* mainWorldScriptState(v8::Isolate* isolate, NPP npp, NPObject* npObject)
89 ASSERT(npObject->_class == &V8NPObjectClass);
90 V8NPObject* object = reinterpret_cast<V8NPObject*>(npObject);
91 LocalDOMWindow* window = object->rootObject;
92 if (!window || !window->isCurrentlyDisplayedInFrame())
94 v8::HandleScope handleScope(isolate);
95 v8::Handle<v8::Context> context = toV8Context(object->rootObject->frame(), DOMWrapperWorld::mainWorld());
96 return ScriptState::from(context);
99 static PassOwnPtr<v8::Handle<v8::Value>[]> createValueListFromVariantArgs(const NPVariant* arguments, uint32_t argumentCount, NPObject* owner, v8::Isolate* isolate)
101 OwnPtr<v8::Handle<v8::Value>[]> argv = adoptArrayPtr(new v8::Handle<v8::Value>[argumentCount]);
102 for (uint32_t index = 0; index < argumentCount; index++) {
103 const NPVariant* arg = &arguments[index];
104 argv[index] = convertNPVariantToV8Object(isolate, arg, owner);
106 return argv.release();
109 // Create an identifier (null terminated utf8 char*) from the NPIdentifier.
110 static v8::Local<v8::String> npIdentifierToV8Identifier(v8::Isolate* isolate, NPIdentifier name)
112 PrivateIdentifier* identifier = static_cast<PrivateIdentifier*>(name);
113 if (identifier->isString)
114 return v8AtomicString(isolate, static_cast<const char*>(identifier->value.string));
117 snprintf(buffer, sizeof(buffer), "%d", identifier->value.number);
118 return v8AtomicString(isolate, buffer);
121 NPObject* v8ObjectToNPObject(v8::Handle<v8::Object> object)
123 return reinterpret_cast<NPObject*>(toScriptWrappableBase(object));
126 bool isWrappedNPObject(v8::Handle<v8::Object> object)
128 if (object->InternalFieldCount() == npObjectInternalFieldCount) {
129 const WrapperTypeInfo* typeInfo = static_cast<const WrapperTypeInfo*>(object->GetAlignedPointerFromInternalField(v8DOMWrapperTypeIndex));
130 return typeInfo == npObjectTypeInfo();
135 NPObject* npCreateV8ScriptObject(v8::Isolate* isolate, NPP npp, v8::Handle<v8::Object> object, LocalDOMWindow* root)
137 // Check to see if this object is already wrapped.
138 if (isWrappedNPObject(object)) {
139 NPObject* returnValue = v8ObjectToNPObject(object);
140 _NPN_RetainObject(returnValue);
144 V8NPObjectVector* objectVector = 0;
145 if (V8PerContextData* perContextData = V8PerContextData::from(object->CreationContext())) {
146 int v8ObjectHash = object->GetIdentityHash();
147 ASSERT(v8ObjectHash);
148 V8NPObjectMap* v8NPObjectMap = perContextData->v8NPObjectMap();
149 V8NPObjectMap::iterator iter = v8NPObjectMap->find(v8ObjectHash);
150 if (iter != v8NPObjectMap->end()) {
151 V8NPObjectVector& objects = iter->value;
152 for (size_t index = 0; index < objects.size(); ++index) {
153 V8NPObject* v8npObject = objects.at(index);
154 if (v8npObject->v8Object == object && v8npObject->rootObject == root) {
155 _NPN_RetainObject(&v8npObject->object);
156 return reinterpret_cast<NPObject*>(v8npObject);
159 objectVector = &iter->value;
161 objectVector = &v8NPObjectMap->set(v8ObjectHash, V8NPObjectVector()).storedValue->value;
165 V8NPObject* v8npObject = reinterpret_cast<V8NPObject*>(_NPN_CreateObject(npp, &V8NPObjectClass));
166 // This is uninitialized memory, we need to clear it so that
167 // Persistent::Reset won't try to Dispose anything bogus.
168 new (&v8npObject->v8Object) v8::Persistent<v8::Object>();
169 v8npObject->v8Object.Reset(isolate, object);
170 v8npObject->rootObject = root;
173 objectVector->append(v8npObject);
175 return reinterpret_cast<NPObject*>(v8npObject);
178 V8NPObject* npObjectToV8NPObject(NPObject* npObject)
180 if (npObject->_class != &V8NPObjectClass)
182 V8NPObject* v8NpObject = reinterpret_cast<V8NPObject*>(npObject);
183 if (v8NpObject->v8Object.IsEmpty())
188 ScriptWrappableBase* npObjectToScriptWrappableBase(NPObject* npObject)
190 return reinterpret_cast<ScriptWrappableBase*>(npObject);
193 void disposeUnderlyingV8Object(v8::Isolate* isolate, NPObject* npObject)
196 V8NPObject* v8NpObject = npObjectToV8NPObject(npObject);
199 v8::HandleScope scope(isolate);
200 v8::Handle<v8::Object> v8Object = v8::Local<v8::Object>::New(isolate, v8NpObject->v8Object);
201 ASSERT(!v8Object->CreationContext().IsEmpty());
202 if (V8PerContextData* perContextData = V8PerContextData::from(v8Object->CreationContext())) {
203 V8NPObjectMap* v8NPObjectMap = perContextData->v8NPObjectMap();
204 int v8ObjectHash = v8Object->GetIdentityHash();
205 ASSERT(v8ObjectHash);
206 V8NPObjectMap::iterator iter = v8NPObjectMap->find(v8ObjectHash);
207 if (iter != v8NPObjectMap->end()) {
208 V8NPObjectVector& objects = iter->value;
209 for (size_t index = 0; index < objects.size(); ++index) {
210 if (objects.at(index) == v8NpObject) {
211 objects.remove(index);
215 if (objects.isEmpty())
216 v8NPObjectMap->remove(v8ObjectHash);
219 v8NpObject->v8Object.Reset();
220 v8NpObject->rootObject = 0;
225 bool _NPN_Invoke(NPP npp, NPObject* npObject, NPIdentifier methodName, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result)
230 v8::Isolate* isolate = v8::Isolate::GetCurrent();
232 V8NPObject* v8NpObject = npObjectToV8NPObject(npObject);
234 if (npObject->_class->invoke)
235 return npObject->_class->invoke(npObject, methodName, arguments, argumentCount, result);
237 VOID_TO_NPVARIANT(*result);
241 PrivateIdentifier* identifier = static_cast<PrivateIdentifier*>(methodName);
242 if (!identifier->isString)
245 if (!strcmp(identifier->value.string, "eval")) {
246 if (argumentCount != 1)
248 if (arguments[0].type != NPVariantType_String)
250 return _NPN_Evaluate(npp, npObject, const_cast<NPString*>(&arguments[0].value.stringValue), result);
253 // FIXME: should use the plugin's owner frame as the security context.
254 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
258 ScriptState::Scope scope(scriptState);
259 ExceptionCatcher exceptionCatcher;
261 v8::Handle<v8::Object> v8Object = v8::Local<v8::Object>::New(isolate, v8NpObject->v8Object);
262 v8::Handle<v8::Value> functionObject = v8Object->Get(v8AtomicString(isolate, identifier->value.string));
263 if (functionObject.IsEmpty() || functionObject->IsNull()) {
264 NULL_TO_NPVARIANT(*result);
267 if (functionObject->IsUndefined()) {
268 VOID_TO_NPVARIANT(*result);
272 LocalFrame* frame = v8NpObject->rootObject->frame();
275 // Call the function object.
276 v8::Handle<v8::Function> function = v8::Handle<v8::Function>::Cast(functionObject);
277 OwnPtr<v8::Handle<v8::Value>[]> argv = createValueListFromVariantArgs(arguments, argumentCount, npObject, isolate);
278 v8::Local<v8::Value> resultObject = frame->script().callFunction(function, v8Object, argumentCount, argv.get());
280 // If we had an error, return false. The spec is a little unclear here, but says "Returns true if the method was
281 // successfully invoked". If we get an error return value, was that successfully invoked?
282 if (resultObject.IsEmpty())
285 convertV8ObjectToNPVariant(isolate, resultObject, npObject, result);
289 // FIXME: Fix it same as _NPN_Invoke (HandleScope and such).
290 bool _NPN_InvokeDefault(NPP npp, NPObject* npObject, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result)
295 v8::Isolate* isolate = v8::Isolate::GetCurrent();
297 V8NPObject* v8NpObject = npObjectToV8NPObject(npObject);
299 if (npObject->_class->invokeDefault)
300 return npObject->_class->invokeDefault(npObject, arguments, argumentCount, result);
302 VOID_TO_NPVARIANT(*result);
306 VOID_TO_NPVARIANT(*result);
308 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
312 ScriptState::Scope scope(scriptState);
313 ExceptionCatcher exceptionCatcher;
315 // Lookup the function object and call it.
316 v8::Local<v8::Object> functionObject = v8::Local<v8::Object>::New(isolate, v8NpObject->v8Object);
317 if (!functionObject->IsFunction())
320 v8::Local<v8::Value> resultObject;
321 v8::Handle<v8::Function> function = v8::Local<v8::Function>::Cast(functionObject);
322 if (!function->IsNull()) {
323 LocalFrame* frame = v8NpObject->rootObject->frame();
326 OwnPtr<v8::Handle<v8::Value>[]> argv = createValueListFromVariantArgs(arguments, argumentCount, npObject, isolate);
327 resultObject = frame->script().callFunction(function, functionObject, argumentCount, argv.get());
329 // If we had an error, return false. The spec is a little unclear here, but says "Returns true if the method was
330 // successfully invoked". If we get an error return value, was that successfully invoked?
331 if (resultObject.IsEmpty())
334 convertV8ObjectToNPVariant(isolate, resultObject, npObject, result);
338 bool _NPN_Evaluate(NPP npp, NPObject* npObject, NPString* npScript, NPVariant* result)
340 // FIXME: Give the embedder a way to control this.
341 bool popupsAllowed = false;
342 return _NPN_EvaluateHelper(npp, popupsAllowed, npObject, npScript, result);
345 bool _NPN_EvaluateHelper(NPP npp, bool popupsAllowed, NPObject* npObject, NPString* npScript, NPVariant* result)
347 VOID_TO_NPVARIANT(*result);
351 V8NPObject* v8NpObject = npObjectToV8NPObject(npObject);
355 v8::Isolate* isolate = v8::Isolate::GetCurrent();
356 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
360 ScriptState::Scope scope(scriptState);
361 ExceptionCatcher exceptionCatcher;
363 // FIXME: Is this branch still needed after switching to using UserGestureIndicator?
366 filename = "npscript";
368 LocalFrame* frame = v8NpObject->rootObject->frame();
371 String script = String::fromUTF8(npScript->UTF8Characters, npScript->UTF8Length);
373 UserGestureIndicator gestureIndicator(popupsAllowed ? DefinitelyProcessingNewUserGesture : PossiblyProcessingUserGesture);
374 v8::Local<v8::Value> v8result = frame->script().executeScriptAndReturnValue(scriptState->context(), ScriptSourceCode(script, KURL(ParsedURLString, filename)));
376 if (v8result.IsEmpty())
379 if (_NPN_IsAlive(npObject))
380 convertV8ObjectToNPVariant(isolate, v8result, npObject, result);
384 bool _NPN_GetProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName, NPVariant* result)
389 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
390 v8::Isolate* isolate = v8::Isolate::GetCurrent();
391 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
395 ScriptState::Scope scope(scriptState);
396 ExceptionCatcher exceptionCatcher;
398 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
399 v8::Local<v8::Value> v8result = obj->Get(npIdentifierToV8Identifier(isolate, propertyName));
401 if (v8result.IsEmpty())
404 convertV8ObjectToNPVariant(isolate, v8result, npObject, result);
408 if (npObject->_class->hasProperty && npObject->_class->getProperty) {
409 if (npObject->_class->hasProperty(npObject, propertyName))
410 return npObject->_class->getProperty(npObject, propertyName, result);
413 VOID_TO_NPVARIANT(*result);
417 bool _NPN_SetProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName, const NPVariant* value)
422 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
423 v8::Isolate* isolate = v8::Isolate::GetCurrent();
424 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
428 ScriptState::Scope scope(scriptState);
429 ExceptionCatcher exceptionCatcher;
431 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
432 obj->Set(npIdentifierToV8Identifier(isolate, propertyName), convertNPVariantToV8Object(isolate, value, object->rootObject->frame()->script().windowScriptNPObject()));
436 if (npObject->_class->setProperty)
437 return npObject->_class->setProperty(npObject, propertyName, value);
442 bool _NPN_RemoveProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName)
447 V8NPObject* object = npObjectToV8NPObject(npObject);
451 v8::Isolate* isolate = v8::Isolate::GetCurrent();
452 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
455 ScriptState::Scope scope(scriptState);
456 ExceptionCatcher exceptionCatcher;
458 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
459 // FIXME: Verify that setting to undefined is right.
460 obj->Set(npIdentifierToV8Identifier(isolate, propertyName), v8::Undefined(isolate));
464 bool _NPN_HasProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName)
469 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
470 v8::Isolate* isolate = v8::Isolate::GetCurrent();
471 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
474 ScriptState::Scope scope(scriptState);
475 ExceptionCatcher exceptionCatcher;
477 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
478 return obj->Has(npIdentifierToV8Identifier(isolate, propertyName));
481 if (npObject->_class->hasProperty)
482 return npObject->_class->hasProperty(npObject, propertyName);
486 bool _NPN_HasMethod(NPP npp, NPObject* npObject, NPIdentifier methodName)
491 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
492 v8::Isolate* isolate = v8::Isolate::GetCurrent();
493 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
496 ScriptState::Scope scope(scriptState);
497 ExceptionCatcher exceptionCatcher;
499 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
500 v8::Handle<v8::Value> prop = obj->Get(npIdentifierToV8Identifier(isolate, methodName));
501 return prop->IsFunction();
504 if (npObject->_class->hasMethod)
505 return npObject->_class->hasMethod(npObject, methodName);
509 void _NPN_SetException(NPObject* npObject, const NPUTF8 *message)
511 if (!npObject || !npObjectToV8NPObject(npObject)) {
512 // We won't be able to find a proper scope for this exception, so just throw it.
513 // This is consistent with JSC, which throws a global exception all the time.
514 V8ThrowException::throwGeneralError(v8::Isolate::GetCurrent(), message);
518 v8::Isolate* isolate = v8::Isolate::GetCurrent();
519 ScriptState* scriptState = mainWorldScriptState(isolate, 0, npObject);
523 ScriptState::Scope scope(scriptState);
524 ExceptionCatcher exceptionCatcher;
526 V8ThrowException::throwGeneralError(isolate, message);
529 bool _NPN_Enumerate(NPP npp, NPObject* npObject, NPIdentifier** identifier, uint32_t* count)
534 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
535 v8::Isolate* isolate = v8::Isolate::GetCurrent();
536 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
539 ScriptState::Scope scope(scriptState);
540 ExceptionCatcher exceptionCatcher;
542 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
544 // FIXME: http://b/issue?id=1210340: Use a v8::Object::Keys() method when it exists, instead of evaluating javascript.
546 // FIXME: Figure out how to cache this helper function. Run a helper function that collects the properties
547 // on the object into an array.
548 const char enumeratorCode[] =
551 " for (var prop in obj) {"
552 " props[props.length] = prop;"
556 v8::Handle<v8::String> source = v8AtomicString(isolate, enumeratorCode);
557 v8::Handle<v8::Value> result = V8ScriptRunner::compileAndRunInternalScript(source, isolate);
558 ASSERT(!result.IsEmpty());
559 ASSERT(result->IsFunction());
560 v8::Handle<v8::Function> enumerator = v8::Handle<v8::Function>::Cast(result);
561 v8::Handle<v8::Value> argv[] = { obj };
562 v8::Local<v8::Value> propsObj = V8ScriptRunner::callInternalFunction(enumerator, v8::Handle<v8::Object>::Cast(result), WTF_ARRAY_LENGTH(argv), argv, isolate);
563 if (propsObj.IsEmpty())
566 // Convert the results into an array of NPIdentifiers.
567 v8::Handle<v8::Array> props = v8::Handle<v8::Array>::Cast(propsObj);
568 *count = props->Length();
569 *identifier = static_cast<NPIdentifier*>(calloc(*count, sizeof(NPIdentifier)));
570 for (uint32_t i = 0; i < *count; ++i) {
571 v8::Local<v8::Value> name = props->Get(v8::Integer::New(isolate, i));
572 (*identifier)[i] = getStringIdentifier(v8::Local<v8::String>::Cast(name));
577 if (NP_CLASS_STRUCT_VERSION_HAS_ENUM(npObject->_class) && npObject->_class->enumerate)
578 return npObject->_class->enumerate(npObject, identifier, count);
583 bool _NPN_Construct(NPP npp, NPObject* npObject, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result)
588 v8::Isolate* isolate = v8::Isolate::GetCurrent();
590 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
591 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
594 ScriptState::Scope scope(scriptState);
595 ExceptionCatcher exceptionCatcher;
597 // Lookup the constructor function.
598 v8::Handle<v8::Object> ctorObj = v8::Local<v8::Object>::New(isolate, object->v8Object);
599 if (!ctorObj->IsFunction())
602 // Call the constructor.
603 v8::Local<v8::Value> resultObject;
604 v8::Handle<v8::Function> ctor = v8::Handle<v8::Function>::Cast(ctorObj);
605 if (!ctor->IsNull()) {
606 LocalFrame* frame = object->rootObject->frame();
608 OwnPtr<v8::Handle<v8::Value>[]> argv = createValueListFromVariantArgs(arguments, argumentCount, npObject, isolate);
609 resultObject = V8ObjectConstructor::newInstanceInDocument(isolate, ctor, argumentCount, argv.get(), frame ? frame->document() : 0);
612 if (resultObject.IsEmpty())
615 convertV8ObjectToNPVariant(isolate, resultObject, npObject, result);
619 if (NP_CLASS_STRUCT_VERSION_HAS_CTOR(npObject->_class) && npObject->_class->construct)
620 return npObject->_class->construct(npObject, arguments, argumentCount, result);