Source code

Revision control

Other Tools

1
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
3
/* This Source Code Form is subject to the terms of the Mozilla Public
4
* License, v. 2.0. If a copy of the MPL was not distributed with this
5
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7
#include "IDBDatabase.h"
8
9
#include "FileInfo.h"
10
#include "IDBEvents.h"
11
#include "IDBFactory.h"
12
#include "IDBIndex.h"
13
#include "IDBMutableFile.h"
14
#include "IDBObjectStore.h"
15
#include "IDBRequest.h"
16
#include "IDBTransaction.h"
17
#include "IDBFactory.h"
18
#include "IndexedDatabaseManager.h"
19
#include "mozilla/ErrorResult.h"
20
#include "mozilla/EventDispatcher.h"
21
#include "MainThreadUtils.h"
22
#include "mozilla/Services.h"
23
#include "mozilla/storage.h"
24
#include "mozilla/dom/BindingDeclarations.h"
25
#include "mozilla/dom/DOMStringListBinding.h"
26
#include "mozilla/dom/Exceptions.h"
27
#include "mozilla/dom/File.h"
28
#include "mozilla/dom/IDBDatabaseBinding.h"
29
#include "mozilla/dom/IDBObjectStoreBinding.h"
30
#include "mozilla/dom/indexedDB/PBackgroundIDBDatabaseFileChild.h"
31
#include "mozilla/dom/indexedDB/PBackgroundIDBSharedTypes.h"
32
#include "mozilla/dom/IPCBlobUtils.h"
33
#include "mozilla/dom/quota/QuotaManager.h"
34
#include "mozilla/ipc/BackgroundChild.h"
35
#include "mozilla/ipc/BackgroundUtils.h"
36
#include "mozilla/ipc/FileDescriptor.h"
37
#include "mozilla/ipc/InputStreamParams.h"
38
#include "mozilla/ipc/InputStreamUtils.h"
39
#include "nsAutoPtr.h"
40
#include "nsCOMPtr.h"
41
#include "mozilla/dom/Document.h"
42
#include "nsIObserver.h"
43
#include "nsIObserverService.h"
44
#include "nsIScriptError.h"
45
#include "nsISupportsPrimitives.h"
46
#include "nsThreadUtils.h"
47
#include "nsIWeakReferenceUtils.h"
48
#include "ProfilerHelpers.h"
49
#include "ReportInternalError.h"
50
#include "ScriptErrorHelper.h"
51
#include "nsQueryObject.h"
52
53
// Include this last to avoid path problems on Windows.
54
#include "ActorsChild.h"
55
56
namespace mozilla {
57
namespace dom {
58
59
using namespace mozilla::dom::indexedDB;
60
using namespace mozilla::dom::quota;
61
using namespace mozilla::ipc;
62
using namespace mozilla::services;
63
64
namespace {
65
66
const char kCycleCollectionObserverTopic[] = "cycle-collector-end";
67
const char kMemoryPressureObserverTopic[] = "memory-pressure";
68
const char kWindowObserverTopic[] = "inner-window-destroyed";
69
70
class CancelableRunnableWrapper final : public CancelableRunnable {
71
nsCOMPtr<nsIRunnable> mRunnable;
72
73
public:
74
explicit CancelableRunnableWrapper(nsIRunnable* aRunnable)
75
: CancelableRunnable("dom::CancelableRunnableWrapper"),
76
mRunnable(aRunnable) {
77
MOZ_ASSERT(aRunnable);
78
}
79
80
private:
81
~CancelableRunnableWrapper() = default;
82
83
NS_DECL_NSIRUNNABLE
84
nsresult Cancel() override;
85
};
86
87
class DatabaseFile final : public PBackgroundIDBDatabaseFileChild {
88
IDBDatabase* mDatabase;
89
90
public:
91
explicit DatabaseFile(IDBDatabase* aDatabase) : mDatabase(aDatabase) {
92
MOZ_ASSERT(aDatabase);
93
aDatabase->AssertIsOnOwningThread();
94
95
MOZ_COUNT_CTOR(DatabaseFile);
96
}
97
98
private:
99
~DatabaseFile() {
100
MOZ_ASSERT(!mDatabase);
101
102
MOZ_COUNT_DTOR(DatabaseFile);
103
}
104
105
virtual void ActorDestroy(ActorDestroyReason aWhy) override {
106
MOZ_ASSERT(mDatabase);
107
mDatabase->AssertIsOnOwningThread();
108
109
if (aWhy != Deletion) {
110
RefPtr<IDBDatabase> database = mDatabase;
111
database->NoteFinishedFileActor(this);
112
}
113
114
#ifdef DEBUG
115
mDatabase = nullptr;
116
#endif
117
}
118
};
119
120
} // namespace
121
122
class IDBDatabase::Observer final : public nsIObserver {
123
IDBDatabase* mWeakDatabase;
124
const uint64_t mWindowId;
125
126
public:
127
Observer(IDBDatabase* aDatabase, uint64_t aWindowId)
128
: mWeakDatabase(aDatabase), mWindowId(aWindowId) {
129
MOZ_ASSERT(NS_IsMainThread());
130
MOZ_ASSERT(aDatabase);
131
}
132
133
void Revoke() {
134
MOZ_ASSERT(NS_IsMainThread());
135
136
mWeakDatabase = nullptr;
137
}
138
139
NS_DECL_ISUPPORTS
140
141
private:
142
~Observer() {
143
MOZ_ASSERT(NS_IsMainThread());
144
MOZ_ASSERT(!mWeakDatabase);
145
}
146
147
NS_DECL_NSIOBSERVER
148
};
149
150
IDBDatabase::IDBDatabase(IDBOpenDBRequest* aRequest, IDBFactory* aFactory,
151
BackgroundDatabaseChild* aActor, DatabaseSpec* aSpec)
152
: DOMEventTargetHelper(aRequest),
153
mFactory(aFactory),
154
mSpec(aSpec),
155
mBackgroundActor(aActor),
156
mFileHandleDisabled(aRequest->IsFileHandleDisabled()),
157
mClosed(false),
158
mInvalidated(false),
159
mQuotaExceeded(false),
160
mIncreasedActiveDatabaseCount(false) {
161
MOZ_ASSERT(aRequest);
162
MOZ_ASSERT(aFactory);
163
aFactory->AssertIsOnOwningThread();
164
MOZ_ASSERT(aActor);
165
MOZ_ASSERT(aSpec);
166
}
167
168
IDBDatabase::~IDBDatabase() {
169
AssertIsOnOwningThread();
170
MOZ_ASSERT(!mBackgroundActor);
171
MOZ_ASSERT(!mIncreasedActiveDatabaseCount);
172
}
173
174
// static
175
already_AddRefed<IDBDatabase> IDBDatabase::Create(
176
IDBOpenDBRequest* aRequest, IDBFactory* aFactory,
177
BackgroundDatabaseChild* aActor, DatabaseSpec* aSpec) {
178
MOZ_ASSERT(aRequest);
179
MOZ_ASSERT(aFactory);
180
aFactory->AssertIsOnOwningThread();
181
MOZ_ASSERT(aActor);
182
MOZ_ASSERT(aSpec);
183
184
RefPtr<IDBDatabase> db = new IDBDatabase(aRequest, aFactory, aActor, aSpec);
185
186
if (NS_IsMainThread()) {
187
nsCOMPtr<nsPIDOMWindowInner> window =
188
do_QueryInterface(aFactory->GetParentObject());
189
if (window) {
190
uint64_t windowId = window->WindowID();
191
192
RefPtr<Observer> observer = new Observer(db, windowId);
193
194
nsCOMPtr<nsIObserverService> obsSvc = GetObserverService();
195
MOZ_ASSERT(obsSvc);
196
197
// This topic must be successfully registered.
198
MOZ_ALWAYS_SUCCEEDS(
199
obsSvc->AddObserver(observer, kWindowObserverTopic, false));
200
201
// These topics are not crucial.
202
if (NS_FAILED(obsSvc->AddObserver(observer, kCycleCollectionObserverTopic,
203
false)) ||
204
NS_FAILED(obsSvc->AddObserver(observer, kMemoryPressureObserverTopic,
205
false))) {
206
NS_WARNING("Failed to add additional memory observers!");
207
}
208
209
db->mObserver.swap(observer);
210
}
211
}
212
213
db->IncreaseActiveDatabaseCount();
214
215
return db.forget();
216
}
217
218
#ifdef DEBUG
219
220
void IDBDatabase::AssertIsOnOwningThread() const {
221
MOZ_ASSERT(mFactory);
222
mFactory->AssertIsOnOwningThread();
223
}
224
225
#endif // DEBUG
226
227
nsIEventTarget* IDBDatabase::EventTarget() const {
228
AssertIsOnOwningThread();
229
return Factory()->EventTarget();
230
}
231
232
void IDBDatabase::CloseInternal() {
233
AssertIsOnOwningThread();
234
235
if (!mClosed) {
236
mClosed = true;
237
238
ExpireFileActors(/* aExpireAll */ true);
239
240
if (mObserver) {
241
mObserver->Revoke();
242
243
nsCOMPtr<nsIObserverService> obsSvc = GetObserverService();
244
if (obsSvc) {
245
// These might not have been registered.
246
obsSvc->RemoveObserver(mObserver, kCycleCollectionObserverTopic);
247
obsSvc->RemoveObserver(mObserver, kMemoryPressureObserverTopic);
248
249
MOZ_ALWAYS_SUCCEEDS(
250
obsSvc->RemoveObserver(mObserver, kWindowObserverTopic));
251
}
252
253
mObserver = nullptr;
254
}
255
256
if (mBackgroundActor && !mInvalidated) {
257
mBackgroundActor->SendClose();
258
}
259
260
// Decrease the number of active databases right after the database is
261
// closed.
262
MaybeDecreaseActiveDatabaseCount();
263
}
264
}
265
266
void IDBDatabase::InvalidateInternal() {
267
AssertIsOnOwningThread();
268
269
InvalidateMutableFiles();
270
AbortTransactions(/* aShouldWarn */ true);
271
272
CloseInternal();
273
}
274
275
void IDBDatabase::EnterSetVersionTransaction(uint64_t aNewVersion) {
276
AssertIsOnOwningThread();
277
MOZ_ASSERT(aNewVersion);
278
MOZ_ASSERT(!RunningVersionChangeTransaction());
279
MOZ_ASSERT(mSpec);
280
MOZ_ASSERT(!mPreviousSpec);
281
282
mPreviousSpec = new DatabaseSpec(*mSpec);
283
284
mSpec->metadata().version() = aNewVersion;
285
}
286
287
void IDBDatabase::ExitSetVersionTransaction() {
288
AssertIsOnOwningThread();
289
290
if (mPreviousSpec) {
291
mPreviousSpec = nullptr;
292
}
293
}
294
295
void IDBDatabase::RevertToPreviousState() {
296
AssertIsOnOwningThread();
297
MOZ_ASSERT(RunningVersionChangeTransaction());
298
MOZ_ASSERT(mPreviousSpec);
299
300
// Hold the current spec alive until RefreshTransactionsSpecEnumerator has
301
// finished!
302
nsAutoPtr<DatabaseSpec> currentSpec(mSpec.forget());
303
304
mSpec = mPreviousSpec.forget();
305
306
RefreshSpec(/* aMayDelete */ true);
307
}
308
309
void IDBDatabase::RefreshSpec(bool aMayDelete) {
310
AssertIsOnOwningThread();
311
312
for (auto iter = mTransactions.Iter(); !iter.Done(); iter.Next()) {
313
RefPtr<IDBTransaction> transaction = iter.Get()->GetKey();
314
MOZ_ASSERT(transaction);
315
transaction->AssertIsOnOwningThread();
316
transaction->RefreshSpec(aMayDelete);
317
}
318
}
319
320
const nsString& IDBDatabase::Name() const {
321
AssertIsOnOwningThread();
322
MOZ_ASSERT(mSpec);
323
324
return mSpec->metadata().name();
325
}
326
327
uint64_t IDBDatabase::Version() const {
328
AssertIsOnOwningThread();
329
MOZ_ASSERT(mSpec);
330
331
return mSpec->metadata().version();
332
}
333
334
already_AddRefed<DOMStringList> IDBDatabase::ObjectStoreNames() const {
335
AssertIsOnOwningThread();
336
MOZ_ASSERT(mSpec);
337
338
return CreateSortedDOMStringList(
339
mSpec->objectStores(),
340
[](const auto& objectStore) { return objectStore.metadata().name(); });
341
}
342
343
already_AddRefed<Document> IDBDatabase::GetOwnerDocument() const {
344
if (nsPIDOMWindowInner* window = GetOwner()) {
345
nsCOMPtr<Document> doc = window->GetExtantDoc();
346
return doc.forget();
347
}
348
return nullptr;
349
}
350
351
already_AddRefed<IDBObjectStore> IDBDatabase::CreateObjectStore(
352
const nsAString& aName, const IDBObjectStoreParameters& aOptionalParameters,
353
ErrorResult& aRv) {
354
AssertIsOnOwningThread();
355
356
IDBTransaction* transaction = IDBTransaction::GetCurrent();
357
if (!transaction || transaction->Database() != this ||
358
transaction->GetMode() != IDBTransaction::Mode::VersionChange) {
359
aRv.Throw(NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR);
360
return nullptr;
361
}
362
363
if (!transaction->CanAcceptRequests()) {
364
aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
365
return nullptr;
366
}
367
368
KeyPath keyPath(0);
369
if (NS_FAILED(KeyPath::Parse(aOptionalParameters.mKeyPath, &keyPath))) {
370
aRv.Throw(NS_ERROR_DOM_SYNTAX_ERR);
371
return nullptr;
372
}
373
374
auto& objectStores = mSpec->objectStores();
375
const auto end = objectStores.cend();
376
const auto foundIt = std::find_if(
377
objectStores.cbegin(), end, [&aName](const auto& objectStore) {
378
return aName == objectStore.metadata().name();
379
});
380
if (foundIt != end) {
381
aRv.ThrowDOMException(
382
NS_ERROR_DOM_INDEXEDDB_CONSTRAINT_ERR,
383
nsPrintfCString("Object store named '%s' already exists at index '%zu'",
384
NS_ConvertUTF16toUTF8(aName).get(),
385
foundIt.GetIndex()));
386
return nullptr;
387
}
388
389
if (!keyPath.IsAllowedForObjectStore(aOptionalParameters.mAutoIncrement)) {
390
aRv.Throw(NS_ERROR_DOM_INVALID_ACCESS_ERR);
391
return nullptr;
392
}
393
394
const ObjectStoreSpec* oldSpecElements =
395
objectStores.IsEmpty() ? nullptr : objectStores.Elements();
396
397
ObjectStoreSpec* newSpec = objectStores.AppendElement();
398
newSpec->metadata() =
399
ObjectStoreMetadata(transaction->NextObjectStoreId(), nsString(aName),
400
keyPath, aOptionalParameters.mAutoIncrement);
401
402
if (oldSpecElements && oldSpecElements != objectStores.Elements()) {
403
MOZ_ASSERT(objectStores.Length() > 1);
404
405
// Array got moved, update the spec pointers for all live objectStores and
406
// indexes.
407
RefreshSpec(/* aMayDelete */ false);
408
}
409
410
RefPtr<IDBObjectStore> objectStore = transaction->CreateObjectStore(*newSpec);
411
MOZ_ASSERT(objectStore);
412
413
// Don't do this in the macro because we always need to increment the serial
414
// number to keep in sync with the parent.
415
const uint64_t requestSerialNumber = IDBRequest::NextSerialNumber();
416
417
IDB_LOG_MARK_CHILD_TRANSACTION_REQUEST(
418
"database(%s).transaction(%s).createObjectStore(%s)",
419
"IDBDatabase.createObjectStore()", transaction->LoggingSerialNumber(),
420
requestSerialNumber, IDB_LOG_STRINGIFY(this),
421
IDB_LOG_STRINGIFY(transaction), IDB_LOG_STRINGIFY(objectStore));
422
423
return objectStore.forget();
424
}
425
426
void IDBDatabase::DeleteObjectStore(const nsAString& aName, ErrorResult& aRv) {
427
AssertIsOnOwningThread();
428
429
IDBTransaction* transaction = IDBTransaction::GetCurrent();
430
if (!transaction || transaction->Database() != this ||
431
transaction->GetMode() != IDBTransaction::Mode::VersionChange) {
432
aRv.Throw(NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR);
433
return;
434
}
435
436
if (!transaction->CanAcceptRequests()) {
437
aRv.Throw(NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR);
438
return;
439
}
440
441
auto& specArray = mSpec->objectStores();
442
const auto end = specArray.end();
443
const auto foundIt =
444
std::find_if(specArray.begin(), end, [&aName](const auto& objectStore) {
445
const ObjectStoreMetadata& metadata = objectStore.metadata();
446
MOZ_ASSERT(metadata.id());
447
448
return aName == metadata.name();
449
});
450
451
if (foundIt == end) {
452
aRv.Throw(NS_ERROR_DOM_INDEXEDDB_NOT_FOUND_ERR);
453
return;
454
}
455
456
// Must do this before altering the metadata array!
457
transaction->DeleteObjectStore(foundIt->metadata().id());
458
459
specArray.RemoveElementAt(foundIt);
460
RefreshSpec(/* aMayDelete */ false);
461
462
// Don't do this in the macro because we always need to increment the serial
463
// number to keep in sync with the parent.
464
const uint64_t requestSerialNumber = IDBRequest::NextSerialNumber();
465
466
IDB_LOG_MARK_CHILD_TRANSACTION_REQUEST(
467
"database(%s).transaction(%s).deleteObjectStore(\"%s\")",
468
"IDBDatabase.deleteObjectStore()", transaction->LoggingSerialNumber(),
469
requestSerialNumber, IDB_LOG_STRINGIFY(this),
470
IDB_LOG_STRINGIFY(transaction), NS_ConvertUTF16toUTF8(aName).get());
471
}
472
473
already_AddRefed<IDBTransaction> IDBDatabase::Transaction(
474
JSContext* aCx, const StringOrStringSequence& aStoreNames,
475
IDBTransactionMode aMode, ErrorResult& aRv) {
476
AssertIsOnOwningThread();
477
478
if ((aMode == IDBTransactionMode::Readwriteflush ||
479
aMode == IDBTransactionMode::Cleanup) &&
480
!IndexedDatabaseManager::ExperimentalFeaturesEnabled()) {
481
// Pretend that this mode doesn't exist. We don't have a way to annotate
482
// certain enum values as depending on preferences so we just duplicate the
483
// normal exception generation here.
484
aRv.ThrowTypeError<MSG_INVALID_ENUM_VALUE>(
485
NS_LITERAL_STRING("Argument 2 of IDBDatabase.transaction"),
486
NS_LITERAL_STRING("readwriteflush"),
487
NS_LITERAL_STRING("IDBTransactionMode"));
488
return nullptr;
489
}
490
491
RefPtr<IDBTransaction> transaction;
492
aRv = Transaction(aCx, aStoreNames, aMode, getter_AddRefs(transaction));
493
if (NS_WARN_IF(aRv.Failed())) {
494
return nullptr;
495
}
496
497
return transaction.forget();
498
}
499
500
nsresult IDBDatabase::Transaction(JSContext* aCx,
501
const StringOrStringSequence& aStoreNames,
502
IDBTransactionMode aMode,
503
IDBTransaction** aTransaction) {
504
AssertIsOnOwningThread();
505
506
if (NS_WARN_IF((aMode == IDBTransactionMode::Readwriteflush ||
507
aMode == IDBTransactionMode::Cleanup) &&
508
!IndexedDatabaseManager::ExperimentalFeaturesEnabled())) {
509
IDB_REPORT_INTERNAL_ERR();
510
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
511
}
512
513
if (QuotaManager::IsShuttingDown()) {
514
IDB_REPORT_INTERNAL_ERR();
515
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
516
}
517
518
if (mClosed || RunningVersionChangeTransaction()) {
519
return NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR;
520
}
521
522
AutoTArray<nsString, 1> stackSequence;
523
524
if (aStoreNames.IsString()) {
525
stackSequence.AppendElement(aStoreNames.GetAsString());
526
} else {
527
MOZ_ASSERT(aStoreNames.IsStringSequence());
528
if (aStoreNames.GetAsStringSequence().IsEmpty()) {
529
return NS_ERROR_DOM_INVALID_ACCESS_ERR;
530
}
531
}
532
533
const nsTArray<nsString>& storeNames =
534
aStoreNames.IsString() ? stackSequence
535
: static_cast<const nsTArray<nsString>&>(
536
aStoreNames.GetAsStringSequence());
537
MOZ_ASSERT(!storeNames.IsEmpty());
538
539
const nsTArray<ObjectStoreSpec>& objectStores = mSpec->objectStores();
540
const uint32_t nameCount = storeNames.Length();
541
542
nsTArray<nsString> sortedStoreNames;
543
sortedStoreNames.SetCapacity(nameCount);
544
545
// While collecting object store names, check if the corresponding object
546
// stores actually exist.
547
const auto begin = objectStores.cbegin();
548
const auto end = objectStores.cend();
549
for (const auto& name : storeNames) {
550
const auto foundIt =
551
std::find_if(begin, end, [&name](const auto& objectStore) {
552
return objectStore.metadata().name() == name;
553
});
554
if (foundIt == end) {
555
return NS_ERROR_DOM_INDEXEDDB_NOT_FOUND_ERR;
556
}
557
558
sortedStoreNames.EmplaceBack(name);
559
}
560
sortedStoreNames.Sort();
561
562
// Remove any duplicates.
563
sortedStoreNames.SetLength(
564
std::unique(sortedStoreNames.begin(), sortedStoreNames.end()).GetIndex());
565
566
IDBTransaction::Mode mode;
567
switch (aMode) {
568
case IDBTransactionMode::Readonly:
569
mode = IDBTransaction::Mode::ReadOnly;
570
break;
571
case IDBTransactionMode::Readwrite:
572
if (mQuotaExceeded) {
573
mode = IDBTransaction::Mode::Cleanup;
574
mQuotaExceeded = false;
575
} else {
576
mode = IDBTransaction::Mode::ReadWrite;
577
}
578
break;
579
case IDBTransactionMode::Readwriteflush:
580
mode = IDBTransaction::Mode::ReadWriteFlush;
581
break;
582
case IDBTransactionMode::Cleanup:
583
mode = IDBTransaction::Mode::Cleanup;
584
mQuotaExceeded = false;
585
break;
586
case IDBTransactionMode::Versionchange:
587
return NS_ERROR_DOM_TYPE_ERR;
588
589
default:
590
MOZ_CRASH("Unknown mode!");
591
}
592
593
RefPtr<IDBTransaction> transaction =
594
IDBTransaction::Create(aCx, this, sortedStoreNames, mode);
595
if (NS_WARN_IF(!transaction)) {
596
IDB_REPORT_INTERNAL_ERR();
597
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
598
}
599
600
BackgroundTransactionChild* actor =
601
new BackgroundTransactionChild(transaction);
602
603
IDB_LOG_MARK_CHILD_TRANSACTION(
604
"database(%s).transaction(%s)", "IDBDatabase.transaction()",
605
transaction->LoggingSerialNumber(), IDB_LOG_STRINGIFY(this),
606
IDB_LOG_STRINGIFY(transaction));
607
608
MOZ_ALWAYS_TRUE(mBackgroundActor->SendPBackgroundIDBTransactionConstructor(
609
actor, sortedStoreNames, mode));
610
MOZ_ASSERT(actor->GetActorEventTarget(),
611
"The event target shall be inherited from it manager actor.");
612
613
transaction->SetBackgroundActor(actor);
614
615
if (mode == IDBTransaction::Mode::Cleanup) {
616
ExpireFileActors(/* aExpireAll */ true);
617
}
618
619
transaction.forget(aTransaction);
620
return NS_OK;
621
}
622
623
StorageType IDBDatabase::Storage() const {
624
AssertIsOnOwningThread();
625
MOZ_ASSERT(mSpec);
626
627
return PersistenceTypeToStorage(mSpec->metadata().persistenceType());
628
}
629
630
already_AddRefed<IDBRequest> IDBDatabase::CreateMutableFile(
631
JSContext* aCx, const nsAString& aName, const Optional<nsAString>& aType,
632
ErrorResult& aRv) {
633
AssertIsOnOwningThread();
634
635
if (aName.IsEmpty()) {
636
aRv.Throw(NS_ERROR_DOM_SYNTAX_ERR);
637
return nullptr;
638
}
639
640
if (QuotaManager::IsShuttingDown()) {
641
IDB_REPORT_INTERNAL_ERR();
642
aRv.Throw(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR);
643
return nullptr;
644
}
645
646
if (mClosed || mFileHandleDisabled) {
647
aRv.Throw(NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR);
648
return nullptr;
649
}
650
651
nsString type;
652
if (aType.WasPassed()) {
653
type = aType.Value();
654
}
655
656
CreateFileParams params(nsString(aName), type);
657
658
RefPtr<IDBRequest> request = IDBRequest::Create(aCx, this, nullptr);
659
MOZ_ASSERT(request);
660
661
BackgroundDatabaseRequestChild* actor =
662
new BackgroundDatabaseRequestChild(this, request);
663
664
IDB_LOG_MARK_CHILD_REQUEST(
665
"database(%s).createMutableFile(%s)", "IDBDatabase.createMutableFile()",
666
request->LoggingSerialNumber(), IDB_LOG_STRINGIFY(this),
667
NS_ConvertUTF16toUTF8(aName).get());
668
669
mBackgroundActor->SendPBackgroundIDBDatabaseRequestConstructor(actor, params);
670
671
MOZ_ASSERT(actor->GetActorEventTarget(),
672
"The event target shall be inherited from its manager actor.");
673
674
return request.forget();
675
}
676
677
void IDBDatabase::RegisterTransaction(IDBTransaction* aTransaction) {
678
AssertIsOnOwningThread();
679
MOZ_ASSERT(aTransaction);
680
aTransaction->AssertIsOnOwningThread();
681
MOZ_ASSERT(!mTransactions.Contains(aTransaction));
682
683
mTransactions.PutEntry(aTransaction);
684
}
685
686
void IDBDatabase::UnregisterTransaction(IDBTransaction* aTransaction) {
687
AssertIsOnOwningThread();
688
MOZ_ASSERT(aTransaction);
689
aTransaction->AssertIsOnOwningThread();
690
MOZ_ASSERT(mTransactions.Contains(aTransaction));
691
692
mTransactions.RemoveEntry(aTransaction);
693
}
694
695
void IDBDatabase::AbortTransactions(bool aShouldWarn) {
696
AssertIsOnOwningThread();
697
698
class MOZ_STACK_CLASS Helper final {
699
typedef AutoTArray<RefPtr<IDBTransaction>, 20> StrongTransactionArray;
700
typedef AutoTArray<IDBTransaction*, 20> WeakTransactionArray;
701
702
public:
703
static void AbortTransactions(IDBDatabase* aDatabase,
704
const bool aShouldWarn) {
705
MOZ_ASSERT(aDatabase);
706
aDatabase->AssertIsOnOwningThread();
707
708
nsTHashtable<nsPtrHashKey<IDBTransaction>>& transactionTable =
709
aDatabase->mTransactions;
710
711
if (!transactionTable.Count()) {
712
// Return early as an optimization, the remainder is a no-op in this
713
// case.
714
return;
715
}
716
717
StrongTransactionArray transactionsToAbort;
718
transactionsToAbort.SetCapacity(transactionTable.Count());
719
720
for (auto iter = transactionTable.Iter(); !iter.Done(); iter.Next()) {
721
IDBTransaction* transaction = iter.Get()->GetKey();
722
MOZ_ASSERT(transaction);
723
724
transaction->AssertIsOnOwningThread();
725
726
// Transactions that are already done can simply be ignored. Otherwise
727
// there is a race here and it's possible that the transaction has not
728
// been successfully committed yet so we will warn the user.
729
if (!transaction->IsFinished()) {
730
transactionsToAbort.AppendElement(transaction);
731
}
732
}
733
MOZ_ASSERT(transactionsToAbort.Length() <= transactionTable.Count());
734
735
if (transactionsToAbort.IsEmpty()) {
736
// Return early as an optimization, the remainder is a no-op in this
737
// case.
738
return;
739
}
740
741
// We want to abort transactions as soon as possible so we iterate the
742
// transactions once and abort them all first, collecting the transactions
743
// that need to have a warning issued along the way. Those that need a
744
// warning will be a subset of those that are aborted, so we don't need
745
// additional strong references here.
746
WeakTransactionArray transactionsThatNeedWarning;
747
748
for (RefPtr<IDBTransaction>& transaction : transactionsToAbort) {
749
MOZ_ASSERT(transaction);
750
MOZ_ASSERT(!transaction->IsFinished());
751
752
// We warn for any transactions that could have written data, but
753
// ignore read-only transactions.
754
if (aShouldWarn && transaction->IsWriteAllowed()) {
755
transactionsThatNeedWarning.AppendElement(transaction);
756
}
757
758
transaction->Abort(NS_ERROR_DOM_INDEXEDDB_ABORT_ERR);
759
}
760
761
static const char kWarningMessage[] =
762
"IndexedDBTransactionAbortNavigation";
763
764
for (IDBTransaction* transaction : transactionsThatNeedWarning) {
765
MOZ_ASSERT(transaction);
766
767
nsString filename;
768
uint32_t lineNo, column;
769
transaction->GetCallerLocation(filename, &lineNo, &column);
770
771
aDatabase->LogWarning(kWarningMessage, filename, lineNo, column);
772
}
773
}
774
};
775
776
Helper::AbortTransactions(this, aShouldWarn);
777
}
778
779
PBackgroundIDBDatabaseFileChild* IDBDatabase::GetOrCreateFileActorForBlob(
780
Blob* aBlob) {
781
AssertIsOnOwningThread();
782
MOZ_ASSERT(aBlob);
783
MOZ_ASSERT(mBackgroundActor);
784
785
// We use the File's nsIWeakReference as the key to the table because
786
// a) it is unique per blob, b) it is reference-counted so that we can
787
// guarantee that it stays alive, and c) it doesn't hold the actual File
788
// alive.
789
nsWeakPtr weakRef = do_GetWeakReference(aBlob);
790
MOZ_ASSERT(weakRef);
791
792
PBackgroundIDBDatabaseFileChild* actor = nullptr;
793
794
if (!mFileActors.Get(weakRef, &actor)) {
795
BlobImpl* blobImpl = aBlob->Impl();
796
MOZ_ASSERT(blobImpl);
797
798
PBackgroundChild* backgroundManager =
799
mBackgroundActor->Manager()->Manager();
800
MOZ_ASSERT(backgroundManager);
801
802
IPCBlob ipcBlob;
803
nsresult rv = IPCBlobUtils::Serialize(blobImpl, backgroundManager, ipcBlob);
804
if (NS_WARN_IF(NS_FAILED(rv))) {
805
return nullptr;
806
}
807
808
auto* dbFile = new DatabaseFile(this);
809
810
actor = mBackgroundActor->SendPBackgroundIDBDatabaseFileConstructor(
811
dbFile, ipcBlob);
812
if (NS_WARN_IF(!actor)) {
813
return nullptr;
814
}
815
816
MOZ_ASSERT(actor->GetActorEventTarget(),
817
"The event target shall be inherited from its manager actor.");
818
mFileActors.Put(weakRef, actor);
819
}
820
821
MOZ_ASSERT(actor);
822
823
return actor;
824
}
825
826
void IDBDatabase::NoteFinishedFileActor(
827
PBackgroundIDBDatabaseFileChild* aFileActor) {
828
AssertIsOnOwningThread();
829
MOZ_ASSERT(aFileActor);
830
831
for (auto iter = mFileActors.Iter(); !iter.Done(); iter.Next()) {
832
MOZ_ASSERT(iter.Key());
833
PBackgroundIDBDatabaseFileChild* actor = iter.Data();
834
MOZ_ASSERT(actor);
835
836
if (actor == aFileActor) {
837
iter.Remove();
838
}
839
}
840
}
841
842
void IDBDatabase::NoteActiveTransaction() {
843
AssertIsOnOwningThread();
844
MOZ_ASSERT(mFactory);
845
846
// Increase the number of active transactions.
847
mFactory->UpdateActiveTransactionCount(1);
848
}
849
850
void IDBDatabase::NoteInactiveTransaction() {
851
AssertIsOnOwningThread();
852
853
if (!mBackgroundActor || !mFileActors.Count()) {
854
MOZ_ASSERT(mFactory);
855
mFactory->UpdateActiveTransactionCount(-1);
856
return;
857
}
858
859
RefPtr<Runnable> runnable =
860
NewRunnableMethod("IDBDatabase::NoteInactiveTransactionDelayed", this,
861
&IDBDatabase::NoteInactiveTransactionDelayed);
862
MOZ_ASSERT(runnable);
863
864
if (!NS_IsMainThread()) {
865
// Wrap as a nsICancelableRunnable to make workers happy.
866
RefPtr<Runnable> cancelable = new CancelableRunnableWrapper(runnable);
867
cancelable.swap(runnable);
868
}
869
870
MOZ_ALWAYS_SUCCEEDS(
871
EventTarget()->Dispatch(runnable.forget(), NS_DISPATCH_NORMAL));
872
}
873
874
nsresult IDBDatabase::GetQuotaInfo(nsACString& aOrigin,
875
PersistenceType* aPersistenceType) {
876
using mozilla::dom::quota::QuotaManager;
877
878
MOZ_ASSERT(NS_IsMainThread(), "This can't work off the main thread!");
879
880
if (aPersistenceType) {
881
*aPersistenceType = mSpec->metadata().persistenceType();
882
MOZ_ASSERT(*aPersistenceType != PERSISTENCE_TYPE_INVALID);
883
}
884
885
PrincipalInfo* principalInfo = mFactory->GetPrincipalInfo();
886
MOZ_ASSERT(principalInfo);
887
888
switch (principalInfo->type()) {
889
case PrincipalInfo::TNullPrincipalInfo:
890
MOZ_CRASH("Is this needed?!");
891
892
case PrincipalInfo::TSystemPrincipalInfo:
893
QuotaManager::GetInfoForChrome(nullptr, nullptr, &aOrigin);
894
return NS_OK;
895
896
case PrincipalInfo::TContentPrincipalInfo: {
897
nsresult rv;
898
nsCOMPtr<nsIPrincipal> principal =
899
PrincipalInfoToPrincipal(*principalInfo, &rv);
900
if (NS_WARN_IF(NS_FAILED(rv))) {
901
return rv;
902
}
903
904
rv = QuotaManager::GetInfoFromPrincipal(principal, nullptr, nullptr,
905
&aOrigin);
906
if (NS_WARN_IF(NS_FAILED(rv))) {
907
return rv;
908
}
909
910
return NS_OK;
911
}
912
913
default:
914
MOZ_CRASH("Unknown PrincipalInfo type!");
915
}
916
917
MOZ_CRASH("Should never get here!");
918
}
919
920
void IDBDatabase::ExpireFileActors(bool aExpireAll) {
921
AssertIsOnOwningThread();
922
923
if (mBackgroundActor && mFileActors.Count()) {
924
for (auto iter = mFileActors.Iter(); !iter.Done(); iter.Next()) {
925
nsISupports* key = iter.Key();
926
PBackgroundIDBDatabaseFileChild* actor = iter.Data();
927
MOZ_ASSERT(key);
928
MOZ_ASSERT(actor);
929
930
bool shouldExpire = aExpireAll;
931
if (!shouldExpire) {
932
nsWeakPtr weakRef = do_QueryInterface(key);
933
MOZ_ASSERT(weakRef);
934
935
nsCOMPtr<nsISupports> referent = do_QueryReferent(weakRef);
936
shouldExpire = !referent;
937
}
938
939
if (shouldExpire) {
940
PBackgroundIDBDatabaseFileChild::Send__delete__(actor);
941
942
if (!aExpireAll) {
943
iter.Remove();
944
}
945
}
946
}
947
if (aExpireAll) {
948
mFileActors.Clear();
949
}
950
} else {
951
MOZ_ASSERT(!mFileActors.Count());
952
}
953
}
954
955
void IDBDatabase::NoteLiveMutableFile(IDBMutableFile* aMutableFile) {
956
AssertIsOnOwningThread();
957
MOZ_ASSERT(aMutableFile);
958
aMutableFile->AssertIsOnOwningThread();
959
MOZ_ASSERT(!mLiveMutableFiles.Contains(aMutableFile));
960
961
mLiveMutableFiles.AppendElement(aMutableFile);
962
}
963
964
void IDBDatabase::NoteFinishedMutableFile(IDBMutableFile* aMutableFile) {
965
AssertIsOnOwningThread();
966
MOZ_ASSERT(aMutableFile);
967
aMutableFile->AssertIsOnOwningThread();
968
969
// It's ok if this is called after we cleared the array, so don't assert that
970
// aMutableFile is in the list.
971
972
mLiveMutableFiles.RemoveElement(aMutableFile);
973
}
974
975
void IDBDatabase::InvalidateMutableFiles() {
976
AssertIsOnOwningThread();
977
978
if (!mLiveMutableFiles.IsEmpty()) {
979
for (uint32_t count = mLiveMutableFiles.Length(), index = 0; index < count;
980
index++) {
981
mLiveMutableFiles[index]->Invalidate();
982
}
983
984
mLiveMutableFiles.Clear();
985
}
986
}
987
988
void IDBDatabase::Invalidate() {
989
AssertIsOnOwningThread();
990
991
if (!mInvalidated) {
992
mInvalidated = true;
993
994
InvalidateInternal();
995
}
996
}
997
998
void IDBDatabase::NoteInactiveTransactionDelayed() {
999
ExpireFileActors(/* aExpireAll */ false);
1000
1001
MOZ_ASSERT(mFactory);
1002
mFactory->UpdateActiveTransactionCount(-1);
1003
}
1004
1005
void IDBDatabase::LogWarning(const char* aMessageName,
1006
const nsAString& aFilename, uint32_t aLineNumber,
1007
uint32_t aColumnNumber) {
1008
AssertIsOnOwningThread();
1009
MOZ_ASSERT(aMessageName);
1010
1011
ScriptErrorHelper::DumpLocalizedMessage(
1012
nsDependentCString(aMessageName), aFilename, aLineNumber, aColumnNumber,
1013
nsIScriptError::warningFlag, mFactory->IsChrome(),
1014
mFactory->InnerWindowID());
1015
}
1016
1017
NS_IMPL_ADDREF_INHERITED(IDBDatabase, DOMEventTargetHelper)
1018
NS_IMPL_RELEASE_INHERITED(IDBDatabase, DOMEventTargetHelper)
1019
1020
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(IDBDatabase)
1021
NS_INTERFACE_MAP_END_INHERITING(DOMEventTargetHelper)
1022
1023
NS_IMPL_CYCLE_COLLECTION_CLASS(IDBDatabase)
1024
1025
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(IDBDatabase,
1026
DOMEventTargetHelper)
1027
tmp->AssertIsOnOwningThread();
1028
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mFactory)
1029
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
1030
1031
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(IDBDatabase,
1032
DOMEventTargetHelper)
1033
tmp->AssertIsOnOwningThread();
1034
1035
// Don't unlink mFactory!
1036
1037
// We've been unlinked, at the very least we should be able to prevent further
1038
// transactions from starting and unblock any other SetVersion callers.
1039
tmp->CloseInternal();
1040
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
1041
1042
void IDBDatabase::DisconnectFromOwner() {
1043
InvalidateInternal();
1044
DOMEventTargetHelper::DisconnectFromOwner();
1045
}
1046
1047
void IDBDatabase::LastRelease() {
1048
AssertIsOnOwningThread();
1049
1050
CloseInternal();
1051
1052
ExpireFileActors(/* aExpireAll */ true);
1053
1054
if (mBackgroundActor) {
1055
mBackgroundActor->SendDeleteMeInternal();
1056
MOZ_ASSERT(!mBackgroundActor, "SendDeleteMeInternal should have cleared!");
1057
}
1058
}
1059
1060
nsresult IDBDatabase::PostHandleEvent(EventChainPostVisitor& aVisitor) {
1061
nsresult rv =
1062
IndexedDatabaseManager::CommonPostHandleEvent(aVisitor, mFactory);
1063
if (NS_WARN_IF(NS_FAILED(rv))) {
1064
return rv;
1065
}
1066
1067
return NS_OK;
1068
}
1069
1070
JSObject* IDBDatabase::WrapObject(JSContext* aCx,
1071
JS::Handle<JSObject*> aGivenProto) {
1072
return IDBDatabase_Binding::Wrap(aCx, this, aGivenProto);
1073
}
1074
1075
NS_IMETHODIMP
1076
CancelableRunnableWrapper::Run() {
1077
nsCOMPtr<nsIRunnable> runnable;
1078
mRunnable.swap(runnable);
1079
1080
if (runnable) {
1081
return runnable->Run();
1082
}
1083
1084
return NS_OK;
1085
}
1086
1087
nsresult CancelableRunnableWrapper::Cancel() {
1088
if (mRunnable) {
1089
mRunnable = nullptr;
1090
return NS_OK;
1091
}
1092
1093
return NS_ERROR_UNEXPECTED;
1094
}
1095
1096
NS_IMPL_ISUPPORTS(IDBDatabase::Observer, nsIObserver)
1097
1098
NS_IMETHODIMP
1099
IDBDatabase::Observer::Observe(nsISupports* aSubject, const char* aTopic,
1100
const char16_t* aData) {
1101
MOZ_ASSERT(NS_IsMainThread());
1102
MOZ_ASSERT(aTopic);
1103
1104
if (!strcmp(aTopic, kWindowObserverTopic)) {
1105
if (mWeakDatabase) {
1106
nsCOMPtr<nsISupportsPRUint64> supportsInt = do_QueryInterface(aSubject);
1107
MOZ_ASSERT(supportsInt);
1108
1109
uint64_t windowId;
1110
MOZ_ALWAYS_SUCCEEDS(supportsInt->GetData(&windowId));
1111
1112
if (windowId == mWindowId) {
1113
RefPtr<IDBDatabase> database = mWeakDatabase;
1114
mWeakDatabase = nullptr;
1115
1116
database->InvalidateInternal();
1117
}
1118
}
1119
1120
return NS_OK;
1121
}
1122
1123
if (!strcmp(aTopic, kCycleCollectionObserverTopic) ||
1124
!strcmp(aTopic, kMemoryPressureObserverTopic)) {
1125
if (mWeakDatabase) {
1126
RefPtr<IDBDatabase> database = mWeakDatabase;
1127
1128
database->ExpireFileActors(/* aExpireAll */ false);
1129
}
1130
1131
return NS_OK;
1132
}
1133
1134
NS_WARNING("Unknown observer topic!");
1135
return NS_OK;
1136
}
1137
1138
nsresult IDBDatabase::RenameObjectStore(int64_t aObjectStoreId,
1139
const nsAString& aName) {
1140
MOZ_ASSERT(mSpec);
1141
1142
nsTArray<ObjectStoreSpec>& objectStores = mSpec->objectStores();
1143
ObjectStoreSpec* foundObjectStoreSpec = nullptr;
1144
1145
// Find the matched object store spec and check if 'aName' is already used by
1146
// another object store.
1147
1148
for (const auto& objSpec : objectStores) {
1149
const bool idIsCurrent = objSpec.metadata().id() == aObjectStoreId;
1150
1151
if (idIsCurrent) {
1152
MOZ_ASSERT(!foundObjectStoreSpec);
1153
foundObjectStoreSpec = const_cast<ObjectStoreSpec*>(&objSpec);
1154
}
1155
1156
if (objSpec.metadata().name() == aName) {
1157
if (idIsCurrent) {
1158
return NS_OK;
1159
}
1160
return NS_ERROR_DOM_INDEXEDDB_RENAME_OBJECT_STORE_ERR;
1161
}
1162
}
1163
1164
MOZ_ASSERT(foundObjectStoreSpec);
1165
1166
// Update the name of the matched object store.
1167
foundObjectStoreSpec->metadata().name().Assign(aName);
1168
1169
return NS_OK;
1170
}
1171
1172
nsresult IDBDatabase::RenameIndex(int64_t aObjectStoreId, int64_t aIndexId,
1173
const nsAString& aName) {
1174
MOZ_ASSERT(mSpec);
1175
1176
nsTArray<ObjectStoreSpec>& objectStores = mSpec->objectStores();
1177
1178
ObjectStoreSpec* foundObjectStoreSpec = nullptr;
1179
// Find the matched index metadata and check if 'aName' is already used by
1180
// another index.
1181
for (uint32_t objCount = objectStores.Length(), objIndex = 0;
1182
objIndex < objCount; objIndex++) {
1183
const ObjectStoreSpec& objSpec = objectStores[objIndex];
1184
if (objSpec.metadata().id() == aObjectStoreId) {
1185
foundObjectStoreSpec = &objectStores[objIndex];
1186
break;
1187
}
1188
}
1189
1190
MOZ_ASSERT(foundObjectStoreSpec);
1191
1192
nsTArray<IndexMetadata>& indexes = foundObjectStoreSpec->indexes();
1193
IndexMetadata* foundIndexMetadata = nullptr;
1194
for (uint32_t idxCount = indexes.Length(), idxIndex = 0; idxIndex < idxCount;
1195
idxIndex++) {
1196
const IndexMetadata& metadata = indexes[idxIndex];
1197
if (metadata.id() == aIndexId) {
1198
MOZ_ASSERT(!foundIndexMetadata);
1199
foundIndexMetadata = &indexes[idxIndex];
1200
continue;
1201
}
1202
if (aName == metadata.name()) {
1203
return NS_ERROR_DOM_INDEXEDDB_RENAME_INDEX_ERR;
1204
}
1205
}
1206
1207
MOZ_ASSERT(foundIndexMetadata);
1208
1209
// Update the name of the matched object store.
1210
foundIndexMetadata->name() = nsString(aName);
1211
1212
return NS_OK;
1213
}
1214
1215
void IDBDatabase::IncreaseActiveDatabaseCount() {
1216
AssertIsOnOwningThread();
1217
MOZ_ASSERT(mFactory);
1218
MOZ_ASSERT(!mIncreasedActiveDatabaseCount);
1219
1220
mFactory->UpdateActiveDatabaseCount(1);
1221
mIncreasedActiveDatabaseCount = true;
1222
}
1223
1224
void IDBDatabase::MaybeDecreaseActiveDatabaseCount() {
1225
AssertIsOnOwningThread();
1226
1227
if (mIncreasedActiveDatabaseCount) {
1228
// Decrease the number of active databases.
1229
MOZ_ASSERT(mFactory);
1230
mFactory->UpdateActiveDatabaseCount(-1);
1231
mIncreasedActiveDatabaseCount = false;
1232
}
1233
}
1234
1235
} // namespace dom
1236
} // namespace mozilla