2 * Copyright (C) 2011 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
15 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
18 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
19 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
20 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
21 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include "bindings/v8/IDBBindingUtilities.h"
29 #include "RuntimeEnabledFeatures.h"
30 #include "V8DOMStringList.h"
31 #include "V8IDBCursor.h"
32 #include "V8IDBCursorWithValue.h"
33 #include "V8IDBDatabase.h"
34 #include "V8IDBIndex.h"
35 #include "V8IDBKeyRange.h"
36 #include "V8IDBObjectStore.h"
37 #include "V8IDBRequest.h"
38 #include "V8IDBTransaction.h"
39 #include "bindings/v8/DOMRequestState.h"
40 #include "bindings/v8/SerializedScriptValue.h"
41 #include "bindings/v8/V8Binding.h"
42 #include "bindings/v8/V8HiddenValue.h"
43 #include "bindings/v8/custom/V8ArrayBufferViewCustom.h"
44 #include "bindings/v8/custom/V8Uint8ArrayCustom.h"
45 #include "modules/indexeddb/IDBKey.h"
46 #include "modules/indexeddb/IDBKeyPath.h"
47 #include "modules/indexeddb/IDBKeyRange.h"
48 #include "modules/indexeddb/IDBTracing.h"
49 #include "platform/SharedBuffer.h"
50 #include "wtf/ArrayBufferView.h"
51 #include "wtf/MathExtras.h"
52 #include "wtf/Uint8Array.h"
53 #include "wtf/Vector.h"
57 static v8::Handle<v8::Value> deserializeIDBValueBuffer(SharedBuffer*, v8::Isolate*);
59 static v8::Handle<v8::Value> toV8(const IDBKeyPath& value, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
61 switch (value.type()) {
62 case IDBKeyPath::NullType:
63 return v8::Null(isolate);
64 case IDBKeyPath::StringType:
65 return v8String(isolate, value.string());
66 case IDBKeyPath::ArrayType:
67 RefPtr<DOMStringList> keyPaths = DOMStringList::create();
68 for (Vector<String>::const_iterator it = value.array().begin(); it != value.array().end(); ++it)
69 keyPaths->append(*it);
70 return toV8(keyPaths.release(), creationContext, isolate);
73 return v8::Undefined(isolate);
76 static v8::Handle<v8::Value> toV8(const IDBKey* key, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
79 // This should be undefined, not null.
80 // Spec: http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html#idl-def-IDBKeyRange
84 switch (key->type()) {
85 case IDBKey::InvalidType:
89 case IDBKey::NumberType:
90 return v8::Number::New(isolate, key->number());
91 case IDBKey::StringType:
92 return v8String(isolate, key->string());
93 case IDBKey::BinaryType:
94 return toV8(Uint8Array::create(reinterpret_cast<const unsigned char*>(key->binary()->data()), key->binary()->size()), creationContext, isolate);
95 case IDBKey::DateType:
96 return v8::Date::New(isolate, key->date());
97 case IDBKey::ArrayType:
99 v8::Local<v8::Array> array = v8::Array::New(isolate, key->array().size());
100 for (size_t i = 0; i < key->array().size(); ++i)
101 array->Set(i, toV8(key->array()[i].get(), creationContext, isolate));
106 ASSERT_NOT_REACHED();
107 return v8Undefined();
110 static v8::Handle<v8::Value> toV8(const IDBAny* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
113 return v8::Null(isolate);
115 switch (impl->type()) {
116 case IDBAny::UndefinedType:
117 return v8::Undefined(isolate);
118 case IDBAny::NullType:
119 return v8::Null(isolate);
120 case IDBAny::DOMStringListType:
121 return toV8(impl->domStringList(), creationContext, isolate);
122 case IDBAny::IDBCursorType: {
123 // Ensure request wrapper is kept alive at least as long as the cursor wrapper,
124 // so that event listeners are retained.
125 v8::Handle<v8::Value> cursor = toV8(impl->idbCursor(), creationContext, isolate);
126 v8::Handle<v8::Value> request = toV8(impl->idbCursor()->request(), creationContext, isolate);
127 V8HiddenValue::setHiddenValue(isolate, cursor->ToObject(), V8HiddenValue::idbCursorRequest(isolate), request);
130 case IDBAny::IDBCursorWithValueType: {
131 // Ensure request wrapper is kept alive at least as long as the cursor wrapper,
132 // so that event listeners are retained.
133 v8::Handle<v8::Value> cursor = toV8(impl->idbCursorWithValue(), creationContext, isolate);
134 v8::Handle<v8::Value> request = toV8(impl->idbCursorWithValue()->request(), creationContext, isolate);
135 V8HiddenValue::setHiddenValue(isolate, cursor->ToObject(), V8HiddenValue::idbCursorRequest(isolate), request);
138 case IDBAny::IDBDatabaseType:
139 return toV8(impl->idbDatabase(), creationContext, isolate);
140 case IDBAny::IDBIndexType:
141 return toV8(impl->idbIndex(), creationContext, isolate);
142 case IDBAny::IDBObjectStoreType:
143 return toV8(impl->idbObjectStore(), creationContext, isolate);
144 case IDBAny::IDBTransactionType:
145 return toV8(impl->idbTransaction(), creationContext, isolate);
146 case IDBAny::BufferType:
147 return deserializeIDBValueBuffer(impl->buffer(), isolate);
148 case IDBAny::StringType:
149 return v8String(isolate, impl->string());
150 case IDBAny::IntegerType:
151 return v8::Number::New(isolate, impl->integer());
152 case IDBAny::KeyType:
153 return toV8(impl->key(), creationContext, isolate);
154 case IDBAny::KeyPathType:
155 return toV8(impl->keyPath(), creationContext, isolate);
156 case IDBAny::BufferKeyAndKeyPathType: {
157 v8::Handle<v8::Value> value = deserializeIDBValueBuffer(impl->buffer(), isolate);
158 v8::Handle<v8::Value> key = toV8(impl->key(), creationContext, isolate);
159 bool injected = injectV8KeyIntoV8Value(key, value, impl->keyPath(), isolate);
160 ASSERT_UNUSED(injected, injected);
165 ASSERT_NOT_REACHED();
166 return v8::Undefined(isolate);
169 static const size_t maximumDepth = 2000;
171 static PassRefPtr<IDBKey> createIDBKeyFromValue(v8::Handle<v8::Value> value, Vector<v8::Handle<v8::Array> >& stack, v8::Isolate* isolate, bool allowExperimentalTypes = false)
173 if (value->IsNumber() && !std::isnan(value->NumberValue()))
174 return IDBKey::createNumber(value->NumberValue());
175 if (value->IsString())
176 return IDBKey::createString(toCoreString(value.As<v8::String>()));
177 if (value->IsDate() && !std::isnan(value->NumberValue()))
178 return IDBKey::createDate(value->NumberValue());
179 if (value->IsUint8Array() && (allowExperimentalTypes || RuntimeEnabledFeatures::indexedDBExperimentalEnabled())) {
180 // Per discussion in https://www.w3.org/Bugs/Public/show_bug.cgi?id=23332 the
181 // input type is constrained to Uint8Array to match the output type.
182 ArrayBufferView* view = WebCore::V8ArrayBufferView::toNative(value->ToObject());
183 const char* start = static_cast<const char*>(view->baseAddress());
184 size_t length = view->byteLength();
185 return IDBKey::createBinary(SharedBuffer::create(start, length));
187 if (value->IsArray()) {
188 v8::Handle<v8::Array> array = v8::Handle<v8::Array>::Cast(value);
190 if (stack.contains(array))
192 if (stack.size() >= maximumDepth)
196 IDBKey::KeyArray subkeys;
197 uint32_t length = array->Length();
198 for (uint32_t i = 0; i < length; ++i) {
199 v8::Local<v8::Value> item = array->Get(v8::Int32::New(isolate, i));
200 RefPtr<IDBKey> subkey = createIDBKeyFromValue(item, stack, isolate, allowExperimentalTypes);
202 subkeys.append(IDBKey::createInvalid());
204 subkeys.append(subkey);
208 return IDBKey::createArray(subkeys);
213 static PassRefPtr<IDBKey> createIDBKeyFromValue(v8::Handle<v8::Value> value, v8::Isolate* isolate, bool allowExperimentalTypes = false)
215 Vector<v8::Handle<v8::Array> > stack;
216 RefPtr<IDBKey> key = createIDBKeyFromValue(value, stack, isolate, allowExperimentalTypes);
219 return IDBKey::createInvalid();
223 static bool getValueFrom(T indexOrName, v8::Handle<v8::Value>& v8Value)
225 v8::Local<v8::Object> object = v8Value->ToObject();
226 if (!object->Has(indexOrName))
228 v8Value = object->Get(indexOrName);
233 static bool setValue(v8::Handle<v8::Value>& v8Object, T indexOrName, const v8::Handle<v8::Value>& v8Value)
235 v8::Local<v8::Object> object = v8Object->ToObject();
236 return object->Set(indexOrName, v8Value);
239 static bool get(v8::Handle<v8::Value>& object, const String& keyPathElement, v8::Handle<v8::Value>& result, v8::Isolate* isolate)
241 if (object->IsString() && keyPathElement == "length") {
242 int32_t length = v8::Handle<v8::String>::Cast(object)->Length();
243 result = v8::Number::New(isolate, length);
246 return object->IsObject() && getValueFrom(v8String(isolate, keyPathElement), result);
249 static bool canSet(v8::Handle<v8::Value>& object, const String& keyPathElement)
251 return object->IsObject();
254 static bool set(v8::Handle<v8::Value>& object, const String& keyPathElement, const v8::Handle<v8::Value>& v8Value, v8::Isolate* isolate)
256 return canSet(object, keyPathElement) && setValue(object, v8String(isolate, keyPathElement), v8Value);
259 static v8::Handle<v8::Value> getNthValueOnKeyPath(v8::Handle<v8::Value>& rootValue, const Vector<String>& keyPathElements, size_t index, v8::Isolate* isolate)
261 v8::Handle<v8::Value> currentValue(rootValue);
262 ASSERT(index <= keyPathElements.size());
263 for (size_t i = 0; i < index; ++i) {
264 v8::Handle<v8::Value> parentValue(currentValue);
265 if (!get(parentValue, keyPathElements[i], currentValue, isolate))
266 return v8Undefined();
272 static bool canInjectNthValueOnKeyPath(v8::Handle<v8::Value>& rootValue, const Vector<String>& keyPathElements, size_t index, v8::Isolate* isolate)
274 if (!rootValue->IsObject())
277 v8::Handle<v8::Value> currentValue(rootValue);
279 ASSERT(index <= keyPathElements.size());
280 for (size_t i = 0; i < index; ++i) {
281 v8::Handle<v8::Value> parentValue(currentValue);
282 const String& keyPathElement = keyPathElements[i];
283 if (!get(parentValue, keyPathElement, currentValue, isolate))
284 return canSet(parentValue, keyPathElement);
290 static v8::Handle<v8::Value> ensureNthValueOnKeyPath(v8::Handle<v8::Value>& rootValue, const Vector<String>& keyPathElements, size_t index, v8::Isolate* isolate)
292 v8::Handle<v8::Value> currentValue(rootValue);
294 ASSERT(index <= keyPathElements.size());
295 for (size_t i = 0; i < index; ++i) {
296 v8::Handle<v8::Value> parentValue(currentValue);
297 const String& keyPathElement = keyPathElements[i];
298 if (!get(parentValue, keyPathElement, currentValue, isolate)) {
299 v8::Handle<v8::Object> object = v8::Object::New(isolate);
300 if (!set(parentValue, keyPathElement, object, isolate))
301 return v8Undefined();
302 currentValue = object;
309 static PassRefPtr<IDBKey> createIDBKeyFromScriptValueAndKeyPath(const ScriptValue& value, const String& keyPath, v8::Isolate* isolate, bool allowExperimentalTypes)
311 Vector<String> keyPathElements;
312 IDBKeyPathParseError error;
313 IDBParseKeyPath(keyPath, keyPathElements, error);
314 ASSERT(error == IDBKeyPathParseErrorNone);
315 ASSERT(isolate->InContext());
317 v8::HandleScope handleScope(isolate);
318 v8::Handle<v8::Value> v8Value(value.v8Value());
319 v8::Handle<v8::Value> v8Key(getNthValueOnKeyPath(v8Value, keyPathElements, keyPathElements.size(), isolate));
322 return createIDBKeyFromValue(v8Key, isolate, allowExperimentalTypes);
325 static PassRefPtr<IDBKey> createIDBKeyFromScriptValueAndKeyPath(const ScriptValue& value, const IDBKeyPath& keyPath, v8::Isolate* isolate, bool allowExperimentalTypes = false)
327 ASSERT(!keyPath.isNull());
328 v8::HandleScope handleScope(isolate);
329 if (keyPath.type() == IDBKeyPath::ArrayType) {
330 IDBKey::KeyArray result;
331 const Vector<String>& array = keyPath.array();
332 for (size_t i = 0; i < array.size(); ++i) {
333 RefPtr<IDBKey> key = createIDBKeyFromScriptValueAndKeyPath(value, array[i], isolate, allowExperimentalTypes);
338 return IDBKey::createArray(result);
341 ASSERT(keyPath.type() == IDBKeyPath::StringType);
342 return createIDBKeyFromScriptValueAndKeyPath(value, keyPath.string(), isolate, allowExperimentalTypes);
345 PassRefPtr<IDBKey> createIDBKeyFromScriptValueAndKeyPath(DOMRequestState* state, const ScriptValue& value, const IDBKeyPath& keyPath)
347 IDB_TRACE("createIDBKeyFromScriptValueAndKeyPath");
348 v8::Isolate* isolate = state ? state->isolate() : v8::Isolate::GetCurrent();
349 return createIDBKeyFromScriptValueAndKeyPath(value, keyPath, isolate);
352 static v8::Handle<v8::Value> deserializeIDBValueBuffer(SharedBuffer* buffer, v8::Isolate* isolate)
354 ASSERT(isolate->InContext());
356 return v8::Null(isolate);
358 // FIXME: The extra copy here can be eliminated by allowing SerializedScriptValue to take a raw const char* or const uint8_t*.
359 Vector<uint8_t> value;
360 value.append(buffer->data(), buffer->size());
361 RefPtr<SerializedScriptValue> serializedValue = SerializedScriptValue::createFromWireBytes(value);
362 return serializedValue->deserialize(isolate);
365 bool injectV8KeyIntoV8Value(v8::Handle<v8::Value> key, v8::Handle<v8::Value> value, const IDBKeyPath& keyPath, v8::Isolate* isolate)
367 IDB_TRACE("injectIDBV8KeyIntoV8Value");
368 ASSERT(isolate->InContext());
370 ASSERT(keyPath.type() == IDBKeyPath::StringType);
371 Vector<String> keyPathElements;
372 IDBKeyPathParseError error;
373 IDBParseKeyPath(keyPath.string(), keyPathElements, error);
374 ASSERT(error == IDBKeyPathParseErrorNone);
376 if (!keyPathElements.size())
379 v8::HandleScope handleScope(isolate);
380 v8::Handle<v8::Value> parent(ensureNthValueOnKeyPath(value, keyPathElements, keyPathElements.size() - 1, isolate));
381 if (parent.IsEmpty())
384 if (!set(parent, keyPathElements.last(), key, isolate))
390 bool canInjectIDBKeyIntoScriptValue(DOMRequestState* state, const ScriptValue& scriptValue, const IDBKeyPath& keyPath)
392 IDB_TRACE("canInjectIDBKeyIntoScriptValue");
393 ASSERT(keyPath.type() == IDBKeyPath::StringType);
394 Vector<String> keyPathElements;
395 IDBKeyPathParseError error;
396 IDBParseKeyPath(keyPath.string(), keyPathElements, error);
397 ASSERT(error == IDBKeyPathParseErrorNone);
399 if (!keyPathElements.size())
402 v8::Handle<v8::Value> v8Value(scriptValue.v8Value());
403 return canInjectNthValueOnKeyPath(v8Value, keyPathElements, keyPathElements.size() - 1, state->context()->GetIsolate());
406 ScriptValue idbAnyToScriptValue(DOMRequestState* state, PassRefPtr<IDBAny> any)
408 v8::Isolate* isolate = state ? state->isolate() : v8::Isolate::GetCurrent();
409 ASSERT(isolate->InContext());
410 v8::Local<v8::Context> context = state ? state->context() : isolate->GetCurrentContext();
411 v8::HandleScope handleScope(isolate);
412 v8::Handle<v8::Value> v8Value(toV8(any.get(), context->Global(), isolate));
413 return ScriptValue(v8Value, isolate);
416 ScriptValue idbKeyToScriptValue(DOMRequestState* state, PassRefPtr<IDBKey> key)
418 v8::Isolate* isolate = state ? state->isolate() : v8::Isolate::GetCurrent();
419 ASSERT(isolate->InContext());
420 v8::Local<v8::Context> context = state ? state->context() : isolate->GetCurrentContext();
421 v8::HandleScope handleScope(isolate);
422 v8::Handle<v8::Value> v8Value(toV8(key.get(), context->Global(), isolate));
423 return ScriptValue(v8Value, isolate);
426 PassRefPtr<IDBKey> scriptValueToIDBKey(DOMRequestState* state, const ScriptValue& scriptValue)
428 v8::Isolate* isolate = state ? state->isolate() : v8::Isolate::GetCurrent();
429 ASSERT(isolate->InContext());
430 v8::HandleScope handleScope(isolate);
431 v8::Handle<v8::Value> v8Value(scriptValue.v8Value());
432 return createIDBKeyFromValue(v8Value, isolate);
435 PassRefPtr<IDBKeyRange> scriptValueToIDBKeyRange(DOMRequestState* state, const ScriptValue& scriptValue)
437 v8::Isolate* isolate = state ? state->isolate() : v8::Isolate::GetCurrent();
438 v8::HandleScope handleScope(isolate);
439 v8::Handle<v8::Value> value(scriptValue.v8Value());
440 return V8IDBKeyRange::toNativeWithTypeCheck(isolate, value);
444 void assertPrimaryKeyValidOrInjectable(DOMRequestState* state, PassRefPtr<SharedBuffer> buffer, PassRefPtr<IDBKey> prpKey, const IDBKeyPath& keyPath)
446 RefPtr<IDBKey> key(prpKey);
448 DOMRequestState::Scope scope(*state);
449 v8::Isolate* isolate = state ? state->isolate() : v8::Isolate::GetCurrent();
451 ScriptValue keyValue = idbKeyToScriptValue(state, key);
452 ScriptValue scriptValue(deserializeIDBValueBuffer(buffer.get(), isolate), isolate);
454 // This assertion is about already persisted data, so allow experimental types.
455 const bool allowExperimentalTypes = true;
456 RefPtr<IDBKey> expectedKey = createIDBKeyFromScriptValueAndKeyPath(scriptValue, keyPath, isolate, allowExperimentalTypes);
457 ASSERT(!expectedKey || expectedKey->isEqual(key.get()));
459 bool injected = injectV8KeyIntoV8Value(keyValue.v8Value(), scriptValue.v8Value(), keyPath, isolate);
460 ASSERT_UNUSED(injected, injected);
464 } // namespace WebCore