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"
10 #include "base/bind_helpers.h"
11 #include "base/float_util.h"
12 #include "base/logging.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/values.h"
15 #include "third_party/WebKit/public/platform/WebArrayBuffer.h"
16 #include "third_party/WebKit/public/web/WebArrayBufferConverter.h"
17 #include "third_party/WebKit/public/web/WebArrayBufferView.h"
18 #include "v8/include/v8.h"
22 // Default implementation of V8ValueConverter::Strategy
24 bool V8ValueConverter::Strategy::FromV8Object(
25 v8::Handle
<v8::Object
> value
,
28 const FromV8ValueCallback
& callback
) const {
32 bool V8ValueConverter::Strategy::FromV8Array(
33 v8::Handle
<v8::Array
> value
,
36 const FromV8ValueCallback
& callback
) const {
40 bool V8ValueConverter::Strategy::FromV8ArrayBuffer(v8::Handle
<v8::Object
> value
,
41 base::Value
** out
) const {
45 bool V8ValueConverter::Strategy::FromV8Number(v8::Handle
<v8::Number
> value
,
46 base::Value
** out
) const {
50 bool V8ValueConverter::Strategy::FromV8Undefined(base::Value
** out
) const {
57 // For the sake of the storage API, make this quite large.
58 const int kMaxRecursionDepth
= 100;
62 // The state of a call to FromV8Value.
63 class V8ValueConverterImpl::FromV8ValueState
{
65 // Level scope which updates the current depth of some FromV8ValueState.
68 explicit Level(FromV8ValueState
* state
) : state_(state
) {
69 state_
->max_recursion_depth_
--;
72 state_
->max_recursion_depth_
++;
76 FromV8ValueState
* state_
;
79 explicit FromV8ValueState(bool avoid_identity_hash_for_testing
)
80 : max_recursion_depth_(kMaxRecursionDepth
),
81 avoid_identity_hash_for_testing_(avoid_identity_hash_for_testing
) {}
83 // If |handle| is not in |unique_map_|, then add it to |unique_map_| and
86 // Otherwise do nothing and return false. Here "A is unique" means that no
87 // other handle B in the map points to the same object as A. Note that A can
88 // be unique even if there already is another handle with the same identity
89 // hash (key) in the map, because two objects can have the same hash.
90 bool UpdateAndCheckUniqueness(v8::Handle
<v8::Object
> handle
) {
91 typedef HashToHandleMap::const_iterator Iterator
;
92 int hash
= avoid_identity_hash_for_testing_
? 0 : handle
->GetIdentityHash();
93 // We only compare using == with handles to objects with the same identity
94 // hash. Different hash obviously means different objects, but two objects
95 // in a couple of thousands could have the same identity hash.
96 std::pair
<Iterator
, Iterator
> range
= unique_map_
.equal_range(hash
);
97 for (Iterator it
= range
.first
; it
!= range
.second
; ++it
) {
98 // Operator == for handles actually compares the underlying objects.
99 if (it
->second
== handle
)
102 unique_map_
.insert(std::make_pair(hash
, handle
));
106 bool HasReachedMaxRecursionDepth() {
107 return max_recursion_depth_
< 0;
111 typedef std::multimap
<int, v8::Handle
<v8::Object
> > HashToHandleMap
;
112 HashToHandleMap unique_map_
;
114 int max_recursion_depth_
;
116 bool avoid_identity_hash_for_testing_
;
119 V8ValueConverter
* V8ValueConverter::create() {
120 return new V8ValueConverterImpl();
123 V8ValueConverterImpl::V8ValueConverterImpl()
124 : date_allowed_(false),
125 reg_exp_allowed_(false),
126 function_allowed_(false),
127 strip_null_from_objects_(false),
128 avoid_identity_hash_for_testing_(false),
131 void V8ValueConverterImpl::SetDateAllowed(bool val
) {
135 void V8ValueConverterImpl::SetRegExpAllowed(bool val
) {
136 reg_exp_allowed_
= val
;
139 void V8ValueConverterImpl::SetFunctionAllowed(bool val
) {
140 function_allowed_
= val
;
143 void V8ValueConverterImpl::SetStripNullFromObjects(bool val
) {
144 strip_null_from_objects_
= val
;
147 void V8ValueConverterImpl::SetStrategy(Strategy
* strategy
) {
148 strategy_
= strategy
;
151 v8::Handle
<v8::Value
> V8ValueConverterImpl::ToV8Value(
152 const base::Value
* value
, v8::Handle
<v8::Context
> context
) const {
153 v8::Context::Scope
context_scope(context
);
154 v8::EscapableHandleScope
handle_scope(context
->GetIsolate());
155 return handle_scope
.Escape(ToV8ValueImpl(context
->GetIsolate(), value
));
158 base::Value
* V8ValueConverterImpl::FromV8Value(
159 v8::Handle
<v8::Value
> val
,
160 v8::Handle
<v8::Context
> context
) const {
161 v8::Context::Scope
context_scope(context
);
162 v8::HandleScope
handle_scope(context
->GetIsolate());
163 FromV8ValueState
state(avoid_identity_hash_for_testing_
);
164 return FromV8ValueImpl(&state
, val
, context
->GetIsolate());
167 v8::Local
<v8::Value
> V8ValueConverterImpl::ToV8ValueImpl(
168 v8::Isolate
* isolate
,
169 const base::Value
* value
) const {
171 switch (value
->GetType()) {
172 case base::Value::TYPE_NULL
:
173 return v8::Null(isolate
);
175 case base::Value::TYPE_BOOLEAN
: {
177 CHECK(value
->GetAsBoolean(&val
));
178 return v8::Boolean::New(isolate
, val
);
181 case base::Value::TYPE_INTEGER
: {
183 CHECK(value
->GetAsInteger(&val
));
184 return v8::Integer::New(isolate
, val
);
187 case base::Value::TYPE_DOUBLE
: {
189 CHECK(value
->GetAsDouble(&val
));
190 return v8::Number::New(isolate
, val
);
193 case base::Value::TYPE_STRING
: {
195 CHECK(value
->GetAsString(&val
));
196 return v8::String::NewFromUtf8(
197 isolate
, val
.c_str(), v8::String::kNormalString
, val
.length());
200 case base::Value::TYPE_LIST
:
201 return ToV8Array(isolate
, static_cast<const base::ListValue
*>(value
));
203 case base::Value::TYPE_DICTIONARY
:
204 return ToV8Object(isolate
,
205 static_cast<const base::DictionaryValue
*>(value
));
207 case base::Value::TYPE_BINARY
:
208 return ToArrayBuffer(static_cast<const base::BinaryValue
*>(value
));
211 LOG(ERROR
) << "Unexpected value type: " << value
->GetType();
212 return v8::Null(isolate
);
216 v8::Handle
<v8::Value
> V8ValueConverterImpl::ToV8Array(
217 v8::Isolate
* isolate
,
218 const base::ListValue
* val
) const {
219 v8::Handle
<v8::Array
> result(v8::Array::New(isolate
, val
->GetSize()));
221 for (size_t i
= 0; i
< val
->GetSize(); ++i
) {
222 const base::Value
* child
= NULL
;
223 CHECK(val
->Get(i
, &child
));
225 v8::Handle
<v8::Value
> child_v8
= ToV8ValueImpl(isolate
, child
);
226 CHECK(!child_v8
.IsEmpty());
228 v8::TryCatch try_catch
;
229 result
->Set(static_cast<uint32
>(i
), child_v8
);
230 if (try_catch
.HasCaught())
231 LOG(ERROR
) << "Setter for index " << i
<< " threw an exception.";
237 v8::Handle
<v8::Value
> V8ValueConverterImpl::ToV8Object(
238 v8::Isolate
* isolate
,
239 const base::DictionaryValue
* val
) const {
240 v8::Handle
<v8::Object
> result(v8::Object::New(isolate
));
242 for (base::DictionaryValue::Iterator
iter(*val
);
243 !iter
.IsAtEnd(); iter
.Advance()) {
244 const std::string
& key
= iter
.key();
245 v8::Handle
<v8::Value
> child_v8
= ToV8ValueImpl(isolate
, &iter
.value());
246 CHECK(!child_v8
.IsEmpty());
248 v8::TryCatch try_catch
;
250 v8::String::NewFromUtf8(
251 isolate
, key
.c_str(), v8::String::kNormalString
, key
.length()),
253 if (try_catch
.HasCaught()) {
254 LOG(ERROR
) << "Setter for property " << key
.c_str() << " threw an "
262 v8::Handle
<v8::Value
> V8ValueConverterImpl::ToArrayBuffer(
263 const base::BinaryValue
* value
) const {
264 blink::WebArrayBuffer buffer
=
265 blink::WebArrayBuffer::create(value
->GetSize(), 1);
266 memcpy(buffer
.data(), value
->GetBuffer(), value
->GetSize());
267 return blink::WebArrayBufferConverter::toV8Value(&buffer
);
270 base::Value
* V8ValueConverterImpl::FromV8ValueImpl(
271 FromV8ValueState
* state
,
272 v8::Handle
<v8::Value
> val
,
273 v8::Isolate
* isolate
) const {
274 CHECK(!val
.IsEmpty());
276 FromV8ValueState::Level
state_level(state
);
277 if (state
->HasReachedMaxRecursionDepth())
281 return base::Value::CreateNullValue();
283 if (val
->IsBoolean())
284 return new base::FundamentalValue(val
->ToBoolean()->Value());
286 if (val
->IsNumber() && strategy_
) {
287 base::Value
* out
= NULL
;
288 if (strategy_
->FromV8Number(val
->ToNumber(), &out
))
293 return new base::FundamentalValue(val
->ToInt32()->Value());
295 if (val
->IsNumber()) {
296 double val_as_double
= val
->ToNumber()->Value();
297 if (!base::IsFinite(val_as_double
))
299 return new base::FundamentalValue(val_as_double
);
302 if (val
->IsString()) {
303 v8::String::Utf8Value
utf8(val
->ToString());
304 return new base::StringValue(std::string(*utf8
, utf8
.length()));
307 if (val
->IsUndefined()) {
309 base::Value
* out
= NULL
;
310 if (strategy_
->FromV8Undefined(&out
))
313 // JSON.stringify ignores undefined.
319 // JSON.stringify would convert this to a string, but an object is more
320 // consistent within this class.
321 return FromV8Object(val
->ToObject(), state
, isolate
);
322 v8::Date
* date
= v8::Date::Cast(*val
);
323 return new base::FundamentalValue(date
->ValueOf() / 1000.0);
326 if (val
->IsRegExp()) {
327 if (!reg_exp_allowed_
)
328 // JSON.stringify converts to an object.
329 return FromV8Object(val
->ToObject(), state
, isolate
);
330 return new base::StringValue(*v8::String::Utf8Value(val
->ToString()));
333 // v8::Value doesn't have a ToArray() method for some reason.
335 return FromV8Array(val
.As
<v8::Array
>(), state
, isolate
);
337 if (val
->IsFunction()) {
338 if (!function_allowed_
)
339 // JSON.stringify refuses to convert function(){}.
341 return FromV8Object(val
->ToObject(), state
, isolate
);
344 if (val
->IsArrayBuffer() || val
->IsArrayBufferView())
345 return FromV8ArrayBuffer(val
->ToObject());
348 return FromV8Object(val
->ToObject(), state
, isolate
);
350 LOG(ERROR
) << "Unexpected v8 value type encountered.";
354 base::Value
* V8ValueConverterImpl::FromV8Array(
355 v8::Handle
<v8::Array
> val
,
356 FromV8ValueState
* state
,
357 v8::Isolate
* isolate
) const {
358 if (!state
->UpdateAndCheckUniqueness(val
))
359 return base::Value::CreateNullValue();
361 scoped_ptr
<v8::Context::Scope
> scope
;
362 // If val was created in a different context than our current one, change to
363 // that context, but change back after val is converted.
364 if (!val
->CreationContext().IsEmpty() &&
365 val
->CreationContext() != isolate
->GetCurrentContext())
366 scope
.reset(new v8::Context::Scope(val
->CreationContext()));
369 // These base::Unretained's are safe, because Strategy::FromV8Value should
370 // be synchronous, so this object can't be out of scope.
371 V8ValueConverter::Strategy::FromV8ValueCallback callback
=
372 base::Bind(&V8ValueConverterImpl::FromV8ValueImpl
,
373 base::Unretained(this),
374 base::Unretained(state
));
375 base::Value
* out
= NULL
;
376 if (strategy_
->FromV8Array(val
, &out
, isolate
, callback
))
380 base::ListValue
* result
= new base::ListValue();
382 // Only fields with integer keys are carried over to the ListValue.
383 for (uint32 i
= 0; i
< val
->Length(); ++i
) {
384 v8::TryCatch try_catch
;
385 v8::Handle
<v8::Value
> child_v8
= val
->Get(i
);
386 if (try_catch
.HasCaught()) {
387 LOG(ERROR
) << "Getter for index " << i
<< " threw an exception.";
388 child_v8
= v8::Null(isolate
);
391 if (!val
->HasRealIndexedProperty(i
)) {
392 result
->Append(base::Value::CreateNullValue());
396 base::Value
* child
= FromV8ValueImpl(state
, child_v8
, isolate
);
398 result
->Append(child
);
400 // JSON.stringify puts null in places where values don't serialize, for
401 // example undefined and functions. Emulate that behavior.
402 result
->Append(base::Value::CreateNullValue());
407 base::Value
* V8ValueConverterImpl::FromV8ArrayBuffer(
408 v8::Handle
<v8::Object
> val
) const {
410 base::Value
* out
= NULL
;
411 if (strategy_
->FromV8ArrayBuffer(val
, &out
))
418 scoped_ptr
<blink::WebArrayBuffer
> array_buffer(
419 blink::WebArrayBufferConverter::createFromV8Value(val
));
420 scoped_ptr
<blink::WebArrayBufferView
> view
;
422 data
= reinterpret_cast<char*>(array_buffer
->data());
423 length
= array_buffer
->byteLength();
425 view
.reset(blink::WebArrayBufferView::createFromV8Value(val
));
427 data
= reinterpret_cast<char*>(view
->baseAddress()) + view
->byteOffset();
428 length
= view
->byteLength();
433 return base::BinaryValue::CreateWithCopiedBuffer(data
, length
);
438 base::Value
* V8ValueConverterImpl::FromV8Object(
439 v8::Handle
<v8::Object
> val
,
440 FromV8ValueState
* state
,
441 v8::Isolate
* isolate
) const {
442 if (!state
->UpdateAndCheckUniqueness(val
))
443 return base::Value::CreateNullValue();
445 scoped_ptr
<v8::Context::Scope
> scope
;
446 // If val was created in a different context than our current one, change to
447 // that context, but change back after val is converted.
448 if (!val
->CreationContext().IsEmpty() &&
449 val
->CreationContext() != isolate
->GetCurrentContext())
450 scope
.reset(new v8::Context::Scope(val
->CreationContext()));
453 // These base::Unretained's are safe, because Strategy::FromV8Value should
454 // be synchronous, so this object can't be out of scope.
455 V8ValueConverter::Strategy::FromV8ValueCallback callback
=
456 base::Bind(&V8ValueConverterImpl::FromV8ValueImpl
,
457 base::Unretained(this),
458 base::Unretained(state
));
459 base::Value
* out
= NULL
;
460 if (strategy_
->FromV8Object(val
, &out
, isolate
, callback
))
464 // Don't consider DOM objects. This check matches isHostObject() in Blink's
465 // bindings/v8/V8Binding.h used in structured cloning. It reads:
467 // If the object has any internal fields, then we won't be able to serialize
468 // or deserialize them; conveniently, this is also a quick way to detect DOM
469 // wrapper objects, because the mechanism for these relies on data stored in
472 // NOTE: check this after |strategy_| so that callers have a chance to
473 // do something else, such as convert to the node's name rather than NULL.
475 // ANOTHER NOTE: returning an empty dictionary here to minimise surprise.
476 // See also http://crbug.com/330559.
477 if (val
->InternalFieldCount())
478 return new base::DictionaryValue();
480 scoped_ptr
<base::DictionaryValue
> result(new base::DictionaryValue());
481 v8::Handle
<v8::Array
> property_names(val
->GetOwnPropertyNames());
483 for (uint32 i
= 0; i
< property_names
->Length(); ++i
) {
484 v8::Handle
<v8::Value
> key(property_names
->Get(i
));
486 // Extend this test to cover more types as necessary and if sensible.
487 if (!key
->IsString() &&
489 NOTREACHED() << "Key \"" << *v8::String::Utf8Value(key
) << "\" "
490 "is neither a string nor a number";
494 v8::String::Utf8Value
name_utf8(key
->ToString());
496 v8::TryCatch try_catch
;
497 v8::Handle
<v8::Value
> child_v8
= val
->Get(key
);
499 if (try_catch
.HasCaught()) {
500 LOG(WARNING
) << "Getter for property " << *name_utf8
501 << " threw an exception.";
502 child_v8
= v8::Null(isolate
);
505 scoped_ptr
<base::Value
> child(FromV8ValueImpl(state
, child_v8
, isolate
));
507 // JSON.stringify skips properties whose values don't serialize, for
508 // example undefined and functions. Emulate that behavior.
511 // Strip null if asked (and since undefined is turned into null, undefined
512 // too). The use case for supporting this is JSON-schema support,
513 // specifically for extensions, where "optional" JSON properties may be
514 // represented as null, yet due to buggy legacy code elsewhere isn't
515 // treated as such (potentially causing crashes). For example, the
516 // "tabs.create" function takes an object as its first argument with an
517 // optional "windowId" property.
523 // this will work as expected on code that only checks for the existence of
524 // a "windowId" property (such as that legacy code). However given
526 // tabs.create({windowId: null})
528 // there *is* a "windowId" property, but since it should be an int, code
529 // on the browser which doesn't additionally check for null will fail.
530 // We can avoid all bugs related to this by stripping null.
531 if (strip_null_from_objects_
&& child
->IsType(base::Value::TYPE_NULL
))
534 result
->SetWithoutPathExpansion(std::string(*name_utf8
, name_utf8
.length()),
538 return result
.release();
541 } // namespace content