Home | History | Annotate | Download | only in pepper
      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.
      4 
      5 #include "content/renderer/pepper/v8_var_converter.h"
      6 
      7 #include <cmath>
      8 
      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"
     30 
     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;
     41 
     42 namespace content {
     43 
     44 namespace {
     45 
     46 void FromV8ValueComplete(const ScopedPPVar& scoped_var,
     47                          bool success) {
     48   NOTREACHED();
     49 }
     50 
     51 class MockResourceConverter : public content::ResourceConverter {
     52  public:
     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 {
     57     NOTREACHED();
     58   }
     59   virtual bool FromV8Value(v8::Handle<v8::Object> val,
     60                            v8::Handle<v8::Context> context,
     61                            PP_Var* result,
     62                            bool* was_resource) OVERRIDE {
     63     *was_resource = false;
     64     return true;
     65   }
     66   virtual bool ToV8Value(const PP_Var& var,
     67                          v8::Handle<v8::Context> context,
     68                          v8::Handle<v8::Value>* result) OVERRIDE {
     69     return false;
     70   }
     71 };
     72 
     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;
     75 
     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;
     84   }
     85 
     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)
    101       return false;
    102     StringVar* string_var = StringVar::FromPPVar(var);
    103     DCHECK(string_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)
    108       return false;
    109     ArrayVar* array_var = ArrayVar::FromPPVar(var);
    110     DCHECK(array_var);
    111     v8::Handle<v8::Array> v8_array = val.As<v8::Array>();
    112     if (v8_array->Length() != array_var->elements().size())
    113       return false;
    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))
    117         return false;
    118     }
    119     return true;
    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.
    123       NOTIMPLEMENTED();
    124       return false;
    125     } else {
    126       v8::Handle<v8::Object> v8_object = val->ToObject();
    127       if (var.type != PP_VARTYPE_DICTIONARY)
    128         return false;
    129       DictionaryVar* dict_var = DictionaryVar::FromPPVar(var);
    130       DCHECK(dict_var);
    131       v8::Handle<v8::Array> property_names(v8_object->GetOwnPropertyNames());
    132       if (property_names->Length() != dict_var->key_value_map().size())
    133         return false;
    134       for (uint32 i = 0; i < property_names->Length(); ++i) {
    135         v8::Handle<v8::Value> key(property_names->Get(i));
    136 
    137         if (!key->IsString() && !key->IsNumber())
    138           return false;
    139         v8::Handle<v8::Value> child_v8 = v8_object->Get(key);
    140 
    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()))
    146           return false;
    147         ScopedPPVar release_value(ScopedPPVar::PassRef(),
    148                                   dict_var->Get(release_key.get()));
    149         if (!Equals(release_value.get(), child_v8, visited_ids))
    150           return false;
    151       }
    152       return true;
    153     }
    154   }
    155   return false;
    156 }
    157 
    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);
    161 }
    162 
    163 class V8VarConverterTest : public testing::Test {
    164  public:
    165   V8VarConverterTest()
    166       : isolate_(v8::Isolate::GetCurrent()) {
    167     PP_Instance dummy = 1234;
    168     converter_.reset(new V8VarConverter(
    169         dummy,
    170         scoped_ptr<ResourceConverter>(new MockResourceConverter).Pass()));
    171   }
    172   virtual ~V8VarConverterTest() {}
    173 
    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));
    180   }
    181   virtual void TearDown() {
    182     context_.Reset();
    183     ASSERT_TRUE(PpapiGlobals::Get()->GetVarTracker()->GetLiveVars().empty());
    184     ProxyLock::Release();
    185   }
    186 
    187  protected:
    188   bool FromV8ValueSync(v8::Handle<v8::Value> val,
    189                        v8::Handle<v8::Context> context,
    190                        PP_Var* result) {
    191     V8VarConverter::VarResult conversion_result =
    192         converter_->FromV8Value(val,
    193                                 context,
    194                                 base::Bind(&FromV8ValueComplete));
    195     DCHECK(conversion_result.completed_synchronously);
    196     if (conversion_result.success)
    197       *result = conversion_result.var.Release();
    198 
    199     return conversion_result.success;
    200   }
    201 
    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))
    209       return false;
    210     if (!Equals(var, v8_result))
    211       return false;
    212     if (!FromV8ValueSync(v8_result, context, result))
    213       return false;
    214     return true;
    215   }
    216 
    217   // Assumes a ref for var.
    218   bool RoundTripAndCompare(const PP_Var& var) {
    219     ScopedPPVar expected(ScopedPPVar::PassRef(), var);
    220     PP_Var actual_var;
    221     if (!RoundTrip(expected.get(), &actual_var))
    222       return false;
    223     ScopedPPVar actual(ScopedPPVar::PassRef(), actual_var);
    224     return TestEqual(expected.get(), actual.get(), false);
    225   }
    226 
    227   v8::Isolate* isolate_;
    228 
    229   // Context for the JavaScript in the test.
    230   v8::Persistent<v8::Context> context_;
    231 
    232   scoped_ptr<V8VarConverter> converter_;
    233 
    234  private:
    235   TestGlobals globals_;
    236 
    237   base::MessageLoop message_loop_;
    238 };
    239 
    240 }  // namespace
    241 
    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)));
    248 }
    249 
    250 TEST_F(V8VarConverterTest, StringRoundTripTest) {
    251   EXPECT_TRUE(RoundTripAndCompare(StringVar::StringToPPVar("")));
    252   EXPECT_TRUE(RoundTripAndCompare(StringVar::StringToPPVar("hello world!")));
    253 }
    254 
    255 TEST_F(V8VarConverterTest, ArrayBufferRoundTripTest) {
    256   // TODO(raymes): Testing this here requires spinning up some of WebKit.
    257   // Work out how to do this.
    258 }
    259 
    260 TEST_F(V8VarConverterTest, DictionaryArrayRoundTripTest) {
    261   // Empty array.
    262   scoped_refptr<ArrayVar> array(new ArrayVar);
    263   ScopedPPVar release_array(ScopedPPVar::PassRef(), array->GetPPVar());
    264   EXPECT_TRUE(RoundTripAndCompare(array->GetPPVar()));
    265 
    266   size_t index = 0;
    267 
    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()));
    275 
    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()));
    282 
    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()));
    289 
    290   // Empty dictionary.
    291   scoped_refptr<DictionaryVar> dictionary(new DictionaryVar);
    292   ScopedPPVar release_dictionary(ScopedPPVar::PassRef(),
    293                                  dictionary->GetPPVar());
    294   EXPECT_TRUE(RoundTripAndCompare(dictionary->GetPPVar()));
    295 
    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()));
    303 
    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()));
    308 
    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()));
    316 
    317   // Array with dictionary.
    318   array->Set(index++, release_dictionary.get());
    319   EXPECT_TRUE(RoundTripAndCompare(array->GetPPVar()));
    320 
    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()));
    325 }
    326 
    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);
    333 
    334   // Var->V8 conversion.
    335   {
    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());
    341 
    342     dictionary->SetWithStringKey("1", release_array.get());
    343     array->Set(0, release_dictionary.get());
    344 
    345     v8::Handle<v8::Value> v8_result;
    346 
    347     // Array <-> dictionary cycle.
    348     dictionary->SetWithStringKey("1", release_array.get());
    349     ASSERT_FALSE(
    350         converter_->ToV8Value(release_dictionary.get(), context, &v8_result));
    351     // Break the cycle.
    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");
    355 
    356     // Array with self reference.
    357     array->Set(0, release_array.get());
    358     ASSERT_FALSE(
    359         converter_->ToV8Value(release_array.get(), context, &v8_result));
    360     // Break the self reference.
    361     array->Set(0, PP_MakeUndefined());
    362   }
    363 
    364   // V8->Var conversion.
    365   {
    366     v8::Handle<v8::Object> object = v8::Object::New(isolate_);
    367     v8::Handle<v8::Array> array = v8::Array::New(isolate_);
    368 
    369     PP_Var var_result;
    370 
    371     // Array <-> dictionary cycle.
    372     std::string key = "1";
    373     object->Set(
    374         v8::String::NewFromUtf8(
    375             isolate_, key.c_str(), v8::String::kNormalString, key.length()),
    376         array);
    377     array->Set(0, object);
    378 
    379     ASSERT_FALSE(FromV8ValueSync(object, context, &var_result));
    380 
    381     // Array with self reference.
    382     array->Set(0, array);
    383     ASSERT_FALSE(FromV8ValueSync(array, context, &var_result));
    384   }
    385 }
    386 
    387 TEST_F(V8VarConverterTest, StrangeDictionaryKeyTest) {
    388   {
    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()));
    394   }
    395 
    396   {
    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);
    402 
    403     const char* source =
    404         "(function() {"
    405         "return {"
    406         "1: 'foo',"
    407         "'2': 'bar',"
    408         "true: 'baz',"
    409         "false: 'qux',"
    410         "null: 'quux',"
    411         "undefined: 'oops'"
    412         "};"
    413         "})();";
    414 
    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());
    419 
    420     PP_Var actual;
    421     ASSERT_TRUE(FromV8ValueSync(
    422         object, v8::Local<v8::Context>::New(isolate_, context_), &actual));
    423     ScopedPPVar release_actual(ScopedPPVar::PassRef(), actual);
    424 
    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());
    439 
    440     ASSERT_TRUE(TestEqual(release_expected.get(), release_actual.get(), true));
    441   }
    442 }
    443 
    444 }  // namespace content
    445