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 WrapperPersistentNode* createPersistentHandle(ScriptWrappableBase* internalPointer)
63 const WrapperTypeInfo* npObjectTypeInfo()
65 static const WrapperTypeInfo typeInfo = { gin::kEmbedderBlink, 0, 0, 0, createPersistentHandle, 0, 0, 0, 0, 0, 0, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::Dependent, WrapperTypeInfo::RefCountedObject };
69 // FIXME: Comments on why use malloc and free.
70 static NPObject* allocV8NPObject(NPP, NPClass*)
72 return static_cast<NPObject*>(malloc(sizeof(V8NPObject)));
75 static void freeV8NPObject(NPObject* npObject)
77 V8NPObject* v8NpObject = reinterpret_cast<V8NPObject*>(npObject);
78 disposeUnderlyingV8Object(npObject, v8::Isolate::GetCurrent());
82 static NPClass V8NPObjectClass = {
83 NP_CLASS_STRUCT_VERSION,
86 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
89 static ScriptState* mainWorldScriptState(v8::Isolate* isolate, NPP npp, NPObject* npObject)
91 ASSERT(npObject->_class == &V8NPObjectClass);
92 V8NPObject* object = reinterpret_cast<V8NPObject*>(npObject);
93 LocalDOMWindow* window = object->rootObject;
94 if (!window || !window->isCurrentlyDisplayedInFrame())
96 v8::HandleScope handleScope(isolate);
97 v8::Handle<v8::Context> context = toV8Context(object->rootObject->frame(), DOMWrapperWorld::mainWorld());
98 return ScriptState::from(context);
101 static PassOwnPtr<v8::Handle<v8::Value>[]> createValueListFromVariantArgs(const NPVariant* arguments, uint32_t argumentCount, NPObject* owner, v8::Isolate* isolate)
103 OwnPtr<v8::Handle<v8::Value>[]> argv = adoptArrayPtr(new v8::Handle<v8::Value>[argumentCount]);
104 for (uint32_t index = 0; index < argumentCount; index++) {
105 const NPVariant* arg = &arguments[index];
106 argv[index] = convertNPVariantToV8Object(arg, owner, isolate);
108 return argv.release();
111 // Create an identifier (null terminated utf8 char*) from the NPIdentifier.
112 static v8::Local<v8::String> npIdentifierToV8Identifier(NPIdentifier name, v8::Isolate* isolate)
114 PrivateIdentifier* identifier = static_cast<PrivateIdentifier*>(name);
115 if (identifier->isString)
116 return v8AtomicString(isolate, static_cast<const char*>(identifier->value.string));
119 snprintf(buffer, sizeof(buffer), "%d", identifier->value.number);
120 return v8AtomicString(isolate, buffer);
123 NPObject* v8ObjectToNPObject(v8::Handle<v8::Object> object)
125 return reinterpret_cast<NPObject*>(toScriptWrappableBase(object));
128 bool isWrappedNPObject(v8::Handle<v8::Object> object)
130 if (object->InternalFieldCount() == npObjectInternalFieldCount) {
131 const WrapperTypeInfo* typeInfo = static_cast<const WrapperTypeInfo*>(object->GetAlignedPointerFromInternalField(v8DOMWrapperTypeIndex));
132 return typeInfo == npObjectTypeInfo();
137 NPObject* npCreateV8ScriptObject(NPP npp, v8::Handle<v8::Object> object, LocalDOMWindow* root, v8::Isolate* isolate)
139 // Check to see if this object is already wrapped.
140 if (isWrappedNPObject(object)) {
141 NPObject* returnValue = v8ObjectToNPObject(object);
142 _NPN_RetainObject(returnValue);
146 V8NPObjectVector* objectVector = 0;
147 if (V8PerContextData* perContextData = V8PerContextData::from(object->CreationContext())) {
148 int v8ObjectHash = object->GetIdentityHash();
149 ASSERT(v8ObjectHash);
150 V8NPObjectMap* v8NPObjectMap = perContextData->v8NPObjectMap();
151 V8NPObjectMap::iterator iter = v8NPObjectMap->find(v8ObjectHash);
152 if (iter != v8NPObjectMap->end()) {
153 V8NPObjectVector& objects = iter->value;
154 for (size_t index = 0; index < objects.size(); ++index) {
155 V8NPObject* v8npObject = objects.at(index);
156 if (v8npObject->v8Object == object && v8npObject->rootObject == root) {
157 _NPN_RetainObject(&v8npObject->object);
158 return reinterpret_cast<NPObject*>(v8npObject);
161 objectVector = &iter->value;
163 objectVector = &v8NPObjectMap->set(v8ObjectHash, V8NPObjectVector()).storedValue->value;
167 V8NPObject* v8npObject = reinterpret_cast<V8NPObject*>(_NPN_CreateObject(npp, &V8NPObjectClass));
168 // This is uninitialized memory, we need to clear it so that
169 // Persistent::Reset won't try to Dispose anything bogus.
170 new (&v8npObject->v8Object) v8::Persistent<v8::Object>();
171 v8npObject->v8Object.Reset(isolate, object);
172 v8npObject->rootObject = root;
175 objectVector->append(v8npObject);
177 return reinterpret_cast<NPObject*>(v8npObject);
180 V8NPObject* npObjectToV8NPObject(NPObject* npObject)
182 if (npObject->_class != &V8NPObjectClass)
184 V8NPObject* v8NpObject = reinterpret_cast<V8NPObject*>(npObject);
185 if (v8NpObject->v8Object.IsEmpty())
190 ScriptWrappableBase* npObjectToScriptWrappableBase(NPObject* npObject)
192 return reinterpret_cast<ScriptWrappableBase*>(npObject);
195 void disposeUnderlyingV8Object(NPObject* npObject, v8::Isolate* isolate)
198 V8NPObject* v8NpObject = npObjectToV8NPObject(npObject);
201 v8::HandleScope scope(isolate);
202 v8::Handle<v8::Object> v8Object = v8::Local<v8::Object>::New(isolate, v8NpObject->v8Object);
203 ASSERT(!v8Object->CreationContext().IsEmpty());
204 if (V8PerContextData* perContextData = V8PerContextData::from(v8Object->CreationContext())) {
205 V8NPObjectMap* v8NPObjectMap = perContextData->v8NPObjectMap();
206 int v8ObjectHash = v8Object->GetIdentityHash();
207 ASSERT(v8ObjectHash);
208 V8NPObjectMap::iterator iter = v8NPObjectMap->find(v8ObjectHash);
209 if (iter != v8NPObjectMap->end()) {
210 V8NPObjectVector& objects = iter->value;
211 for (size_t index = 0; index < objects.size(); ++index) {
212 if (objects.at(index) == v8NpObject) {
213 objects.remove(index);
217 if (objects.isEmpty())
218 v8NPObjectMap->remove(v8ObjectHash);
221 v8NpObject->v8Object.Reset();
222 v8NpObject->rootObject = 0;
227 bool _NPN_Invoke(NPP npp, NPObject* npObject, NPIdentifier methodName, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result)
229 ScriptForbiddenScope::AllowSuperUnsafeScript thisShouldBeRemoved;
234 v8::Isolate* isolate = v8::Isolate::GetCurrent();
236 V8NPObject* v8NpObject = npObjectToV8NPObject(npObject);
238 if (npObject->_class->invoke)
239 return npObject->_class->invoke(npObject, methodName, arguments, argumentCount, result);
241 VOID_TO_NPVARIANT(*result);
245 PrivateIdentifier* identifier = static_cast<PrivateIdentifier*>(methodName);
246 if (!identifier->isString)
249 if (!strcmp(identifier->value.string, "eval")) {
250 if (argumentCount != 1)
252 if (arguments[0].type != NPVariantType_String)
254 return _NPN_Evaluate(npp, npObject, const_cast<NPString*>(&arguments[0].value.stringValue), result);
257 // FIXME: should use the plugin's owner frame as the security context.
258 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
262 ScriptState::Scope scope(scriptState);
263 ExceptionCatcher exceptionCatcher;
265 v8::Handle<v8::Object> v8Object = v8::Local<v8::Object>::New(isolate, v8NpObject->v8Object);
266 v8::Handle<v8::Value> functionObject = v8Object->Get(v8AtomicString(isolate, identifier->value.string));
267 if (functionObject.IsEmpty() || functionObject->IsNull()) {
268 NULL_TO_NPVARIANT(*result);
271 if (functionObject->IsUndefined()) {
272 VOID_TO_NPVARIANT(*result);
276 LocalFrame* frame = v8NpObject->rootObject->frame();
279 // Call the function object.
280 v8::Handle<v8::Function> function = v8::Handle<v8::Function>::Cast(functionObject);
281 OwnPtr<v8::Handle<v8::Value>[]> argv = createValueListFromVariantArgs(arguments, argumentCount, npObject, isolate);
282 v8::Local<v8::Value> resultObject = frame->script().callFunction(function, v8Object, argumentCount, argv.get());
284 // If we had an error, return false. The spec is a little unclear here, but says "Returns true if the method was
285 // successfully invoked". If we get an error return value, was that successfully invoked?
286 if (resultObject.IsEmpty())
289 convertV8ObjectToNPVariant(resultObject, npObject, result, isolate);
293 // FIXME: Fix it same as _NPN_Invoke (HandleScope and such).
294 bool _NPN_InvokeDefault(NPP npp, NPObject* npObject, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result)
296 ScriptForbiddenScope::AllowSuperUnsafeScript thisShouldBeRemoved;
301 v8::Isolate* isolate = v8::Isolate::GetCurrent();
303 V8NPObject* v8NpObject = npObjectToV8NPObject(npObject);
305 if (npObject->_class->invokeDefault)
306 return npObject->_class->invokeDefault(npObject, arguments, argumentCount, result);
308 VOID_TO_NPVARIANT(*result);
312 VOID_TO_NPVARIANT(*result);
314 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
318 ScriptState::Scope scope(scriptState);
319 ExceptionCatcher exceptionCatcher;
321 // Lookup the function object and call it.
322 v8::Local<v8::Object> functionObject = v8::Local<v8::Object>::New(isolate, v8NpObject->v8Object);
323 if (!functionObject->IsFunction())
326 v8::Local<v8::Value> resultObject;
327 v8::Handle<v8::Function> function = v8::Local<v8::Function>::Cast(functionObject);
328 if (!function->IsNull()) {
329 LocalFrame* frame = v8NpObject->rootObject->frame();
332 OwnPtr<v8::Handle<v8::Value>[]> argv = createValueListFromVariantArgs(arguments, argumentCount, npObject, isolate);
333 resultObject = frame->script().callFunction(function, functionObject, argumentCount, argv.get());
335 // If we had an error, return false. The spec is a little unclear here, but says "Returns true if the method was
336 // successfully invoked". If we get an error return value, was that successfully invoked?
337 if (resultObject.IsEmpty())
340 convertV8ObjectToNPVariant(resultObject, npObject, result, isolate);
344 bool _NPN_Evaluate(NPP npp, NPObject* npObject, NPString* npScript, NPVariant* result)
346 // FIXME: Give the embedder a way to control this.
347 bool popupsAllowed = false;
348 return _NPN_EvaluateHelper(npp, popupsAllowed, npObject, npScript, result);
351 bool _NPN_EvaluateHelper(NPP npp, bool popupsAllowed, NPObject* npObject, NPString* npScript, NPVariant* result)
353 ScriptForbiddenScope::AllowSuperUnsafeScript thisShouldBeRemoved;
355 VOID_TO_NPVARIANT(*result);
359 V8NPObject* v8NpObject = npObjectToV8NPObject(npObject);
363 v8::Isolate* isolate = v8::Isolate::GetCurrent();
364 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
368 ScriptState::Scope scope(scriptState);
369 ExceptionCatcher exceptionCatcher;
371 // FIXME: Is this branch still needed after switching to using UserGestureIndicator?
374 filename = "npscript";
376 LocalFrame* frame = v8NpObject->rootObject->frame();
379 String script = String::fromUTF8(npScript->UTF8Characters, npScript->UTF8Length);
381 UserGestureIndicator gestureIndicator(popupsAllowed ? DefinitelyProcessingNewUserGesture : PossiblyProcessingUserGesture);
382 v8::Local<v8::Value> v8result = frame->script().executeScriptAndReturnValue(scriptState->context(), ScriptSourceCode(script, KURL(ParsedURLString, filename)));
384 if (v8result.IsEmpty())
387 if (_NPN_IsAlive(npObject))
388 convertV8ObjectToNPVariant(v8result, npObject, result, isolate);
392 bool _NPN_GetProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName, NPVariant* result)
397 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
398 v8::Isolate* isolate = v8::Isolate::GetCurrent();
399 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
403 ScriptState::Scope scope(scriptState);
404 ExceptionCatcher exceptionCatcher;
406 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
407 v8::Local<v8::Value> v8result = obj->Get(npIdentifierToV8Identifier(propertyName, isolate));
409 if (v8result.IsEmpty())
412 convertV8ObjectToNPVariant(v8result, npObject, result, isolate);
416 if (npObject->_class->hasProperty && npObject->_class->getProperty) {
417 if (npObject->_class->hasProperty(npObject, propertyName))
418 return npObject->_class->getProperty(npObject, propertyName, result);
421 VOID_TO_NPVARIANT(*result);
425 bool _NPN_SetProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName, const NPVariant* value)
430 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
431 v8::Isolate* isolate = v8::Isolate::GetCurrent();
432 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
436 ScriptState::Scope scope(scriptState);
437 ExceptionCatcher exceptionCatcher;
439 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
440 obj->Set(npIdentifierToV8Identifier(propertyName, isolate), convertNPVariantToV8Object(value, object->rootObject->frame()->script().windowScriptNPObject(), isolate));
444 if (npObject->_class->setProperty)
445 return npObject->_class->setProperty(npObject, propertyName, value);
450 bool _NPN_RemoveProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName)
455 V8NPObject* object = npObjectToV8NPObject(npObject);
459 v8::Isolate* isolate = v8::Isolate::GetCurrent();
460 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
463 ScriptState::Scope scope(scriptState);
464 ExceptionCatcher exceptionCatcher;
466 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
467 // FIXME: Verify that setting to undefined is right.
468 obj->Set(npIdentifierToV8Identifier(propertyName, isolate), v8::Undefined(isolate));
472 bool _NPN_HasProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName)
477 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
478 v8::Isolate* isolate = v8::Isolate::GetCurrent();
479 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
482 ScriptState::Scope scope(scriptState);
483 ExceptionCatcher exceptionCatcher;
485 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
486 return obj->Has(npIdentifierToV8Identifier(propertyName, isolate));
489 if (npObject->_class->hasProperty)
490 return npObject->_class->hasProperty(npObject, propertyName);
494 bool _NPN_HasMethod(NPP npp, NPObject* npObject, NPIdentifier methodName)
499 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
500 v8::Isolate* isolate = v8::Isolate::GetCurrent();
501 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
504 ScriptState::Scope scope(scriptState);
505 ExceptionCatcher exceptionCatcher;
507 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
508 v8::Handle<v8::Value> prop = obj->Get(npIdentifierToV8Identifier(methodName, isolate));
509 return prop->IsFunction();
512 if (npObject->_class->hasMethod)
513 return npObject->_class->hasMethod(npObject, methodName);
517 void _NPN_SetException(NPObject* npObject, const NPUTF8 *message)
519 if (!npObject || !npObjectToV8NPObject(npObject)) {
520 // We won't be able to find a proper scope for this exception, so just throw it.
521 // This is consistent with JSC, which throws a global exception all the time.
522 V8ThrowException::throwGeneralError(message, v8::Isolate::GetCurrent());
526 v8::Isolate* isolate = v8::Isolate::GetCurrent();
527 ScriptState* scriptState = mainWorldScriptState(isolate, 0, npObject);
531 ScriptState::Scope scope(scriptState);
532 ExceptionCatcher exceptionCatcher;
534 V8ThrowException::throwGeneralError(message, isolate);
537 bool _NPN_Enumerate(NPP npp, NPObject* npObject, NPIdentifier** identifier, uint32_t* count)
542 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
543 v8::Isolate* isolate = v8::Isolate::GetCurrent();
544 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
547 ScriptState::Scope scope(scriptState);
548 ExceptionCatcher exceptionCatcher;
550 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
552 // FIXME: http://b/issue?id=1210340: Use a v8::Object::Keys() method when it exists, instead of evaluating javascript.
554 // FIXME: Figure out how to cache this helper function. Run a helper function that collects the properties
555 // on the object into an array.
556 const char enumeratorCode[] =
559 " for (var prop in obj) {"
560 " props[props.length] = prop;"
564 v8::Handle<v8::String> source = v8AtomicString(isolate, enumeratorCode);
565 v8::Handle<v8::Value> result = V8ScriptRunner::compileAndRunInternalScript(source, isolate);
566 ASSERT(!result.IsEmpty());
567 ASSERT(result->IsFunction());
568 v8::Handle<v8::Function> enumerator = v8::Handle<v8::Function>::Cast(result);
569 v8::Handle<v8::Value> argv[] = { obj };
570 v8::Local<v8::Value> propsObj = V8ScriptRunner::callInternalFunction(enumerator, v8::Handle<v8::Object>::Cast(result), WTF_ARRAY_LENGTH(argv), argv, isolate);
571 if (propsObj.IsEmpty())
574 // Convert the results into an array of NPIdentifiers.
575 v8::Handle<v8::Array> props = v8::Handle<v8::Array>::Cast(propsObj);
576 *count = props->Length();
577 *identifier = static_cast<NPIdentifier*>(calloc(*count, sizeof(NPIdentifier)));
578 for (uint32_t i = 0; i < *count; ++i) {
579 v8::Local<v8::Value> name = props->Get(v8::Integer::New(isolate, i));
580 (*identifier)[i] = getStringIdentifier(v8::Local<v8::String>::Cast(name));
585 if (NP_CLASS_STRUCT_VERSION_HAS_ENUM(npObject->_class) && npObject->_class->enumerate)
586 return npObject->_class->enumerate(npObject, identifier, count);
591 bool _NPN_Construct(NPP npp, NPObject* npObject, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result)
596 v8::Isolate* isolate = v8::Isolate::GetCurrent();
598 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
599 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
602 ScriptState::Scope scope(scriptState);
603 ExceptionCatcher exceptionCatcher;
605 // Lookup the constructor function.
606 v8::Handle<v8::Object> ctorObj = v8::Local<v8::Object>::New(isolate, object->v8Object);
607 if (!ctorObj->IsFunction())
610 // Call the constructor.
611 v8::Local<v8::Value> resultObject;
612 v8::Handle<v8::Function> ctor = v8::Handle<v8::Function>::Cast(ctorObj);
613 if (!ctor->IsNull()) {
614 LocalFrame* frame = object->rootObject->frame();
616 OwnPtr<v8::Handle<v8::Value>[]> argv = createValueListFromVariantArgs(arguments, argumentCount, npObject, isolate);
617 resultObject = V8ObjectConstructor::newInstanceInDocument(isolate, ctor, argumentCount, argv.get(), frame ? frame->document() : 0);
620 if (resultObject.IsEmpty())
623 convertV8ObjectToNPVariant(resultObject, npObject, result, isolate);
627 if (NP_CLASS_STRUCT_VERSION_HAS_CTOR(npObject->_class) && npObject->_class->construct)
628 return npObject->_class->construct(npObject, arguments, argumentCount, result);