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/v8_value_converter_impl.h"
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"
21 // For the sake of the storage API, make this quite large.
22 const int kMaxRecursionDepth
= 100;
26 // The state of a call to FromV8Value.
27 class V8ValueConverterImpl::FromV8ValueState
{
29 // Level scope which updates the current depth of some FromV8ValueState.
32 explicit Level(FromV8ValueState
* state
) : state_(state
) {
33 state_
->max_recursion_depth_
--;
36 state_
->max_recursion_depth_
++;
40 FromV8ValueState
* state_
;
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
) {}
47 // If |handle| is not in |unique_map_|, then add it to |unique_map_| and
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
)
66 unique_map_
.insert(std::make_pair(hash
, handle
));
70 bool HasReachedMaxRecursionDepth() {
71 return max_recursion_depth_
< 0;
75 typedef std::multimap
<int, v8::Handle
<v8::Object
> > HashToHandleMap
;
76 HashToHandleMap unique_map_
;
78 int max_recursion_depth_
;
80 bool avoid_identity_hash_for_testing_
;
83 V8ValueConverter
* V8ValueConverter::create() {
84 return new V8ValueConverterImpl();
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),
95 void V8ValueConverterImpl::SetDateAllowed(bool val
) {
99 void V8ValueConverterImpl::SetRegExpAllowed(bool val
) {
100 reg_exp_allowed_
= val
;
103 void V8ValueConverterImpl::SetFunctionAllowed(bool val
) {
104 function_allowed_
= val
;
107 void V8ValueConverterImpl::SetStripNullFromObjects(bool val
) {
108 strip_null_from_objects_
= val
;
111 void V8ValueConverterImpl::SetStrategy(Strategy
* strategy
) {
112 strategy_
= strategy
;
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
));
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
);
131 v8::Handle
<v8::Value
> V8ValueConverterImpl::ToV8ValueImpl(
132 const base::Value
* value
) const {
134 switch (value
->GetType()) {
135 case base::Value::TYPE_NULL
:
138 case base::Value::TYPE_BOOLEAN
: {
140 CHECK(value
->GetAsBoolean(&val
));
141 return v8::Boolean::New(val
);
144 case base::Value::TYPE_INTEGER
: {
146 CHECK(value
->GetAsInteger(&val
));
147 return v8::Integer::New(val
);
150 case base::Value::TYPE_DOUBLE
: {
152 CHECK(value
->GetAsDouble(&val
));
153 return v8::Number::New(val
);
156 case base::Value::TYPE_STRING
: {
158 CHECK(value
->GetAsString(&val
));
159 return v8::String::New(val
.c_str(), val
.length());
162 case base::Value::TYPE_LIST
:
163 return ToV8Array(static_cast<const base::ListValue
*>(value
));
165 case base::Value::TYPE_DICTIONARY
:
166 return ToV8Object(static_cast<const base::DictionaryValue
*>(value
));
168 case base::Value::TYPE_BINARY
:
169 return ToArrayBuffer(static_cast<const base::BinaryValue
*>(value
));
172 LOG(ERROR
) << "Unexpected value type: " << value
->GetType();
177 v8::Handle
<v8::Value
> V8ValueConverterImpl::ToV8Array(
178 const base::ListValue
* val
) const {
179 v8::Handle
<v8::Array
> result(v8::Array::New(val
->GetSize()));
181 for (size_t i
= 0; i
< val
->GetSize(); ++i
) {
182 const base::Value
* child
= NULL
;
183 CHECK(val
->Get(i
, &child
));
185 v8::Handle
<v8::Value
> child_v8
= ToV8ValueImpl(child
);
186 CHECK(!child_v8
.IsEmpty());
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.";
197 v8::Handle
<v8::Value
> V8ValueConverterImpl::ToV8Object(
198 const base::DictionaryValue
* val
) const {
199 v8::Handle
<v8::Object
> result(v8::Object::New());
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());
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 "
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();
226 Value
* V8ValueConverterImpl::FromV8ValueImpl(
227 v8::Handle
<v8::Value
> val
,
228 FromV8ValueState
* state
) const {
229 CHECK(!val
.IsEmpty());
231 FromV8ValueState::Level
state_level(state
);
232 if (state
->HasReachedMaxRecursionDepth())
236 return base::Value::CreateNullValue();
238 if (val
->IsBoolean())
239 return new base::FundamentalValue(val
->ToBoolean()->Value());
242 return new base::FundamentalValue(val
->ToInt32()->Value());
244 if (val
->IsNumber()) {
245 double val_as_double
= val
->ToNumber()->Value();
246 if (!base::IsFinite(val_as_double
))
248 return new base::FundamentalValue(val_as_double
);
251 if (val
->IsString()) {
252 v8::String::Utf8Value
utf8(val
->ToString());
253 return new base::StringValue(std::string(*utf8
, utf8
.length()));
256 if (val
->IsUndefined())
257 // JSON.stringify ignores undefined.
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);
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()));
276 // v8::Value doesn't have a ToArray() method for some reason.
278 return FromV8Array(val
.As
<v8::Array
>(), state
);
280 if (val
->IsFunction()) {
281 if (!function_allowed_
)
282 // JSON.stringify refuses to convert function(){}.
284 return FromV8Object(val
->ToObject(), state
);
287 if (val
->IsObject()) {
288 base::BinaryValue
* binary_value
= FromV8Buffer(val
);
292 return FromV8Object(val
->ToObject(), state
);
296 LOG(ERROR
) << "Unexpected v8 value type encountered.";
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();
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()));
315 if (strategy_
->FromV8Array(val
, &out
))
319 base::ListValue
* result
= new base::ListValue();
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();
330 if (!val
->HasRealIndexedProperty(i
))
333 base::Value
* child
= FromV8ValueImpl(child_v8
, state
);
335 result
->Append(child
);
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());
344 base::BinaryValue
* V8ValueConverterImpl::FromV8Buffer(
345 v8::Handle
<v8::Value
> val
) const {
349 scoped_ptr
<WebKit::WebArrayBuffer
> array_buffer(
350 WebKit::WebArrayBuffer::createFromV8Value(val
));
351 scoped_ptr
<WebKit::WebArrayBufferView
> view
;
353 data
= reinterpret_cast<char*>(array_buffer
->data());
354 length
= array_buffer
->byteLength();
356 view
.reset(WebKit::WebArrayBufferView::createFromV8Value(val
));
358 data
= reinterpret_cast<char*>(view
->baseAddress()) + view
->byteOffset();
359 length
= view
->byteLength();
364 return base::BinaryValue::CreateWithCopiedBuffer(data
, length
);
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();
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()));
384 if (strategy_
->FromV8Object(val
, &out
))
388 // Don't consider DOM objects. This check matches isHostObject() in Blink's
389 // bindings/v8/V8Binding.h used in structured cloning. It reads:
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
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())
401 scoped_ptr
<base::DictionaryValue
> result(new base::DictionaryValue());
402 v8::Handle
<v8::Array
> property_names(val
->GetOwnPropertyNames());
404 for (uint32 i
= 0; i
< property_names
->Length(); ++i
) {
405 v8::Handle
<v8::Value
> key(property_names
->Get(i
));
407 // Extend this test to cover more types as necessary and if sensible.
408 if (!key
->IsString() &&
410 NOTREACHED() << "Key \"" << *v8::String::AsciiValue(key
) << "\" "
411 "is neither a string nor a number";
415 v8::String::Utf8Value
name_utf8(key
->ToString());
417 v8::TryCatch try_catch
;
418 v8::Handle
<v8::Value
> child_v8
= val
->Get(key
);
420 if (try_catch
.HasCaught()) {
421 LOG(WARNING
) << "Getter for property " << *name_utf8
422 << " threw an exception.";
423 child_v8
= v8::Null();
426 scoped_ptr
<base::Value
> child(FromV8ValueImpl(child_v8
, state
));
428 // JSON.stringify skips properties whose values don't serialize, for
429 // example undefined and functions. Emulate that behavior.
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.
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
447 // tabs.create({windowId: null})
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
))
455 result
->SetWithoutPathExpansion(std::string(*name_utf8
, name_utf8
.length()),
459 return result
.release();
462 } // namespace content