- add sources.
[platform/framework/web/crosswalk.git] / src / content / renderer / v8_value_converter_impl.cc
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/v8_value_converter_impl.h"
6
7 #include <string>
8
9 #include "base/float_util.h"
10 #include "base/logging.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/values.h"
13 #include "third_party/WebKit/public/platform/WebArrayBuffer.h"
14 #include "third_party/WebKit/public/web/WebArrayBufferView.h"
15 #include "v8/include/v8.h"
16
17 namespace content {
18
19 namespace {
20
21 // For the sake of the storage API, make this quite large.
22 const int kMaxRecursionDepth = 100;
23
24 }  // namespace
25
26 // The state of a call to FromV8Value.
27 class V8ValueConverterImpl::FromV8ValueState {
28  public:
29   // Level scope which updates the current depth of some FromV8ValueState.
30   class Level {
31    public:
32     explicit Level(FromV8ValueState* state) : state_(state) {
33       state_->max_recursion_depth_--;
34     }
35     ~Level() {
36       state_->max_recursion_depth_++;
37     }
38
39    private:
40     FromV8ValueState* state_;
41   };
42
43   explicit FromV8ValueState(bool avoid_identity_hash_for_testing)
44       : max_recursion_depth_(kMaxRecursionDepth),
45         avoid_identity_hash_for_testing_(avoid_identity_hash_for_testing) {}
46
47   // If |handle| is not in |unique_map_|, then add it to |unique_map_| and
48   // return true.
49   //
50   // Otherwise do nothing and return false. Here "A is unique" means that no
51   // other handle B in the map points to the same object as A. Note that A can
52   // be unique even if there already is another handle with the same identity
53   // hash (key) in the map, because two objects can have the same hash.
54   bool UpdateAndCheckUniqueness(v8::Handle<v8::Object> handle) {
55     typedef HashToHandleMap::const_iterator Iterator;
56     int hash = avoid_identity_hash_for_testing_ ? 0 : handle->GetIdentityHash();
57     // We only compare using == with handles to objects with the same identity
58     // hash. Different hash obviously means different objects, but two objects
59     // in a couple of thousands could have the same identity hash.
60     std::pair<Iterator, Iterator> range = unique_map_.equal_range(hash);
61     for (Iterator it = range.first; it != range.second; ++it) {
62       // Operator == for handles actually compares the underlying objects.
63       if (it->second == handle)
64         return false;
65     }
66     unique_map_.insert(std::make_pair(hash, handle));
67     return true;
68   }
69
70   bool HasReachedMaxRecursionDepth() {
71     return max_recursion_depth_ < 0;
72   }
73
74  private:
75   typedef std::multimap<int, v8::Handle<v8::Object> > HashToHandleMap;
76   HashToHandleMap unique_map_;
77
78   int max_recursion_depth_;
79
80   bool avoid_identity_hash_for_testing_;
81 };
82
83 V8ValueConverter* V8ValueConverter::create() {
84   return new V8ValueConverterImpl();
85 }
86
87 V8ValueConverterImpl::V8ValueConverterImpl()
88     : date_allowed_(false),
89       reg_exp_allowed_(false),
90       function_allowed_(false),
91       strip_null_from_objects_(false),
92       avoid_identity_hash_for_testing_(false),
93       strategy_(NULL) {}
94
95 void V8ValueConverterImpl::SetDateAllowed(bool val) {
96   date_allowed_ = val;
97 }
98
99 void V8ValueConverterImpl::SetRegExpAllowed(bool val) {
100   reg_exp_allowed_ = val;
101 }
102
103 void V8ValueConverterImpl::SetFunctionAllowed(bool val) {
104   function_allowed_ = val;
105 }
106
107 void V8ValueConverterImpl::SetStripNullFromObjects(bool val) {
108   strip_null_from_objects_ = val;
109 }
110
111 void V8ValueConverterImpl::SetStrategy(Strategy* strategy) {
112   strategy_ = strategy;
113 }
114
115 v8::Handle<v8::Value> V8ValueConverterImpl::ToV8Value(
116     const base::Value* value, v8::Handle<v8::Context> context) const {
117   v8::Context::Scope context_scope(context);
118   v8::HandleScope handle_scope(context->GetIsolate());
119   return handle_scope.Close(ToV8ValueImpl(value));
120 }
121
122 Value* V8ValueConverterImpl::FromV8Value(
123     v8::Handle<v8::Value> val,
124     v8::Handle<v8::Context> context) const {
125   v8::Context::Scope context_scope(context);
126   v8::HandleScope handle_scope(context->GetIsolate());
127   FromV8ValueState state(avoid_identity_hash_for_testing_);
128   return FromV8ValueImpl(val, &state);
129 }
130
131 v8::Handle<v8::Value> V8ValueConverterImpl::ToV8ValueImpl(
132      const base::Value* value) const {
133   CHECK(value);
134   switch (value->GetType()) {
135     case base::Value::TYPE_NULL:
136       return v8::Null();
137
138     case base::Value::TYPE_BOOLEAN: {
139       bool val = false;
140       CHECK(value->GetAsBoolean(&val));
141       return v8::Boolean::New(val);
142     }
143
144     case base::Value::TYPE_INTEGER: {
145       int val = 0;
146       CHECK(value->GetAsInteger(&val));
147       return v8::Integer::New(val);
148     }
149
150     case base::Value::TYPE_DOUBLE: {
151       double val = 0.0;
152       CHECK(value->GetAsDouble(&val));
153       return v8::Number::New(val);
154     }
155
156     case base::Value::TYPE_STRING: {
157       std::string val;
158       CHECK(value->GetAsString(&val));
159       return v8::String::New(val.c_str(), val.length());
160     }
161
162     case base::Value::TYPE_LIST:
163       return ToV8Array(static_cast<const base::ListValue*>(value));
164
165     case base::Value::TYPE_DICTIONARY:
166       return ToV8Object(static_cast<const base::DictionaryValue*>(value));
167
168     case base::Value::TYPE_BINARY:
169       return ToArrayBuffer(static_cast<const base::BinaryValue*>(value));
170
171     default:
172       LOG(ERROR) << "Unexpected value type: " << value->GetType();
173       return v8::Null();
174   }
175 }
176
177 v8::Handle<v8::Value> V8ValueConverterImpl::ToV8Array(
178     const base::ListValue* val) const {
179   v8::Handle<v8::Array> result(v8::Array::New(val->GetSize()));
180
181   for (size_t i = 0; i < val->GetSize(); ++i) {
182     const base::Value* child = NULL;
183     CHECK(val->Get(i, &child));
184
185     v8::Handle<v8::Value> child_v8 = ToV8ValueImpl(child);
186     CHECK(!child_v8.IsEmpty());
187
188     v8::TryCatch try_catch;
189     result->Set(static_cast<uint32>(i), child_v8);
190     if (try_catch.HasCaught())
191       LOG(ERROR) << "Setter for index " << i << " threw an exception.";
192   }
193
194   return result;
195 }
196
197 v8::Handle<v8::Value> V8ValueConverterImpl::ToV8Object(
198     const base::DictionaryValue* val) const {
199   v8::Handle<v8::Object> result(v8::Object::New());
200
201   for (base::DictionaryValue::Iterator iter(*val);
202        !iter.IsAtEnd(); iter.Advance()) {
203     const std::string& key = iter.key();
204     v8::Handle<v8::Value> child_v8 = ToV8ValueImpl(&iter.value());
205     CHECK(!child_v8.IsEmpty());
206
207     v8::TryCatch try_catch;
208     result->Set(v8::String::New(key.c_str(), key.length()), child_v8);
209     if (try_catch.HasCaught()) {
210       LOG(ERROR) << "Setter for property " << key.c_str() << " threw an "
211                  << "exception.";
212     }
213   }
214
215   return result;
216 }
217
218 v8::Handle<v8::Value> V8ValueConverterImpl::ToArrayBuffer(
219     const base::BinaryValue* value) const {
220   WebKit::WebArrayBuffer buffer =
221       WebKit::WebArrayBuffer::create(value->GetSize(), 1);
222   memcpy(buffer.data(), value->GetBuffer(), value->GetSize());
223   return buffer.toV8Value();
224 }
225
226 Value* V8ValueConverterImpl::FromV8ValueImpl(
227     v8::Handle<v8::Value> val,
228     FromV8ValueState* state) const {
229   CHECK(!val.IsEmpty());
230
231   FromV8ValueState::Level state_level(state);
232   if (state->HasReachedMaxRecursionDepth())
233     return NULL;
234
235   if (val->IsNull())
236     return base::Value::CreateNullValue();
237
238   if (val->IsBoolean())
239     return new base::FundamentalValue(val->ToBoolean()->Value());
240
241   if (val->IsInt32())
242     return new base::FundamentalValue(val->ToInt32()->Value());
243
244   if (val->IsNumber()) {
245     double val_as_double = val->ToNumber()->Value();
246     if (!base::IsFinite(val_as_double))
247       return NULL;
248     return new base::FundamentalValue(val_as_double);
249   }
250
251   if (val->IsString()) {
252     v8::String::Utf8Value utf8(val->ToString());
253     return new base::StringValue(std::string(*utf8, utf8.length()));
254   }
255
256   if (val->IsUndefined())
257     // JSON.stringify ignores undefined.
258     return NULL;
259
260   if (val->IsDate()) {
261     if (!date_allowed_)
262       // JSON.stringify would convert this to a string, but an object is more
263       // consistent within this class.
264       return FromV8Object(val->ToObject(), state);
265     v8::Date* date = v8::Date::Cast(*val);
266     return new base::FundamentalValue(date->NumberValue() / 1000.0);
267   }
268
269   if (val->IsRegExp()) {
270     if (!reg_exp_allowed_)
271       // JSON.stringify converts to an object.
272       return FromV8Object(val->ToObject(), state);
273     return new base::StringValue(*v8::String::Utf8Value(val->ToString()));
274   }
275
276   // v8::Value doesn't have a ToArray() method for some reason.
277   if (val->IsArray())
278     return FromV8Array(val.As<v8::Array>(), state);
279
280   if (val->IsFunction()) {
281     if (!function_allowed_)
282       // JSON.stringify refuses to convert function(){}.
283       return NULL;
284     return FromV8Object(val->ToObject(), state);
285   }
286
287   if (val->IsObject()) {
288     base::BinaryValue* binary_value = FromV8Buffer(val);
289     if (binary_value) {
290       return binary_value;
291     } else {
292       return FromV8Object(val->ToObject(), state);
293     }
294   }
295
296   LOG(ERROR) << "Unexpected v8 value type encountered.";
297   return NULL;
298 }
299
300 base::Value* V8ValueConverterImpl::FromV8Array(
301     v8::Handle<v8::Array> val,
302     FromV8ValueState* state) const {
303   if (!state->UpdateAndCheckUniqueness(val))
304     return base::Value::CreateNullValue();
305
306   scoped_ptr<v8::Context::Scope> scope;
307   // If val was created in a different context than our current one, change to
308   // that context, but change back after val is converted.
309   if (!val->CreationContext().IsEmpty() &&
310       val->CreationContext() != v8::Context::GetCurrent())
311     scope.reset(new v8::Context::Scope(val->CreationContext()));
312
313   if (strategy_) {
314     Value* out = NULL;
315     if (strategy_->FromV8Array(val, &out))
316       return out;
317   }
318
319   base::ListValue* result = new base::ListValue();
320
321   // Only fields with integer keys are carried over to the ListValue.
322   for (uint32 i = 0; i < val->Length(); ++i) {
323     v8::TryCatch try_catch;
324     v8::Handle<v8::Value> child_v8 = val->Get(i);
325     if (try_catch.HasCaught()) {
326       LOG(ERROR) << "Getter for index " << i << " threw an exception.";
327       child_v8 = v8::Null();
328     }
329
330     if (!val->HasRealIndexedProperty(i))
331       continue;
332
333     base::Value* child = FromV8ValueImpl(child_v8, state);
334     if (child)
335       result->Append(child);
336     else
337       // JSON.stringify puts null in places where values don't serialize, for
338       // example undefined and functions. Emulate that behavior.
339       result->Append(base::Value::CreateNullValue());
340   }
341   return result;
342 }
343
344 base::BinaryValue* V8ValueConverterImpl::FromV8Buffer(
345     v8::Handle<v8::Value> val) const {
346   char* data = NULL;
347   size_t length = 0;
348
349   scoped_ptr<WebKit::WebArrayBuffer> array_buffer(
350       WebKit::WebArrayBuffer::createFromV8Value(val));
351   scoped_ptr<WebKit::WebArrayBufferView> view;
352   if (array_buffer) {
353     data = reinterpret_cast<char*>(array_buffer->data());
354     length = array_buffer->byteLength();
355   } else {
356     view.reset(WebKit::WebArrayBufferView::createFromV8Value(val));
357     if (view) {
358       data = reinterpret_cast<char*>(view->baseAddress()) + view->byteOffset();
359       length = view->byteLength();
360     }
361   }
362
363   if (data)
364     return base::BinaryValue::CreateWithCopiedBuffer(data, length);
365   else
366     return NULL;
367 }
368
369 base::Value* V8ValueConverterImpl::FromV8Object(
370     v8::Handle<v8::Object> val,
371     FromV8ValueState* state) const {
372   if (!state->UpdateAndCheckUniqueness(val))
373     return base::Value::CreateNullValue();
374
375   scoped_ptr<v8::Context::Scope> scope;
376   // If val was created in a different context than our current one, change to
377   // that context, but change back after val is converted.
378   if (!val->CreationContext().IsEmpty() &&
379       val->CreationContext() != v8::Context::GetCurrent())
380     scope.reset(new v8::Context::Scope(val->CreationContext()));
381
382   if (strategy_) {
383     Value* out = NULL;
384     if (strategy_->FromV8Object(val, &out))
385       return out;
386   }
387
388   // Don't consider DOM objects. This check matches isHostObject() in Blink's
389   // bindings/v8/V8Binding.h used in structured cloning. It reads:
390   //
391   // If the object has any internal fields, then we won't be able to serialize
392   // or deserialize them; conveniently, this is also a quick way to detect DOM
393   // wrapper objects, because the mechanism for these relies on data stored in
394   // these fields.
395   //
396   // NOTE: check this after |strategy_| so that callers have a chance to
397   // do something else, such as convert to the node's name rather than NULL.
398   if (val->InternalFieldCount())
399     return NULL;
400
401   scoped_ptr<base::DictionaryValue> result(new base::DictionaryValue());
402   v8::Handle<v8::Array> property_names(val->GetOwnPropertyNames());
403
404   for (uint32 i = 0; i < property_names->Length(); ++i) {
405     v8::Handle<v8::Value> key(property_names->Get(i));
406
407     // Extend this test to cover more types as necessary and if sensible.
408     if (!key->IsString() &&
409         !key->IsNumber()) {
410       NOTREACHED() << "Key \"" << *v8::String::AsciiValue(key) << "\" "
411                       "is neither a string nor a number";
412       continue;
413     }
414
415     v8::String::Utf8Value name_utf8(key->ToString());
416
417     v8::TryCatch try_catch;
418     v8::Handle<v8::Value> child_v8 = val->Get(key);
419
420     if (try_catch.HasCaught()) {
421       LOG(WARNING) << "Getter for property " << *name_utf8
422                    << " threw an exception.";
423       child_v8 = v8::Null();
424     }
425
426     scoped_ptr<base::Value> child(FromV8ValueImpl(child_v8, state));
427     if (!child)
428       // JSON.stringify skips properties whose values don't serialize, for
429       // example undefined and functions. Emulate that behavior.
430       continue;
431
432     // Strip null if asked (and since undefined is turned into null, undefined
433     // too). The use case for supporting this is JSON-schema support,
434     // specifically for extensions, where "optional" JSON properties may be
435     // represented as null, yet due to buggy legacy code elsewhere isn't
436     // treated as such (potentially causing crashes). For example, the
437     // "tabs.create" function takes an object as its first argument with an
438     // optional "windowId" property.
439     //
440     // Given just
441     //
442     //   tabs.create({})
443     //
444     // this will work as expected on code that only checks for the existence of
445     // a "windowId" property (such as that legacy code). However given
446     //
447     //   tabs.create({windowId: null})
448     //
449     // there *is* a "windowId" property, but since it should be an int, code
450     // on the browser which doesn't additionally check for null will fail.
451     // We can avoid all bugs related to this by stripping null.
452     if (strip_null_from_objects_ && child->IsType(base::Value::TYPE_NULL))
453       continue;
454
455     result->SetWithoutPathExpansion(std::string(*name_utf8, name_utf8.length()),
456                                     child.release());
457   }
458
459   return result.release();
460 }
461
462 }  // namespace content