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 const WrapperTypeInfo* npObjectTypeInfo()
55 static const WrapperTypeInfo typeInfo = { gin::kEmbedderBlink, 0, 0, 0, 0, 0, 0, 0, WrapperTypeObjectPrototype, RefCountedObject };
59 // FIXME: Comments on why use malloc and free.
60 static NPObject* allocV8NPObject(NPP, NPClass*)
62 return static_cast<NPObject*>(malloc(sizeof(V8NPObject)));
65 static void freeV8NPObject(NPObject* npObject)
67 V8NPObject* v8NpObject = reinterpret_cast<V8NPObject*>(npObject);
68 disposeUnderlyingV8Object(npObject, v8::Isolate::GetCurrent());
72 static NPClass V8NPObjectClass = {
73 NP_CLASS_STRUCT_VERSION,
76 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
79 static ScriptState* mainWorldScriptState(v8::Isolate* isolate, NPP npp, NPObject* npObject)
81 ASSERT(npObject->_class == &V8NPObjectClass);
82 V8NPObject* object = reinterpret_cast<V8NPObject*>(npObject);
83 LocalDOMWindow* window = object->rootObject;
84 if (!window || !window->isCurrentlyDisplayedInFrame())
86 v8::HandleScope handleScope(isolate);
87 v8::Handle<v8::Context> context = toV8Context(object->rootObject->frame(), DOMWrapperWorld::mainWorld());
88 return ScriptState::from(context);
91 static PassOwnPtr<v8::Handle<v8::Value>[]> createValueListFromVariantArgs(const NPVariant* arguments, uint32_t argumentCount, NPObject* owner, v8::Isolate* isolate)
93 OwnPtr<v8::Handle<v8::Value>[]> argv = adoptArrayPtr(new v8::Handle<v8::Value>[argumentCount]);
94 for (uint32_t index = 0; index < argumentCount; index++) {
95 const NPVariant* arg = &arguments[index];
96 argv[index] = convertNPVariantToV8Object(arg, owner, isolate);
98 return argv.release();
101 // Create an identifier (null terminated utf8 char*) from the NPIdentifier.
102 static v8::Local<v8::String> npIdentifierToV8Identifier(NPIdentifier name, v8::Isolate* isolate)
104 PrivateIdentifier* identifier = static_cast<PrivateIdentifier*>(name);
105 if (identifier->isString)
106 return v8AtomicString(isolate, static_cast<const char*>(identifier->value.string));
109 snprintf(buffer, sizeof(buffer), "%d", identifier->value.number);
110 return v8AtomicString(isolate, buffer);
113 NPObject* v8ObjectToNPObject(v8::Handle<v8::Object> object)
115 return reinterpret_cast<NPObject*>(toInternalPointer(object));
118 bool isWrappedNPObject(v8::Handle<v8::Object> object)
120 if (object->InternalFieldCount() == npObjectInternalFieldCount) {
121 const WrapperTypeInfo* typeInfo = static_cast<const WrapperTypeInfo*>(object->GetAlignedPointerFromInternalField(v8DOMWrapperTypeIndex));
122 return typeInfo == npObjectTypeInfo();
127 NPObject* npCreateV8ScriptObject(NPP npp, v8::Handle<v8::Object> object, LocalDOMWindow* root, v8::Isolate* isolate)
129 // Check to see if this object is already wrapped.
130 if (isWrappedNPObject(object)) {
131 NPObject* returnValue = v8ObjectToNPObject(object);
132 _NPN_RetainObject(returnValue);
136 V8NPObjectVector* objectVector = 0;
137 if (V8PerContextData* perContextData = V8PerContextData::from(object->CreationContext())) {
138 int v8ObjectHash = object->GetIdentityHash();
139 ASSERT(v8ObjectHash);
140 V8NPObjectMap* v8NPObjectMap = perContextData->v8NPObjectMap();
141 V8NPObjectMap::iterator iter = v8NPObjectMap->find(v8ObjectHash);
142 if (iter != v8NPObjectMap->end()) {
143 V8NPObjectVector& objects = iter->value;
144 for (size_t index = 0; index < objects.size(); ++index) {
145 V8NPObject* v8npObject = objects.at(index);
146 if (v8npObject->v8Object == object && v8npObject->rootObject == root) {
147 _NPN_RetainObject(&v8npObject->object);
148 return reinterpret_cast<NPObject*>(v8npObject);
151 objectVector = &iter->value;
153 objectVector = &v8NPObjectMap->set(v8ObjectHash, V8NPObjectVector()).storedValue->value;
157 V8NPObject* v8npObject = reinterpret_cast<V8NPObject*>(_NPN_CreateObject(npp, &V8NPObjectClass));
158 // This is uninitialized memory, we need to clear it so that
159 // Persistent::Reset won't try to Dispose anything bogus.
160 new (&v8npObject->v8Object) v8::Persistent<v8::Object>();
161 v8npObject->v8Object.Reset(isolate, object);
162 v8npObject->rootObject = root;
165 objectVector->append(v8npObject);
167 return reinterpret_cast<NPObject*>(v8npObject);
170 V8NPObject* npObjectToV8NPObject(NPObject* npObject)
172 if (npObject->_class != &V8NPObjectClass)
174 V8NPObject* v8NpObject = reinterpret_cast<V8NPObject*>(npObject);
175 if (v8NpObject->v8Object.IsEmpty())
180 ScriptWrappableBase* npObjectToInternalPointer(NPObject* npObject)
182 return reinterpret_cast<ScriptWrappableBase*>(npObject);
185 void disposeUnderlyingV8Object(NPObject* npObject, v8::Isolate* isolate)
188 V8NPObject* v8NpObject = npObjectToV8NPObject(npObject);
191 v8::HandleScope scope(isolate);
192 v8::Handle<v8::Object> v8Object = v8::Local<v8::Object>::New(isolate, v8NpObject->v8Object);
193 ASSERT(!v8Object->CreationContext().IsEmpty());
194 if (V8PerContextData* perContextData = V8PerContextData::from(v8Object->CreationContext())) {
195 V8NPObjectMap* v8NPObjectMap = perContextData->v8NPObjectMap();
196 int v8ObjectHash = v8Object->GetIdentityHash();
197 ASSERT(v8ObjectHash);
198 V8NPObjectMap::iterator iter = v8NPObjectMap->find(v8ObjectHash);
199 if (iter != v8NPObjectMap->end()) {
200 V8NPObjectVector& objects = iter->value;
201 for (size_t index = 0; index < objects.size(); ++index) {
202 if (objects.at(index) == v8NpObject) {
203 objects.remove(index);
207 if (objects.isEmpty())
208 v8NPObjectMap->remove(v8ObjectHash);
211 v8NpObject->v8Object.Reset();
212 v8NpObject->rootObject = 0;
217 bool _NPN_Invoke(NPP npp, NPObject* npObject, NPIdentifier methodName, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result)
219 ScriptForbiddenScope::AllowSuperUnsafeScript thisShouldBeRemoved;
224 v8::Isolate* isolate = v8::Isolate::GetCurrent();
226 V8NPObject* v8NpObject = npObjectToV8NPObject(npObject);
228 if (npObject->_class->invoke)
229 return npObject->_class->invoke(npObject, methodName, arguments, argumentCount, result);
231 VOID_TO_NPVARIANT(*result);
235 PrivateIdentifier* identifier = static_cast<PrivateIdentifier*>(methodName);
236 if (!identifier->isString)
239 if (!strcmp(identifier->value.string, "eval")) {
240 if (argumentCount != 1)
242 if (arguments[0].type != NPVariantType_String)
244 return _NPN_Evaluate(npp, npObject, const_cast<NPString*>(&arguments[0].value.stringValue), result);
247 // FIXME: should use the plugin's owner frame as the security context.
248 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
252 ScriptState::Scope scope(scriptState);
253 ExceptionCatcher exceptionCatcher;
255 v8::Handle<v8::Object> v8Object = v8::Local<v8::Object>::New(isolate, v8NpObject->v8Object);
256 v8::Handle<v8::Value> functionObject = v8Object->Get(v8AtomicString(isolate, identifier->value.string));
257 if (functionObject.IsEmpty() || functionObject->IsNull()) {
258 NULL_TO_NPVARIANT(*result);
261 if (functionObject->IsUndefined()) {
262 VOID_TO_NPVARIANT(*result);
266 LocalFrame* frame = v8NpObject->rootObject->frame();
269 // Call the function object.
270 v8::Handle<v8::Function> function = v8::Handle<v8::Function>::Cast(functionObject);
271 OwnPtr<v8::Handle<v8::Value>[]> argv = createValueListFromVariantArgs(arguments, argumentCount, npObject, isolate);
272 v8::Local<v8::Value> resultObject = frame->script().callFunction(function, v8Object, argumentCount, argv.get());
274 // If we had an error, return false. The spec is a little unclear here, but says "Returns true if the method was
275 // successfully invoked". If we get an error return value, was that successfully invoked?
276 if (resultObject.IsEmpty())
279 convertV8ObjectToNPVariant(resultObject, npObject, result, isolate);
283 // FIXME: Fix it same as _NPN_Invoke (HandleScope and such).
284 bool _NPN_InvokeDefault(NPP npp, NPObject* npObject, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result)
286 ScriptForbiddenScope::AllowSuperUnsafeScript thisShouldBeRemoved;
291 v8::Isolate* isolate = v8::Isolate::GetCurrent();
293 V8NPObject* v8NpObject = npObjectToV8NPObject(npObject);
295 if (npObject->_class->invokeDefault)
296 return npObject->_class->invokeDefault(npObject, arguments, argumentCount, result);
298 VOID_TO_NPVARIANT(*result);
302 VOID_TO_NPVARIANT(*result);
304 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
308 ScriptState::Scope scope(scriptState);
309 ExceptionCatcher exceptionCatcher;
311 // Lookup the function object and call it.
312 v8::Local<v8::Object> functionObject = v8::Local<v8::Object>::New(isolate, v8NpObject->v8Object);
313 if (!functionObject->IsFunction())
316 v8::Local<v8::Value> resultObject;
317 v8::Handle<v8::Function> function = v8::Local<v8::Function>::Cast(functionObject);
318 if (!function->IsNull()) {
319 LocalFrame* frame = v8NpObject->rootObject->frame();
322 OwnPtr<v8::Handle<v8::Value>[]> argv = createValueListFromVariantArgs(arguments, argumentCount, npObject, isolate);
323 resultObject = frame->script().callFunction(function, functionObject, argumentCount, argv.get());
325 // If we had an error, return false. The spec is a little unclear here, but says "Returns true if the method was
326 // successfully invoked". If we get an error return value, was that successfully invoked?
327 if (resultObject.IsEmpty())
330 convertV8ObjectToNPVariant(resultObject, npObject, result, isolate);
334 bool _NPN_Evaluate(NPP npp, NPObject* npObject, NPString* npScript, NPVariant* result)
336 // FIXME: Give the embedder a way to control this.
337 bool popupsAllowed = false;
338 return _NPN_EvaluateHelper(npp, popupsAllowed, npObject, npScript, result);
341 bool _NPN_EvaluateHelper(NPP npp, bool popupsAllowed, NPObject* npObject, NPString* npScript, NPVariant* result)
343 ScriptForbiddenScope::AllowSuperUnsafeScript thisShouldBeRemoved;
345 VOID_TO_NPVARIANT(*result);
349 V8NPObject* v8NpObject = npObjectToV8NPObject(npObject);
353 v8::Isolate* isolate = v8::Isolate::GetCurrent();
354 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
358 ScriptState::Scope scope(scriptState);
359 ExceptionCatcher exceptionCatcher;
361 // FIXME: Is this branch still needed after switching to using UserGestureIndicator?
364 filename = "npscript";
366 LocalFrame* frame = v8NpObject->rootObject->frame();
369 String script = String::fromUTF8(npScript->UTF8Characters, npScript->UTF8Length);
371 UserGestureIndicator gestureIndicator(popupsAllowed ? DefinitelyProcessingNewUserGesture : PossiblyProcessingUserGesture);
372 v8::Local<v8::Value> v8result = frame->script().executeScriptAndReturnValue(scriptState->context(), ScriptSourceCode(script, KURL(ParsedURLString, filename)));
374 if (v8result.IsEmpty())
377 if (_NPN_IsAlive(npObject))
378 convertV8ObjectToNPVariant(v8result, npObject, result, isolate);
382 bool _NPN_GetProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName, NPVariant* result)
387 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
388 v8::Isolate* isolate = v8::Isolate::GetCurrent();
389 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
393 ScriptState::Scope scope(scriptState);
394 ExceptionCatcher exceptionCatcher;
396 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
397 v8::Local<v8::Value> v8result = obj->Get(npIdentifierToV8Identifier(propertyName, isolate));
399 if (v8result.IsEmpty())
402 convertV8ObjectToNPVariant(v8result, npObject, result, isolate);
406 if (npObject->_class->hasProperty && npObject->_class->getProperty) {
407 if (npObject->_class->hasProperty(npObject, propertyName))
408 return npObject->_class->getProperty(npObject, propertyName, result);
411 VOID_TO_NPVARIANT(*result);
415 bool _NPN_SetProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName, const NPVariant* value)
420 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
421 v8::Isolate* isolate = v8::Isolate::GetCurrent();
422 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
426 ScriptState::Scope scope(scriptState);
427 ExceptionCatcher exceptionCatcher;
429 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
430 obj->Set(npIdentifierToV8Identifier(propertyName, isolate), convertNPVariantToV8Object(value, object->rootObject->frame()->script().windowScriptNPObject(), isolate));
434 if (npObject->_class->setProperty)
435 return npObject->_class->setProperty(npObject, propertyName, value);
440 bool _NPN_RemoveProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName)
445 V8NPObject* object = npObjectToV8NPObject(npObject);
449 v8::Isolate* isolate = v8::Isolate::GetCurrent();
450 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
453 ScriptState::Scope scope(scriptState);
454 ExceptionCatcher exceptionCatcher;
456 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
457 // FIXME: Verify that setting to undefined is right.
458 obj->Set(npIdentifierToV8Identifier(propertyName, isolate), v8::Undefined(isolate));
462 bool _NPN_HasProperty(NPP npp, NPObject* npObject, NPIdentifier propertyName)
467 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
468 v8::Isolate* isolate = v8::Isolate::GetCurrent();
469 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
472 ScriptState::Scope scope(scriptState);
473 ExceptionCatcher exceptionCatcher;
475 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
476 return obj->Has(npIdentifierToV8Identifier(propertyName, isolate));
479 if (npObject->_class->hasProperty)
480 return npObject->_class->hasProperty(npObject, propertyName);
484 bool _NPN_HasMethod(NPP npp, NPObject* npObject, NPIdentifier methodName)
489 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
490 v8::Isolate* isolate = v8::Isolate::GetCurrent();
491 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
494 ScriptState::Scope scope(scriptState);
495 ExceptionCatcher exceptionCatcher;
497 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
498 v8::Handle<v8::Value> prop = obj->Get(npIdentifierToV8Identifier(methodName, isolate));
499 return prop->IsFunction();
502 if (npObject->_class->hasMethod)
503 return npObject->_class->hasMethod(npObject, methodName);
507 void _NPN_SetException(NPObject* npObject, const NPUTF8 *message)
509 if (!npObject || !npObjectToV8NPObject(npObject)) {
510 // We won't be able to find a proper scope for this exception, so just throw it.
511 // This is consistent with JSC, which throws a global exception all the time.
512 V8ThrowException::throwGeneralError(message, v8::Isolate::GetCurrent());
516 v8::Isolate* isolate = v8::Isolate::GetCurrent();
517 ScriptState* scriptState = mainWorldScriptState(isolate, 0, npObject);
521 ScriptState::Scope scope(scriptState);
522 ExceptionCatcher exceptionCatcher;
524 V8ThrowException::throwGeneralError(message, isolate);
527 bool _NPN_Enumerate(NPP npp, NPObject* npObject, NPIdentifier** identifier, uint32_t* count)
532 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
533 v8::Isolate* isolate = v8::Isolate::GetCurrent();
534 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
537 ScriptState::Scope scope(scriptState);
538 ExceptionCatcher exceptionCatcher;
540 v8::Handle<v8::Object> obj = v8::Local<v8::Object>::New(isolate, object->v8Object);
542 // FIXME: http://b/issue?id=1210340: Use a v8::Object::Keys() method when it exists, instead of evaluating javascript.
544 // FIXME: Figure out how to cache this helper function. Run a helper function that collects the properties
545 // on the object into an array.
546 const char enumeratorCode[] =
549 " for (var prop in obj) {"
550 " props[props.length] = prop;"
554 v8::Handle<v8::String> source = v8AtomicString(isolate, enumeratorCode);
555 v8::Handle<v8::Value> result = V8ScriptRunner::compileAndRunInternalScript(source, isolate);
556 ASSERT(!result.IsEmpty());
557 ASSERT(result->IsFunction());
558 v8::Handle<v8::Function> enumerator = v8::Handle<v8::Function>::Cast(result);
559 v8::Handle<v8::Value> argv[] = { obj };
560 v8::Local<v8::Value> propsObj = V8ScriptRunner::callInternalFunction(enumerator, v8::Handle<v8::Object>::Cast(result), WTF_ARRAY_LENGTH(argv), argv, isolate);
561 if (propsObj.IsEmpty())
564 // Convert the results into an array of NPIdentifiers.
565 v8::Handle<v8::Array> props = v8::Handle<v8::Array>::Cast(propsObj);
566 *count = props->Length();
567 *identifier = static_cast<NPIdentifier*>(calloc(*count, sizeof(NPIdentifier)));
568 for (uint32_t i = 0; i < *count; ++i) {
569 v8::Local<v8::Value> name = props->Get(v8::Integer::New(isolate, i));
570 (*identifier)[i] = getStringIdentifier(v8::Local<v8::String>::Cast(name));
575 if (NP_CLASS_STRUCT_VERSION_HAS_ENUM(npObject->_class) && npObject->_class->enumerate)
576 return npObject->_class->enumerate(npObject, identifier, count);
581 bool _NPN_Construct(NPP npp, NPObject* npObject, const NPVariant* arguments, uint32_t argumentCount, NPVariant* result)
586 v8::Isolate* isolate = v8::Isolate::GetCurrent();
588 if (V8NPObject* object = npObjectToV8NPObject(npObject)) {
589 ScriptState* scriptState = mainWorldScriptState(isolate, npp, npObject);
592 ScriptState::Scope scope(scriptState);
593 ExceptionCatcher exceptionCatcher;
595 // Lookup the constructor function.
596 v8::Handle<v8::Object> ctorObj = v8::Local<v8::Object>::New(isolate, object->v8Object);
597 if (!ctorObj->IsFunction())
600 // Call the constructor.
601 v8::Local<v8::Value> resultObject;
602 v8::Handle<v8::Function> ctor = v8::Handle<v8::Function>::Cast(ctorObj);
603 if (!ctor->IsNull()) {
604 LocalFrame* frame = object->rootObject->frame();
606 OwnPtr<v8::Handle<v8::Value>[]> argv = createValueListFromVariantArgs(arguments, argumentCount, npObject, isolate);
607 resultObject = V8ObjectConstructor::newInstanceInDocument(isolate, ctor, argumentCount, argv.get(), frame ? frame->document() : 0);
610 if (resultObject.IsEmpty())
613 convertV8ObjectToNPVariant(resultObject, npObject, result, isolate);
617 if (NP_CLASS_STRUCT_VERSION_HAS_CTOR(npObject->_class) && npObject->_class->construct)
618 return npObject->_class->construct(npObject, arguments, argumentCount, result);