1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/renderer/pepper/v8_var_converter.h"
9 #include "base/logging.h"
10 #include "base/memory/ref_counted.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/run_loop.h"
14 #include "base/synchronization/waitable_event.h"
15 #include "base/values.h"
16 #include "content/renderer/pepper/resource_converter.h"
17 #include "ppapi/c/pp_bool.h"
18 #include "ppapi/c/pp_var.h"
19 #include "ppapi/shared_impl/array_var.h"
20 #include "ppapi/shared_impl/dictionary_var.h"
21 #include "ppapi/shared_impl/ppapi_globals.h"
22 #include "ppapi/shared_impl/proxy_lock.h"
23 #include "ppapi/shared_impl/scoped_pp_var.h"
24 #include "ppapi/shared_impl/test_globals.h"
25 #include "ppapi/shared_impl/unittest_utils.h"
26 #include "ppapi/shared_impl/var.h"
27 #include "ppapi/shared_impl/var_tracker.h"
28 #include "testing/gtest/include/gtest/gtest.h"
29 #include "v8/include/v8.h"
31 using ppapi::ArrayBufferVar
;
32 using ppapi::ArrayVar
;
33 using ppapi::DictionaryVar
;
34 using ppapi::PpapiGlobals
;
35 using ppapi::ProxyLock
;
36 using ppapi::ScopedPPVar
;
37 using ppapi::StringVar
;
38 using ppapi::TestGlobals
;
39 using ppapi::TestEqual
;
40 using ppapi::VarTracker
;
46 void FromV8ValueComplete(const ScopedPPVar
& scoped_var
,
51 class MockResourceConverter
: public content::ResourceConverter
{
53 virtual ~MockResourceConverter() {}
54 virtual void Reset() OVERRIDE
{}
55 virtual bool NeedsFlush() OVERRIDE
{ return false; }
56 virtual void Flush(const base::Callback
<void(bool)>& callback
) OVERRIDE
{
59 virtual bool FromV8Value(v8::Handle
<v8::Object
> val
,
60 v8::Handle
<v8::Context
> context
,
62 bool* was_resource
) OVERRIDE
{
63 *was_resource
= false;
66 virtual bool ToV8Value(const PP_Var
& var
,
67 v8::Handle
<v8::Context
> context
,
68 v8::Handle
<v8::Value
>* result
) OVERRIDE
{
73 // Maps PP_Var IDs to the V8 value handle they correspond to.
74 typedef base::hash_map
<int64_t, v8::Handle
<v8::Value
> > VarHandleMap
;
76 bool Equals(const PP_Var
& var
,
77 v8::Handle
<v8::Value
> val
,
78 VarHandleMap
* visited_ids
) {
79 if (ppapi::VarTracker::IsVarTypeRefcounted(var
.type
)) {
80 VarHandleMap::iterator it
= visited_ids
->find(var
.value
.as_id
);
81 if (it
!= visited_ids
->end())
82 return it
->second
== val
;
83 (*visited_ids
)[var
.value
.as_id
] = val
;
86 if (val
->IsUndefined()) {
87 return var
.type
== PP_VARTYPE_UNDEFINED
;
88 } else if (val
->IsNull()) {
89 return var
.type
== PP_VARTYPE_NULL
;
90 } else if (val
->IsBoolean() || val
->IsBooleanObject()) {
91 return var
.type
== PP_VARTYPE_BOOL
&&
92 PP_FromBool(val
->ToBoolean()->Value()) == var
.value
.as_bool
;
93 } else if (val
->IsInt32()) {
94 return var
.type
== PP_VARTYPE_INT32
&&
95 val
->ToInt32()->Value() == var
.value
.as_int
;
96 } else if (val
->IsNumber() || val
->IsNumberObject()) {
97 return var
.type
== PP_VARTYPE_DOUBLE
&&
98 fabs(val
->ToNumber()->Value() - var
.value
.as_double
) <= 1.0e-4;
99 } else if (val
->IsString() || val
->IsStringObject()) {
100 if (var
.type
!= PP_VARTYPE_STRING
)
102 StringVar
* string_var
= StringVar::FromPPVar(var
);
104 v8::String::Utf8Value
utf8(val
->ToString());
105 return std::string(*utf8
, utf8
.length()) == string_var
->value();
106 } else if (val
->IsArray()) {
107 if (var
.type
!= PP_VARTYPE_ARRAY
)
109 ArrayVar
* array_var
= ArrayVar::FromPPVar(var
);
111 v8::Handle
<v8::Array
> v8_array
= val
.As
<v8::Array
>();
112 if (v8_array
->Length() != array_var
->elements().size())
114 for (uint32 i
= 0; i
< v8_array
->Length(); ++i
) {
115 v8::Handle
<v8::Value
> child_v8
= v8_array
->Get(i
);
116 if (!Equals(array_var
->elements()[i
].get(), child_v8
, visited_ids
))
120 } else if (val
->IsObject()) {
121 if (var
.type
== PP_VARTYPE_ARRAY_BUFFER
) {
122 // TODO(raymes): Implement this when we have tests for array buffers.
126 v8::Handle
<v8::Object
> v8_object
= val
->ToObject();
127 if (var
.type
!= PP_VARTYPE_DICTIONARY
)
129 DictionaryVar
* dict_var
= DictionaryVar::FromPPVar(var
);
131 v8::Handle
<v8::Array
> property_names(v8_object
->GetOwnPropertyNames());
132 if (property_names
->Length() != dict_var
->key_value_map().size())
134 for (uint32 i
= 0; i
< property_names
->Length(); ++i
) {
135 v8::Handle
<v8::Value
> key(property_names
->Get(i
));
137 if (!key
->IsString() && !key
->IsNumber())
139 v8::Handle
<v8::Value
> child_v8
= v8_object
->Get(key
);
141 v8::String::Utf8Value
name_utf8(key
->ToString());
142 ScopedPPVar
release_key(ScopedPPVar::PassRef(),
143 StringVar::StringToPPVar(std::string(
144 *name_utf8
, name_utf8
.length())));
145 if (!dict_var
->HasKey(release_key
.get()))
147 ScopedPPVar
release_value(ScopedPPVar::PassRef(),
148 dict_var
->Get(release_key
.get()));
149 if (!Equals(release_value
.get(), child_v8
, visited_ids
))
158 bool Equals(const PP_Var
& var
, v8::Handle
<v8::Value
> val
) {
159 VarHandleMap var_handle_map
;
160 return Equals(var
, val
, &var_handle_map
);
163 class V8VarConverterTest
: public testing::Test
{
166 : isolate_(v8::Isolate::GetCurrent()) {
167 PP_Instance dummy
= 1234;
168 converter_
.reset(new V8VarConverter(
170 scoped_ptr
<ResourceConverter
>(new MockResourceConverter
).Pass()));
172 virtual ~V8VarConverterTest() {}
174 // testing::Test implementation.
175 virtual void SetUp() {
176 ProxyLock::Acquire();
177 v8::HandleScope
handle_scope(isolate_
);
178 v8::Handle
<v8::ObjectTemplate
> global
= v8::ObjectTemplate::New(isolate_
);
179 context_
.Reset(isolate_
, v8::Context::New(isolate_
, NULL
, global
));
181 virtual void TearDown() {
183 ASSERT_TRUE(PpapiGlobals::Get()->GetVarTracker()->GetLiveVars().empty());
184 ProxyLock::Release();
188 bool FromV8ValueSync(v8::Handle
<v8::Value
> val
,
189 v8::Handle
<v8::Context
> context
,
191 V8VarConverter::VarResult conversion_result
=
192 converter_
->FromV8Value(val
,
194 base::Bind(&FromV8ValueComplete
));
195 DCHECK(conversion_result
.completed_synchronously
);
196 if (conversion_result
.success
)
197 *result
= conversion_result
.var
.Release();
199 return conversion_result
.success
;
202 bool RoundTrip(const PP_Var
& var
, PP_Var
* result
) {
203 v8::HandleScope
handle_scope(isolate_
);
204 v8::Local
<v8::Context
> context
=
205 v8::Local
<v8::Context
>::New(isolate_
, context_
);
206 v8::Context::Scope
context_scope(context
);
207 v8::Handle
<v8::Value
> v8_result
;
208 if (!converter_
->ToV8Value(var
, context
, &v8_result
))
210 if (!Equals(var
, v8_result
))
212 if (!FromV8ValueSync(v8_result
, context
, result
))
217 // Assumes a ref for var.
218 bool RoundTripAndCompare(const PP_Var
& var
) {
219 ScopedPPVar
expected(ScopedPPVar::PassRef(), var
);
221 if (!RoundTrip(expected
.get(), &actual_var
))
223 ScopedPPVar
actual(ScopedPPVar::PassRef(), actual_var
);
224 return TestEqual(expected
.get(), actual
.get(), false);
227 v8::Isolate
* isolate_
;
229 // Context for the JavaScript in the test.
230 v8::Persistent
<v8::Context
> context_
;
232 scoped_ptr
<V8VarConverter
> converter_
;
235 TestGlobals globals_
;
237 base::MessageLoop message_loop_
;
242 TEST_F(V8VarConverterTest
, SimpleRoundTripTest
) {
243 EXPECT_TRUE(RoundTripAndCompare(PP_MakeUndefined()));
244 EXPECT_TRUE(RoundTripAndCompare(PP_MakeNull()));
245 EXPECT_TRUE(RoundTripAndCompare(PP_MakeInt32(100)));
246 EXPECT_TRUE(RoundTripAndCompare(PP_MakeBool(PP_TRUE
)));
247 EXPECT_TRUE(RoundTripAndCompare(PP_MakeDouble(53.75)));
250 TEST_F(V8VarConverterTest
, StringRoundTripTest
) {
251 EXPECT_TRUE(RoundTripAndCompare(StringVar::StringToPPVar("")));
252 EXPECT_TRUE(RoundTripAndCompare(StringVar::StringToPPVar("hello world!")));
255 TEST_F(V8VarConverterTest
, ArrayBufferRoundTripTest
) {
256 // TODO(raymes): Testing this here requires spinning up some of WebKit.
257 // Work out how to do this.
260 TEST_F(V8VarConverterTest
, DictionaryArrayRoundTripTest
) {
262 scoped_refptr
<ArrayVar
> array(new ArrayVar
);
263 ScopedPPVar
release_array(ScopedPPVar::PassRef(), array
->GetPPVar());
264 EXPECT_TRUE(RoundTripAndCompare(array
->GetPPVar()));
268 // Array with primitives.
269 array
->Set(index
++, PP_MakeUndefined());
270 array
->Set(index
++, PP_MakeNull());
271 array
->Set(index
++, PP_MakeInt32(100));
272 array
->Set(index
++, PP_MakeBool(PP_FALSE
));
273 array
->Set(index
++, PP_MakeDouble(0.123));
274 EXPECT_TRUE(RoundTripAndCompare(array
->GetPPVar()));
276 // Array with 2 references to the same string.
277 ScopedPPVar
release_string(ScopedPPVar::PassRef(),
278 StringVar::StringToPPVar("abc"));
279 array
->Set(index
++, release_string
.get());
280 array
->Set(index
++, release_string
.get());
281 EXPECT_TRUE(RoundTripAndCompare(array
->GetPPVar()));
283 // Array with nested array that references the same string.
284 scoped_refptr
<ArrayVar
> array2(new ArrayVar
);
285 ScopedPPVar
release_array2(ScopedPPVar::PassRef(), array2
->GetPPVar());
286 array2
->Set(0, release_string
.get());
287 array
->Set(index
++, release_array2
.get());
288 EXPECT_TRUE(RoundTripAndCompare(array
->GetPPVar()));
291 scoped_refptr
<DictionaryVar
> dictionary(new DictionaryVar
);
292 ScopedPPVar
release_dictionary(ScopedPPVar::PassRef(),
293 dictionary
->GetPPVar());
294 EXPECT_TRUE(RoundTripAndCompare(dictionary
->GetPPVar()));
296 // Dictionary with primitives.
297 dictionary
->SetWithStringKey("1", PP_MakeUndefined());
298 dictionary
->SetWithStringKey("2", PP_MakeNull());
299 dictionary
->SetWithStringKey("3", PP_MakeInt32(-100));
300 dictionary
->SetWithStringKey("4", PP_MakeBool(PP_TRUE
));
301 dictionary
->SetWithStringKey("5", PP_MakeDouble(-103.52));
302 EXPECT_TRUE(RoundTripAndCompare(dictionary
->GetPPVar()));
304 // Dictionary with 2 references to the same string.
305 dictionary
->SetWithStringKey("6", release_string
.get());
306 dictionary
->SetWithStringKey("7", release_string
.get());
307 EXPECT_TRUE(RoundTripAndCompare(dictionary
->GetPPVar()));
309 // Dictionary with nested dictionary that references the same string.
310 scoped_refptr
<DictionaryVar
> dictionary2(new DictionaryVar
);
311 ScopedPPVar
release_dictionary2(ScopedPPVar::PassRef(),
312 dictionary2
->GetPPVar());
313 dictionary2
->SetWithStringKey("abc", release_string
.get());
314 dictionary
->SetWithStringKey("8", release_dictionary2
.get());
315 EXPECT_TRUE(RoundTripAndCompare(dictionary
->GetPPVar()));
317 // Array with dictionary.
318 array
->Set(index
++, release_dictionary
.get());
319 EXPECT_TRUE(RoundTripAndCompare(array
->GetPPVar()));
321 // Array with dictionary with array.
322 array2
->Set(0, PP_MakeInt32(100));
323 dictionary
->SetWithStringKey("9", release_array2
.get());
324 EXPECT_TRUE(RoundTripAndCompare(array
->GetPPVar()));
327 TEST_F(V8VarConverterTest
, Cycles
) {
328 // Check that cycles aren't converted.
329 v8::HandleScope
handle_scope(isolate_
);
330 v8::Local
<v8::Context
> context
=
331 v8::Local
<v8::Context
>::New(isolate_
, context_
);
332 v8::Context::Scope
context_scope(context
);
334 // Var->V8 conversion.
336 scoped_refptr
<DictionaryVar
> dictionary(new DictionaryVar
);
337 ScopedPPVar
release_dictionary(ScopedPPVar::PassRef(),
338 dictionary
->GetPPVar());
339 scoped_refptr
<ArrayVar
> array(new ArrayVar
);
340 ScopedPPVar
release_array(ScopedPPVar::PassRef(), array
->GetPPVar());
342 dictionary
->SetWithStringKey("1", release_array
.get());
343 array
->Set(0, release_dictionary
.get());
345 v8::Handle
<v8::Value
> v8_result
;
347 // Array <-> dictionary cycle.
348 dictionary
->SetWithStringKey("1", release_array
.get());
350 converter_
->ToV8Value(release_dictionary
.get(), context
, &v8_result
));
352 // TODO(raymes): We need some better machinery for releasing vars with
353 // cycles. Remove the code below once we have that.
354 dictionary
->DeleteWithStringKey("1");
356 // Array with self reference.
357 array
->Set(0, release_array
.get());
359 converter_
->ToV8Value(release_array
.get(), context
, &v8_result
));
360 // Break the self reference.
361 array
->Set(0, PP_MakeUndefined());
364 // V8->Var conversion.
366 v8::Handle
<v8::Object
> object
= v8::Object::New(isolate_
);
367 v8::Handle
<v8::Array
> array
= v8::Array::New(isolate_
);
371 // Array <-> dictionary cycle.
372 std::string key
= "1";
374 v8::String::NewFromUtf8(
375 isolate_
, key
.c_str(), v8::String::kNormalString
, key
.length()),
377 array
->Set(0, object
);
379 ASSERT_FALSE(FromV8ValueSync(object
, context
, &var_result
));
381 // Array with self reference.
382 array
->Set(0, array
);
383 ASSERT_FALSE(FromV8ValueSync(array
, context
, &var_result
));
387 TEST_F(V8VarConverterTest
, StrangeDictionaryKeyTest
) {
389 // Test keys with '.'.
390 scoped_refptr
<DictionaryVar
> dictionary(new DictionaryVar
);
391 dictionary
->SetWithStringKey(".", PP_MakeUndefined());
392 dictionary
->SetWithStringKey("x.y", PP_MakeUndefined());
393 EXPECT_TRUE(RoundTripAndCompare(dictionary
->GetPPVar()));
397 // Test non-string key types. They should be cast to strings.
398 v8::HandleScope
handle_scope(isolate_
);
399 v8::Local
<v8::Context
> context
=
400 v8::Local
<v8::Context
>::New(isolate_
, context_
);
401 v8::Context::Scope
context_scope(context
);
415 v8::Handle
<v8::Script
> script(
416 v8::Script::Compile(v8::String::NewFromUtf8(isolate_
, source
)));
417 v8::Handle
<v8::Object
> object
= script
->Run().As
<v8::Object
>();
418 ASSERT_FALSE(object
.IsEmpty());
421 ASSERT_TRUE(FromV8ValueSync(
422 object
, v8::Local
<v8::Context
>::New(isolate_
, context_
), &actual
));
423 ScopedPPVar
release_actual(ScopedPPVar::PassRef(), actual
);
425 scoped_refptr
<DictionaryVar
> expected(new DictionaryVar
);
426 ScopedPPVar
foo(ScopedPPVar::PassRef(), StringVar::StringToPPVar("foo"));
427 expected
->SetWithStringKey("1", foo
.get());
428 ScopedPPVar
bar(ScopedPPVar::PassRef(), StringVar::StringToPPVar("bar"));
429 expected
->SetWithStringKey("2", bar
.get());
430 ScopedPPVar
baz(ScopedPPVar::PassRef(), StringVar::StringToPPVar("baz"));
431 expected
->SetWithStringKey("true", baz
.get());
432 ScopedPPVar
qux(ScopedPPVar::PassRef(), StringVar::StringToPPVar("qux"));
433 expected
->SetWithStringKey("false", qux
.get());
434 ScopedPPVar
quux(ScopedPPVar::PassRef(), StringVar::StringToPPVar("quux"));
435 expected
->SetWithStringKey("null", quux
.get());
436 ScopedPPVar
oops(ScopedPPVar::PassRef(), StringVar::StringToPPVar("oops"));
437 expected
->SetWithStringKey("undefined", oops
.get());
438 ScopedPPVar
release_expected(ScopedPPVar::PassRef(), expected
->GetPPVar());
440 ASSERT_TRUE(TestEqual(release_expected
.get(), release_actual
.get(), true));
444 } // namespace content