forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mozStorageConnection.cpp
2212 lines (1891 loc) · 70.4 KB
/
mozStorageConnection.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: sw=2 ts=2 et lcs=trail\:.,tab\:>~ :
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <stdio.h>
#include "nsError.h"
#include "nsThreadUtils.h"
#include "nsIFile.h"
#include "nsIFileURL.h"
#include "nsIXPConnect.h"
#include "mozilla/Telemetry.h"
#include "mozilla/Mutex.h"
#include "mozilla/CondVar.h"
#include "mozilla/Attributes.h"
#include "mozilla/ErrorNames.h"
#include "mozilla/Unused.h"
#include "mozilla/dom/quota/QuotaObject.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/StaticPrefs_storage.h"
#include "mozIStorageCompletionCallback.h"
#include "mozIStorageFunction.h"
#include "mozStorageAsyncStatementExecution.h"
#include "mozStorageSQLFunctions.h"
#include "mozStorageConnection.h"
#include "mozStorageService.h"
#include "mozStorageStatement.h"
#include "mozStorageAsyncStatement.h"
#include "mozStorageArgValueArray.h"
#include "mozStoragePrivateHelpers.h"
#include "mozStorageStatementData.h"
#include "StorageBaseStatementInternal.h"
#include "SQLCollations.h"
#include "FileSystemModule.h"
#include "mozStorageHelper.h"
#include "GeckoProfiler.h"
#include "mozilla/Logging.h"
#include "mozilla/Printf.h"
#include "nsProxyRelease.h"
#include <algorithm>
#define MIN_AVAILABLE_BYTES_PER_CHUNKED_GROWTH 524288000 // 500 MiB
// Maximum size of the pages cache per connection.
#define MAX_CACHE_SIZE_KIBIBYTES 2048 // 2 MiB
mozilla::LazyLogModule gStorageLog("mozStorage");
// Checks that the protected code is running on the main-thread only if the
// connection was also opened on it.
#ifdef DEBUG
# define CHECK_MAINTHREAD_ABUSE() \
do { \
nsCOMPtr<nsIThread> mainThread = do_GetMainThread(); \
NS_WARNING_ASSERTION( \
threadOpenedOn == mainThread || !NS_IsMainThread(), \
"Using Storage synchronous API on main-thread, but " \
"the connection was " \
"opened on another thread."); \
} while (0)
#else
# define CHECK_MAINTHREAD_ABUSE() \
do { /* Nothing */ \
} while (0)
#endif
namespace mozilla::storage {
using mozilla::dom::quota::QuotaObject;
const char* GetVFSName(bool);
namespace {
int nsresultToSQLiteResult(nsresult aXPCOMResultCode) {
if (NS_SUCCEEDED(aXPCOMResultCode)) {
return SQLITE_OK;
}
switch (aXPCOMResultCode) {
case NS_ERROR_FILE_CORRUPTED:
return SQLITE_CORRUPT;
case NS_ERROR_FILE_ACCESS_DENIED:
return SQLITE_CANTOPEN;
case NS_ERROR_STORAGE_BUSY:
return SQLITE_BUSY;
case NS_ERROR_FILE_IS_LOCKED:
return SQLITE_LOCKED;
case NS_ERROR_FILE_READ_ONLY:
return SQLITE_READONLY;
case NS_ERROR_STORAGE_IOERR:
return SQLITE_IOERR;
case NS_ERROR_FILE_NO_DEVICE_SPACE:
return SQLITE_FULL;
case NS_ERROR_OUT_OF_MEMORY:
return SQLITE_NOMEM;
case NS_ERROR_UNEXPECTED:
return SQLITE_MISUSE;
case NS_ERROR_ABORT:
return SQLITE_ABORT;
case NS_ERROR_STORAGE_CONSTRAINT:
return SQLITE_CONSTRAINT;
default:
return SQLITE_ERROR;
}
MOZ_MAKE_COMPILER_ASSUME_IS_UNREACHABLE("Must return in switch above!");
}
////////////////////////////////////////////////////////////////////////////////
//// Variant Specialization Functions (variantToSQLiteT)
int sqlite3_T_int(sqlite3_context* aCtx, int aValue) {
::sqlite3_result_int(aCtx, aValue);
return SQLITE_OK;
}
int sqlite3_T_int64(sqlite3_context* aCtx, sqlite3_int64 aValue) {
::sqlite3_result_int64(aCtx, aValue);
return SQLITE_OK;
}
int sqlite3_T_double(sqlite3_context* aCtx, double aValue) {
::sqlite3_result_double(aCtx, aValue);
return SQLITE_OK;
}
int sqlite3_T_text(sqlite3_context* aCtx, const nsCString& aValue) {
::sqlite3_result_text(aCtx, aValue.get(), aValue.Length(), SQLITE_TRANSIENT);
return SQLITE_OK;
}
int sqlite3_T_text16(sqlite3_context* aCtx, const nsString& aValue) {
::sqlite3_result_text16(
aCtx, aValue.get(),
aValue.Length() * sizeof(char16_t), // Number of bytes.
SQLITE_TRANSIENT);
return SQLITE_OK;
}
int sqlite3_T_null(sqlite3_context* aCtx) {
::sqlite3_result_null(aCtx);
return SQLITE_OK;
}
int sqlite3_T_blob(sqlite3_context* aCtx, const void* aData, int aSize) {
::sqlite3_result_blob(aCtx, aData, aSize, free);
return SQLITE_OK;
}
#include "variantToSQLiteT_impl.h"
////////////////////////////////////////////////////////////////////////////////
//// Modules
struct Module {
const char* name;
int (*registerFunc)(sqlite3*, const char*);
};
Module gModules[] = {{"filesystem", RegisterFileSystemModule}};
////////////////////////////////////////////////////////////////////////////////
//// Local Functions
int tracefunc(unsigned aReason, void* aClosure, void* aP, void* aX) {
switch (aReason) {
case SQLITE_TRACE_STMT: {
// aP is a pointer to the prepared statement.
sqlite3_stmt* stmt = static_cast<sqlite3_stmt*>(aP);
// aX is a pointer to a string containing the unexpanded SQL or a comment,
// starting with "--"" in case of a trigger.
char* expanded = static_cast<char*>(aX);
// Simulate what sqlite_trace was doing.
if (!::strncmp(expanded, "--", 2)) {
MOZ_LOG(gStorageLog, LogLevel::Debug,
("TRACE_STMT on %p: '%s'", aClosure, expanded));
} else {
char* sql = ::sqlite3_expanded_sql(stmt);
MOZ_LOG(gStorageLog, LogLevel::Debug,
("TRACE_STMT on %p: '%s'", aClosure, sql));
::sqlite3_free(sql);
}
break;
}
case SQLITE_TRACE_PROFILE: {
// aX is pointer to a 64bit integer containing nanoseconds it took to
// execute the last command.
sqlite_int64 time = *(static_cast<sqlite_int64*>(aX)) / 1000000;
if (time > 0) {
MOZ_LOG(gStorageLog, LogLevel::Debug,
("TRACE_TIME on %p: %lldms", aClosure, time));
}
break;
}
}
return 0;
}
void basicFunctionHelper(sqlite3_context* aCtx, int aArgc,
sqlite3_value** aArgv) {
void* userData = ::sqlite3_user_data(aCtx);
mozIStorageFunction* func = static_cast<mozIStorageFunction*>(userData);
RefPtr<ArgValueArray> arguments(new ArgValueArray(aArgc, aArgv));
if (!arguments) return;
nsCOMPtr<nsIVariant> result;
nsresult rv = func->OnFunctionCall(arguments, getter_AddRefs(result));
if (NS_FAILED(rv)) {
nsAutoCString errorMessage;
GetErrorName(rv, errorMessage);
errorMessage.InsertLiteral("User function returned ", 0);
errorMessage.Append('!');
NS_WARNING(errorMessage.get());
::sqlite3_result_error(aCtx, errorMessage.get(), -1);
::sqlite3_result_error_code(aCtx, nsresultToSQLiteResult(rv));
return;
}
int retcode = variantToSQLiteT(aCtx, result);
if (retcode != SQLITE_OK) {
NS_WARNING("User function returned invalid data type!");
::sqlite3_result_error(aCtx, "User function returned invalid data type",
-1);
}
}
/**
* This code is heavily based on the sample at:
* http://www.sqlite.org/unlock_notify.html
*/
class UnlockNotification {
public:
UnlockNotification()
: mMutex("UnlockNotification mMutex"),
mCondVar(mMutex, "UnlockNotification condVar"),
mSignaled(false) {}
void Wait() {
MutexAutoLock lock(mMutex);
while (!mSignaled) {
(void)mCondVar.Wait();
}
}
void Signal() {
MutexAutoLock lock(mMutex);
mSignaled = true;
(void)mCondVar.Notify();
}
private:
Mutex mMutex;
CondVar mCondVar;
bool mSignaled;
};
void UnlockNotifyCallback(void** aArgs, int aArgsSize) {
for (int i = 0; i < aArgsSize; i++) {
UnlockNotification* notification =
static_cast<UnlockNotification*>(aArgs[i]);
notification->Signal();
}
}
int WaitForUnlockNotify(sqlite3* aDatabase) {
UnlockNotification notification;
int srv =
::sqlite3_unlock_notify(aDatabase, UnlockNotifyCallback, ¬ification);
MOZ_ASSERT(srv == SQLITE_LOCKED || srv == SQLITE_OK);
if (srv == SQLITE_OK) {
notification.Wait();
}
return srv;
}
////////////////////////////////////////////////////////////////////////////////
//// Local Classes
class AsyncCloseConnection final : public Runnable {
public:
AsyncCloseConnection(Connection* aConnection, sqlite3* aNativeConnection,
nsIRunnable* aCallbackEvent)
: Runnable("storage::AsyncCloseConnection"),
mConnection(aConnection),
mNativeConnection(aNativeConnection),
mCallbackEvent(aCallbackEvent) {}
NS_IMETHOD Run() override {
// This code is executed on the background thread
MOZ_ASSERT(NS_GetCurrentThread() != mConnection->threadOpenedOn);
nsCOMPtr<nsIRunnable> event =
NewRunnableMethod("storage::Connection::shutdownAsyncThread",
mConnection, &Connection::shutdownAsyncThread);
MOZ_ALWAYS_SUCCEEDS(NS_DispatchToMainThread(event));
// Internal close.
(void)mConnection->internalClose(mNativeConnection);
// Callback
if (mCallbackEvent) {
nsCOMPtr<nsIThread> thread;
(void)NS_GetMainThread(getter_AddRefs(thread));
(void)thread->Dispatch(mCallbackEvent, NS_DISPATCH_NORMAL);
}
return NS_OK;
}
~AsyncCloseConnection() override {
NS_ReleaseOnMainThread("AsyncCloseConnection::mConnection",
mConnection.forget());
NS_ReleaseOnMainThread("AsyncCloseConnection::mCallbackEvent",
mCallbackEvent.forget());
}
private:
RefPtr<Connection> mConnection;
sqlite3* mNativeConnection;
nsCOMPtr<nsIRunnable> mCallbackEvent;
};
/**
* An event used to initialize the clone of a connection.
*
* Must be executed on the clone's async execution thread.
*/
class AsyncInitializeClone final : public Runnable {
public:
/**
* @param aConnection The connection being cloned.
* @param aClone The clone.
* @param aReadOnly If |true|, the clone is read only.
* @param aCallback A callback to trigger once initialization
* is complete. This event will be called on
* aClone->threadOpenedOn.
*/
AsyncInitializeClone(Connection* aConnection, Connection* aClone,
const bool aReadOnly,
mozIStorageCompletionCallback* aCallback)
: Runnable("storage::AsyncInitializeClone"),
mConnection(aConnection),
mClone(aClone),
mReadOnly(aReadOnly),
mCallback(aCallback) {
MOZ_ASSERT(NS_IsMainThread());
}
NS_IMETHOD Run() override {
MOZ_ASSERT(!NS_IsMainThread());
nsresult rv = mConnection->initializeClone(mClone, mReadOnly);
if (NS_FAILED(rv)) {
return Dispatch(rv, nullptr);
}
return Dispatch(NS_OK,
NS_ISUPPORTS_CAST(mozIStorageAsyncConnection*, mClone));
}
private:
nsresult Dispatch(nsresult aResult, nsISupports* aValue) {
RefPtr<CallbackComplete> event =
new CallbackComplete(aResult, aValue, mCallback.forget());
return mClone->threadOpenedOn->Dispatch(event, NS_DISPATCH_NORMAL);
}
~AsyncInitializeClone() override {
nsCOMPtr<nsIThread> thread;
DebugOnly<nsresult> rv = NS_GetMainThread(getter_AddRefs(thread));
MOZ_ASSERT(NS_SUCCEEDED(rv));
// Handle ambiguous nsISupports inheritance.
NS_ProxyRelease("AsyncInitializeClone::mConnection", thread,
mConnection.forget());
NS_ProxyRelease("AsyncInitializeClone::mClone", thread, mClone.forget());
// Generally, the callback will be released by CallbackComplete.
// However, if for some reason Run() is not executed, we still
// need to ensure that it is released here.
NS_ProxyRelease("AsyncInitializeClone::mCallback", thread,
mCallback.forget());
}
RefPtr<Connection> mConnection;
RefPtr<Connection> mClone;
const bool mReadOnly;
nsCOMPtr<mozIStorageCompletionCallback> mCallback;
};
/**
* A listener for async connection closing.
*/
class CloseListener final : public mozIStorageCompletionCallback {
public:
NS_DECL_ISUPPORTS
CloseListener() : mClosed(false) {}
NS_IMETHOD Complete(nsresult, nsISupports*) override {
mClosed = true;
return NS_OK;
}
bool mClosed;
private:
~CloseListener() = default;
};
NS_IMPL_ISUPPORTS(CloseListener, mozIStorageCompletionCallback)
} // namespace
////////////////////////////////////////////////////////////////////////////////
//// Connection
Connection::Connection(Service* aService, int aFlags,
ConnectionOperation aSupportedOperations,
bool aIgnoreLockingMode)
: sharedAsyncExecutionMutex("Connection::sharedAsyncExecutionMutex"),
sharedDBMutex("Connection::sharedDBMutex"),
threadOpenedOn(do_GetCurrentThread()),
mDBConn(nullptr),
mAsyncExecutionThreadShuttingDown(false),
mConnectionClosed(false),
mDefaultTransactionType(mozIStorageConnection::TRANSACTION_DEFERRED),
mDestroying(false),
mProgressHandler(nullptr),
mFlags(aFlags),
mIgnoreLockingMode(aIgnoreLockingMode),
mStorageService(aService),
mSupportedOperations(aSupportedOperations) {
MOZ_ASSERT(!mIgnoreLockingMode || mFlags & SQLITE_OPEN_READONLY,
"Can't ignore locking for a non-readonly connection!");
mStorageService->registerConnection(this);
}
Connection::~Connection() {
// Failsafe Close() occurs in our custom Release method because of
// complications related to Close() potentially invoking AsyncClose() which
// will increment our refcount.
MOZ_ASSERT(!mAsyncExecutionThread,
"The async thread has not been shutdown properly!");
}
NS_IMPL_ADDREF(Connection)
NS_INTERFACE_MAP_BEGIN(Connection)
NS_INTERFACE_MAP_ENTRY(mozIStorageAsyncConnection)
NS_INTERFACE_MAP_ENTRY(nsIInterfaceRequestor)
NS_INTERFACE_MAP_ENTRY(mozIStorageConnection)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, mozIStorageConnection)
NS_INTERFACE_MAP_END
// This is identical to what NS_IMPL_RELEASE provides, but with the
// extra |1 == count| case.
NS_IMETHODIMP_(MozExternalRefCountType) Connection::Release(void) {
MOZ_ASSERT(0 != mRefCnt, "dup release");
nsrefcnt count = --mRefCnt;
NS_LOG_RELEASE(this, count, "Connection");
if (1 == count) {
// If the refcount went to 1, the single reference must be from
// gService->mConnections (in class |Service|). And the code calling
// Release is either:
// - The "user" code that had created the connection, releasing on any
// thread.
// - One of Service's getConnections() callers had acquired a strong
// reference to the Connection that out-lived the last "user" reference,
// and now that just got dropped. Note that this reference could be
// getting dropped on the main thread or Connection->threadOpenedOn
// (because of the NewRunnableMethod used by minimizeMemory).
//
// Either way, we should now perform our failsafe Close() and unregister.
// However, we only want to do this once, and the reality is that our
// refcount could go back up above 1 and down again at any time if we are
// off the main thread and getConnections() gets called on the main thread,
// so we use an atomic here to do this exactly once.
if (mDestroying.compareExchange(false, true)) {
// Close the connection, dispatching to the opening thread if we're not
// on that thread already and that thread is still accepting runnables.
// We do this because it's possible we're on the main thread because of
// getConnections(), and we REALLY don't want to transfer I/O to the main
// thread if we can avoid it.
if (threadOpenedOn->IsOnCurrentThread()) {
// This could cause SpinningSynchronousClose() to be invoked and AddRef
// triggered for AsyncCloseConnection's strong ref if the conn was ever
// use for async purposes. (Main-thread only, though.)
Unused << synchronousClose();
} else {
nsCOMPtr<nsIRunnable> event =
NewRunnableMethod("storage::Connection::synchronousClose", this,
&Connection::synchronousClose);
if (NS_FAILED(
threadOpenedOn->Dispatch(event.forget(), NS_DISPATCH_NORMAL))) {
// The target thread was dead and so we've just leaked our runnable.
// This should not happen because our non-main-thread consumers should
// be explicitly closing their connections, not relying on us to close
// them for them. (It's okay to let a statement go out of scope for
// automatic cleanup, but not a Connection.)
MOZ_ASSERT(false,
"Leaked Connection::synchronousClose(), ownership fail.");
Unused << synchronousClose();
}
}
// This will drop its strong reference right here, right now.
mStorageService->unregisterConnection(this);
}
} else if (0 == count) {
mRefCnt = 1; /* stabilize */
#if 0 /* enable this to find non-threadsafe destructors: */
NS_ASSERT_OWNINGTHREAD(Connection);
#endif
delete (this);
return 0;
}
return count;
}
int32_t Connection::getSqliteRuntimeStatus(int32_t aStatusOption,
int32_t* aMaxValue) {
MOZ_ASSERT(connectionReady(), "A connection must exist at this point");
int curr = 0, max = 0;
DebugOnly<int> rc =
::sqlite3_db_status(mDBConn, aStatusOption, &curr, &max, 0);
MOZ_ASSERT(NS_SUCCEEDED(convertResultCode(rc)));
if (aMaxValue) *aMaxValue = max;
return curr;
}
nsIEventTarget* Connection::getAsyncExecutionTarget() {
NS_ENSURE_TRUE(threadOpenedOn == NS_GetCurrentThread(), nullptr);
// Don't return the asynchronous thread if we are shutting down.
if (mAsyncExecutionThreadShuttingDown) {
return nullptr;
}
// Create the async thread if there's none yet.
if (!mAsyncExecutionThread) {
static nsThreadPoolNaming naming;
nsresult rv = NS_NewNamedThread(naming.GetNextThreadName("mozStorage"),
getter_AddRefs(mAsyncExecutionThread));
if (NS_FAILED(rv)) {
NS_WARNING("Failed to create async thread.");
return nullptr;
}
mAsyncExecutionThread->SetNameForWakeupTelemetry("mozStorage (all)"_ns);
}
return mAsyncExecutionThread;
}
nsresult Connection::initialize() {
NS_ASSERTION(!connectionReady(),
"Initialize called on already opened database!");
MOZ_ASSERT(!mIgnoreLockingMode, "Can't ignore locking on an in-memory db.");
AUTO_PROFILER_LABEL("Connection::initialize", OTHER);
// in memory database requested, sqlite uses a magic file name
int srv = ::sqlite3_open_v2(":memory:", &mDBConn, mFlags, GetVFSName(true));
if (srv != SQLITE_OK) {
mDBConn = nullptr;
return convertResultCode(srv);
}
#ifdef MOZ_SQLITE_FTS3_TOKENIZER
srv =
::sqlite3_db_config(mDBConn, SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
MOZ_ASSERT(srv == SQLITE_OK,
"SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER should be enabled");
#endif
// Do not set mDatabaseFile or mFileURL here since this is a "memory"
// database.
nsresult rv = initializeInternal();
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
nsresult Connection::initialize(nsIFile* aDatabaseFile) {
NS_ASSERTION(aDatabaseFile, "Passed null file!");
NS_ASSERTION(!connectionReady(),
"Initialize called on already opened database!");
AUTO_PROFILER_LABEL("Connection::initialize", OTHER);
// Do not set mFileURL here since this is database does not have an associated
// URL.
mDatabaseFile = aDatabaseFile;
nsAutoString path;
nsresult rv = aDatabaseFile->GetPath(path);
NS_ENSURE_SUCCESS(rv, rv);
#ifdef XP_WIN
static const char* sIgnoreLockingVFS = "win32-none";
#else
static const char* sIgnoreLockingVFS = "unix-none";
#endif
bool exclusive = StaticPrefs::storage_sqlite_exclusiveLock_enabled();
int srv;
if (mIgnoreLockingMode) {
exclusive = false;
srv = ::sqlite3_open_v2(NS_ConvertUTF16toUTF8(path).get(), &mDBConn, mFlags,
sIgnoreLockingVFS);
} else {
srv = ::sqlite3_open_v2(NS_ConvertUTF16toUTF8(path).get(), &mDBConn, mFlags,
GetVFSName(exclusive));
if (exclusive && (srv == SQLITE_LOCKED || srv == SQLITE_BUSY)) {
// Retry without trying to get an exclusive lock.
exclusive = false;
srv = ::sqlite3_open_v2(NS_ConvertUTF16toUTF8(path).get(), &mDBConn,
mFlags, GetVFSName(false));
}
}
if (srv != SQLITE_OK) {
mDBConn = nullptr;
return convertResultCode(srv);
}
rv = initializeInternal();
if (exclusive &&
(rv == NS_ERROR_STORAGE_BUSY || rv == NS_ERROR_FILE_IS_LOCKED)) {
// Usually SQLite will fail to acquire an exclusive lock on opening, but in
// some cases it may successfully open the database and then lock on the
// first query execution. When initializeInternal fails it closes the
// connection, so we can try to restart it in non-exclusive mode.
srv = ::sqlite3_open_v2(NS_ConvertUTF16toUTF8(path).get(), &mDBConn, mFlags,
GetVFSName(false));
if (srv == SQLITE_OK) {
rv = initializeInternal();
}
}
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
nsresult Connection::initialize(nsIFileURL* aFileURL) {
NS_ASSERTION(aFileURL, "Passed null file URL!");
NS_ASSERTION(!connectionReady(),
"Initialize called on already opened database!");
AUTO_PROFILER_LABEL("Connection::initialize", OTHER);
nsCOMPtr<nsIFile> databaseFile;
nsresult rv = aFileURL->GetFile(getter_AddRefs(databaseFile));
NS_ENSURE_SUCCESS(rv, rv);
// Set both mDatabaseFile and mFileURL here.
mFileURL = aFileURL;
mDatabaseFile = databaseFile;
nsAutoCString spec;
rv = aFileURL->GetSpec(spec);
NS_ENSURE_SUCCESS(rv, rv);
bool exclusive = StaticPrefs::storage_sqlite_exclusiveLock_enabled();
int srv =
::sqlite3_open_v2(spec.get(), &mDBConn, mFlags, GetVFSName(exclusive));
if (srv != SQLITE_OK) {
mDBConn = nullptr;
return convertResultCode(srv);
}
rv = initializeInternal();
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
nsresult Connection::initializeInternal() {
MOZ_ASSERT(mDBConn);
auto guard = MakeScopeExit([&]() { initializeFailed(); });
mConnectionClosed = false;
#ifdef MOZ_SQLITE_FTS3_TOKENIZER
DebugOnly<int> srv2 =
::sqlite3_db_config(mDBConn, SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
MOZ_ASSERT(srv2 == SQLITE_OK,
"SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER should be enabled");
#endif
if (mFileURL) {
const char* dbPath = ::sqlite3_db_filename(mDBConn, "main");
MOZ_ASSERT(dbPath);
const char* telemetryFilename =
::sqlite3_uri_parameter(dbPath, "telemetryFilename");
if (telemetryFilename) {
if (NS_WARN_IF(*telemetryFilename == '\0')) {
return NS_ERROR_INVALID_ARG;
}
mTelemetryFilename = telemetryFilename;
}
}
if (mTelemetryFilename.IsEmpty()) {
mTelemetryFilename = getFilename();
MOZ_ASSERT(!mTelemetryFilename.IsEmpty());
}
// Properly wrap the database handle's mutex.
sharedDBMutex.initWithMutex(sqlite3_db_mutex(mDBConn));
// SQLite tracing can slow down queries (especially long queries)
// significantly. Don't trace unless the user is actively monitoring SQLite.
if (MOZ_LOG_TEST(gStorageLog, LogLevel::Debug)) {
::sqlite3_trace_v2(mDBConn, SQLITE_TRACE_STMT | SQLITE_TRACE_PROFILE,
tracefunc, this);
MOZ_LOG(
gStorageLog, LogLevel::Debug,
("Opening connection to '%s' (%p)", mTelemetryFilename.get(), this));
}
int64_t pageSize = Service::kDefaultPageSize;
// Set page_size to the preferred default value. This is effective only if
// the database has just been created, otherwise, if the database does not
// use WAL journal mode, a VACUUM operation will updated its page_size.
nsAutoCString pageSizeQuery(MOZ_STORAGE_UNIQUIFY_QUERY_STR
"PRAGMA page_size = ");
pageSizeQuery.AppendInt(pageSize);
int srv = executeSql(mDBConn, pageSizeQuery.get());
if (srv != SQLITE_OK) {
return convertResultCode(srv);
}
// Setting the cache_size forces the database open, verifying if it is valid
// or corrupt. So this is executed regardless it being actually needed.
// The cache_size is calculated from the actual page_size, to save memory.
nsAutoCString cacheSizeQuery(MOZ_STORAGE_UNIQUIFY_QUERY_STR
"PRAGMA cache_size = ");
cacheSizeQuery.AppendInt(-MAX_CACHE_SIZE_KIBIBYTES);
srv = executeSql(mDBConn, cacheSizeQuery.get());
if (srv != SQLITE_OK) {
return convertResultCode(srv);
}
// Register our built-in SQL functions.
srv = registerFunctions(mDBConn);
if (srv != SQLITE_OK) {
return convertResultCode(srv);
}
// Register our built-in SQL collating sequences.
srv = registerCollations(mDBConn, mStorageService);
if (srv != SQLITE_OK) {
return convertResultCode(srv);
}
// Set the default synchronous value. Each consumer can switch this
// accordingly to their needs.
#if defined(ANDROID)
// Android prefers synchronous = OFF for performance reasons.
Unused << ExecuteSimpleSQL("PRAGMA synchronous = OFF;"_ns);
#else
// Normal is the suggested value for WAL journals.
Unused << ExecuteSimpleSQL("PRAGMA synchronous = NORMAL;"_ns);
#endif
// Initialization succeeded, we can stop guarding for failures.
guard.release();
return NS_OK;
}
nsresult Connection::initializeOnAsyncThread(nsIFile* aStorageFile) {
MOZ_ASSERT(threadOpenedOn != NS_GetCurrentThread());
nsresult rv = aStorageFile ? initialize(aStorageFile) : initialize();
if (NS_FAILED(rv)) {
// Shutdown the async thread, since initialization failed.
MutexAutoLock lockedScope(sharedAsyncExecutionMutex);
mAsyncExecutionThreadShuttingDown = true;
nsCOMPtr<nsIRunnable> event =
NewRunnableMethod("Connection::shutdownAsyncThread", this,
&Connection::shutdownAsyncThread);
Unused << NS_DispatchToMainThread(event);
}
return rv;
}
void Connection::initializeFailed() {
{
MutexAutoLock lockedScope(sharedAsyncExecutionMutex);
mConnectionClosed = true;
}
MOZ_ALWAYS_TRUE(::sqlite3_close(mDBConn) == SQLITE_OK);
mDBConn = nullptr;
sharedDBMutex.destroy();
}
nsresult Connection::databaseElementExists(
enum DatabaseElementType aElementType, const nsACString& aElementName,
bool* _exists) {
if (!connectionReady()) {
return NS_ERROR_NOT_AVAILABLE;
}
nsresult rv = ensureOperationSupported(SYNCHRONOUS);
if (NS_FAILED(rv)) {
return rv;
}
// When constructing the query, make sure to SELECT the correct db's
// sqlite_master if the user is prefixing the element with a specific db. ex:
// sample.test
nsCString query("SELECT name FROM (SELECT * FROM ");
nsDependentCSubstring element;
int32_t ind = aElementName.FindChar('.');
if (ind == kNotFound) {
element.Assign(aElementName);
} else {
nsDependentCSubstring db(Substring(aElementName, 0, ind + 1));
element.Assign(Substring(aElementName, ind + 1, aElementName.Length()));
query.Append(db);
}
query.AppendLiteral(
"sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type = "
"'");
switch (aElementType) {
case INDEX:
query.AppendLiteral("index");
break;
case TABLE:
query.AppendLiteral("table");
break;
}
query.AppendLiteral("' AND name ='");
query.Append(element);
query.Append('\'');
sqlite3_stmt* stmt;
int srv = prepareStatement(mDBConn, query, &stmt);
if (srv != SQLITE_OK) return convertResultCode(srv);
srv = stepStatement(mDBConn, stmt);
// we just care about the return value from step
(void)::sqlite3_finalize(stmt);
if (srv == SQLITE_ROW) {
*_exists = true;
return NS_OK;
}
if (srv == SQLITE_DONE) {
*_exists = false;
return NS_OK;
}
return convertResultCode(srv);
}
bool Connection::findFunctionByInstance(mozIStorageFunction* aInstance) {
sharedDBMutex.assertCurrentThreadOwns();
for (auto iter = mFunctions.Iter(); !iter.Done(); iter.Next()) {
if (iter.UserData().function == aInstance) {
return true;
}
}
return false;
}
/* static */
int Connection::sProgressHelper(void* aArg) {
Connection* _this = static_cast<Connection*>(aArg);
return _this->progressHandler();
}
int Connection::progressHandler() {
sharedDBMutex.assertCurrentThreadOwns();
if (mProgressHandler) {
bool result;
nsresult rv = mProgressHandler->OnProgress(this, &result);
if (NS_FAILED(rv)) return 0; // Don't break request
return result ? 1 : 0;
}
return 0;
}
nsresult Connection::setClosedState() {
// Ensure that we are on the correct thread to close the database.
bool onOpenedThread;
nsresult rv = threadOpenedOn->IsOnCurrentThread(&onOpenedThread);
NS_ENSURE_SUCCESS(rv, rv);
if (!onOpenedThread) {
NS_ERROR("Must close the database on the thread that you opened it with!");
return NS_ERROR_UNEXPECTED;
}
// Flag that we are shutting down the async thread, so that
// getAsyncExecutionTarget knows not to expose/create the async thread.
{
MutexAutoLock lockedScope(sharedAsyncExecutionMutex);
NS_ENSURE_FALSE(mAsyncExecutionThreadShuttingDown, NS_ERROR_UNEXPECTED);
mAsyncExecutionThreadShuttingDown = true;
// Set the property to null before closing the connection, otherwise the
// other functions in the module may try to use the connection after it is
// closed.
mDBConn = nullptr;
}
return NS_OK;
}
bool Connection::operationSupported(ConnectionOperation aOperationType) {
if (aOperationType == ASYNCHRONOUS) {
// Async operations are supported for all connections, on any thread.
return true;
}
// Sync operations are supported for sync connections (on any thread), and
// async connections on a background thread.
MOZ_ASSERT(aOperationType == SYNCHRONOUS);
return mSupportedOperations == SYNCHRONOUS || !NS_IsMainThread();
}
nsresult Connection::ensureOperationSupported(
ConnectionOperation aOperationType) {
if (NS_WARN_IF(!operationSupported(aOperationType))) {
#ifdef DEBUG
if (NS_IsMainThread()) {
nsCOMPtr<nsIXPConnect> xpc = nsIXPConnect::XPConnect();
Unused << xpc->DebugDumpJSStack(false, false, false);
}
#endif
MOZ_ASSERT(false,
"Don't use async connections synchronously on the main thread");
return NS_ERROR_NOT_AVAILABLE;
}
return NS_OK;
}
bool Connection::isConnectionReadyOnThisThread() {
MOZ_ASSERT_IF(connectionReady(), !mConnectionClosed);
if (mAsyncExecutionThread && mAsyncExecutionThread->IsOnCurrentThread()) {
return true;
}
return connectionReady();
}
bool Connection::isClosing() {
MutexAutoLock lockedScope(sharedAsyncExecutionMutex);
return mAsyncExecutionThreadShuttingDown && !mConnectionClosed;
}
bool Connection::isClosed() {
MutexAutoLock lockedScope(sharedAsyncExecutionMutex);
return mConnectionClosed;
}
bool Connection::isClosed(MutexAutoLock& lock) { return mConnectionClosed; }
bool Connection::isAsyncExecutionThreadAvailable() {
MOZ_ASSERT(threadOpenedOn == NS_GetCurrentThread());
return mAsyncExecutionThread && !mAsyncExecutionThreadShuttingDown;
}
void Connection::shutdownAsyncThread() {
MOZ_ASSERT(threadOpenedOn == NS_GetCurrentThread());
MOZ_ASSERT(mAsyncExecutionThread);
MOZ_ASSERT(mAsyncExecutionThreadShuttingDown);
MOZ_ALWAYS_SUCCEEDS(mAsyncExecutionThread->Shutdown());
mAsyncExecutionThread = nullptr;
}
nsresult Connection::internalClose(sqlite3* aNativeConnection) {
#ifdef DEBUG
{ // Make sure we have marked our async thread as shutting down.
MutexAutoLock lockedScope(sharedAsyncExecutionMutex);
MOZ_ASSERT(mAsyncExecutionThreadShuttingDown,
"Did not call setClosedState!");
MOZ_ASSERT(!isClosed(lockedScope), "Unexpected closed state");
}
#endif // DEBUG
if (MOZ_LOG_TEST(gStorageLog, LogLevel::Debug)) {
nsAutoCString leafName(":memory");
if (mDatabaseFile) (void)mDatabaseFile->GetNativeLeafName(leafName);
MOZ_LOG(gStorageLog, LogLevel::Debug,
("Closing connection to '%s'", leafName.get()));
}
// At this stage, we may still have statements that need to be
// finalized. Attempt to close the database connection. This will
// always disconnect any virtual tables and cleanly finalize their
// internal statements. Once this is done, closing may fail due to
// unfinalized client statements, in which case we need to finalize
// these statements and close again.