Assume the foo_test_run depends on everything needed to run the test.
[chromium-blink-merge.git] / content / renderer / v8_value_converter_impl.cc
blobb321f55cf6acc1e636febd90a55fceacd26d05c2
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"
7 #include <string>
9 #include "base/bind.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"
20 namespace content {
22 // Default implementation of V8ValueConverter::Strategy
24 bool V8ValueConverter::Strategy::FromV8Object(
25 v8::Handle<v8::Object> value,
26 base::Value** out,
27 v8::Isolate* isolate,
28 const FromV8ValueCallback& callback) const {
29 return false;
32 bool V8ValueConverter::Strategy::FromV8Array(
33 v8::Handle<v8::Array> value,
34 base::Value** out,
35 v8::Isolate* isolate,
36 const FromV8ValueCallback& callback) const {
37 return false;
40 bool V8ValueConverter::Strategy::FromV8ArrayBuffer(v8::Handle<v8::Object> value,
41 base::Value** out) const {
42 return false;
45 bool V8ValueConverter::Strategy::FromV8Number(v8::Handle<v8::Number> value,
46 base::Value** out) const {
47 return false;
50 bool V8ValueConverter::Strategy::FromV8Undefined(base::Value** out) const {
51 return false;
55 namespace {
57 // For the sake of the storage API, make this quite large.
58 const int kMaxRecursionDepth = 100;
60 } // namespace
62 // The state of a call to FromV8Value.
63 class V8ValueConverterImpl::FromV8ValueState {
64 public:
65 // Level scope which updates the current depth of some FromV8ValueState.
66 class Level {
67 public:
68 explicit Level(FromV8ValueState* state) : state_(state) {
69 state_->max_recursion_depth_--;
71 ~Level() {
72 state_->max_recursion_depth_++;
75 private:
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
84 // return true.
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)
100 return false;
102 unique_map_.insert(std::make_pair(hash, handle));
103 return true;
106 bool HasReachedMaxRecursionDepth() {
107 return max_recursion_depth_ < 0;
110 private:
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),
129 strategy_(NULL) {}
131 void V8ValueConverterImpl::SetDateAllowed(bool val) {
132 date_allowed_ = 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 {
170 CHECK(value);
171 switch (value->GetType()) {
172 case base::Value::TYPE_NULL:
173 return v8::Null(isolate);
175 case base::Value::TYPE_BOOLEAN: {
176 bool val = false;
177 CHECK(value->GetAsBoolean(&val));
178 return v8::Boolean::New(isolate, val);
181 case base::Value::TYPE_INTEGER: {
182 int val = 0;
183 CHECK(value->GetAsInteger(&val));
184 return v8::Integer::New(isolate, val);
187 case base::Value::TYPE_DOUBLE: {
188 double val = 0.0;
189 CHECK(value->GetAsDouble(&val));
190 return v8::Number::New(isolate, val);
193 case base::Value::TYPE_STRING: {
194 std::string val;
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));
210 default:
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.";
234 return result;
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;
249 result->Set(
250 v8::String::NewFromUtf8(
251 isolate, key.c_str(), v8::String::kNormalString, key.length()),
252 child_v8);
253 if (try_catch.HasCaught()) {
254 LOG(ERROR) << "Setter for property " << key.c_str() << " threw an "
255 << "exception.";
259 return result;
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())
278 return NULL;
280 if (val->IsNull())
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))
289 return out;
292 if (val->IsInt32())
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))
298 return NULL;
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()) {
308 if (strategy_) {
309 base::Value* out = NULL;
310 if (strategy_->FromV8Undefined(&out))
311 return out;
313 // JSON.stringify ignores undefined.
314 return NULL;
317 if (val->IsDate()) {
318 if (!date_allowed_)
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.
334 if (val->IsArray())
335 return FromV8Array(val.As<v8::Array>(), state, isolate);
337 if (val->IsFunction()) {
338 if (!function_allowed_)
339 // JSON.stringify refuses to convert function(){}.
340 return NULL;
341 return FromV8Object(val->ToObject(), state, isolate);
344 if (val->IsArrayBuffer() || val->IsArrayBufferView())
345 return FromV8ArrayBuffer(val->ToObject());
347 if (val->IsObject())
348 return FromV8Object(val->ToObject(), state, isolate);
350 LOG(ERROR) << "Unexpected v8 value type encountered.";
351 return NULL;
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()));
368 if (strategy_) {
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))
377 return out;
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());
393 continue;
396 base::Value* child = FromV8ValueImpl(state, child_v8, isolate);
397 if (child)
398 result->Append(child);
399 else
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());
404 return result;
407 base::Value* V8ValueConverterImpl::FromV8ArrayBuffer(
408 v8::Handle<v8::Object> val) const {
409 if (strategy_) {
410 base::Value* out = NULL;
411 if (strategy_->FromV8ArrayBuffer(val, &out))
412 return out;
415 char* data = NULL;
416 size_t length = 0;
418 scoped_ptr<blink::WebArrayBuffer> array_buffer(
419 blink::WebArrayBufferConverter::createFromV8Value(val));
420 scoped_ptr<blink::WebArrayBufferView> view;
421 if (array_buffer) {
422 data = reinterpret_cast<char*>(array_buffer->data());
423 length = array_buffer->byteLength();
424 } else {
425 view.reset(blink::WebArrayBufferView::createFromV8Value(val));
426 if (view) {
427 data = reinterpret_cast<char*>(view->baseAddress()) + view->byteOffset();
428 length = view->byteLength();
432 if (data)
433 return base::BinaryValue::CreateWithCopiedBuffer(data, length);
434 else
435 return NULL;
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()));
452 if (strategy_) {
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))
461 return out;
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
470 // these fields.
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() &&
488 !key->IsNumber()) {
489 NOTREACHED() << "Key \"" << *v8::String::Utf8Value(key) << "\" "
490 "is neither a string nor a number";
491 continue;
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));
506 if (!child)
507 // JSON.stringify skips properties whose values don't serialize, for
508 // example undefined and functions. Emulate that behavior.
509 continue;
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.
519 // Given just
521 // tabs.create({})
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))
532 continue;
534 result->SetWithoutPathExpansion(std::string(*name_utf8, name_utf8.length()),
535 child.release());
538 return result.release();
541 } // namespace content