Refactor management of overview window copy lifetime into a separate class.
[chromium-blink-merge.git] / content / renderer / v8_value_converter_impl.cc
blobab2a6330442a8fbd0f5eda2592b61e56d5cf605d
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/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"
17 namespace content {
19 namespace {
21 // For the sake of the storage API, make this quite large.
22 const int kMaxRecursionDepth = 100;
24 } // namespace
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_--;
35 ~Level() {
36 state_->max_recursion_depth_++;
39 private:
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
48 // return true.
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;
66 unique_map_.insert(std::make_pair(hash, handle));
67 return true;
70 bool HasReachedMaxRecursionDepth() {
71 return max_recursion_depth_ < 0;
74 private:
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),
93 strategy_(NULL) {}
95 void V8ValueConverterImpl::SetDateAllowed(bool val) {
96 date_allowed_ = 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 {
133 CHECK(value);
134 switch (value->GetType()) {
135 case base::Value::TYPE_NULL:
136 return v8::Null();
138 case base::Value::TYPE_BOOLEAN: {
139 bool val = false;
140 CHECK(value->GetAsBoolean(&val));
141 return v8::Boolean::New(val);
144 case base::Value::TYPE_INTEGER: {
145 int val = 0;
146 CHECK(value->GetAsInteger(&val));
147 return v8::Integer::New(val);
150 case base::Value::TYPE_DOUBLE: {
151 double val = 0.0;
152 CHECK(value->GetAsDouble(&val));
153 return v8::Number::New(val);
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());
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));
171 default:
172 LOG(ERROR) << "Unexpected value type: " << value->GetType();
173 return v8::Null();
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.";
194 return result;
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 "
211 << "exception.";
215 return result;
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())
233 return NULL;
235 if (val->IsNull())
236 return base::Value::CreateNullValue();
238 if (val->IsBoolean())
239 return new base::FundamentalValue(val->ToBoolean()->Value());
241 if (val->IsInt32())
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))
247 return NULL;
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.
258 return NULL;
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);
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.
277 if (val->IsArray())
278 return FromV8Array(val.As<v8::Array>(), state);
280 if (val->IsFunction()) {
281 if (!function_allowed_)
282 // JSON.stringify refuses to convert function(){}.
283 return NULL;
284 return FromV8Object(val->ToObject(), state);
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);
296 LOG(ERROR) << "Unexpected v8 value type encountered.";
297 return NULL;
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()));
313 if (strategy_) {
314 Value* out = NULL;
315 if (strategy_->FromV8Array(val, &out))
316 return 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))
331 continue;
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());
341 return result;
344 base::BinaryValue* V8ValueConverterImpl::FromV8Buffer(
345 v8::Handle<v8::Value> val) const {
346 char* data = NULL;
347 size_t length = 0;
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();
363 if (data)
364 return base::BinaryValue::CreateWithCopiedBuffer(data, length);
365 else
366 return NULL;
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()));
382 if (strategy_) {
383 Value* out = NULL;
384 if (strategy_->FromV8Object(val, &out))
385 return 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
394 // these fields.
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;
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() &&
409 !key->IsNumber()) {
410 NOTREACHED() << "Key \"" << *v8::String::AsciiValue(key) << "\" "
411 "is neither a string nor a number";
412 continue;
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));
427 if (!child)
428 // JSON.stringify skips properties whose values don't serialize, for
429 // example undefined and functions. Emulate that behavior.
430 continue;
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.
440 // Given just
442 // tabs.create({})
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))
453 continue;
455 result->SetWithoutPathExpansion(std::string(*name_utf8, name_utf8.length()),
456 child.release());
459 return result.release();
462 } // namespace content