forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.cc
2373 lines (2022 loc) · 86.2 KB
/
database.cc
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
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/351564777): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif
#include "sql/database.h"
#include <limits.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <cinttypes>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <tuple>
#include <utility>
#include <vector>
#include "base/check.h"
#include "base/check_op.h"
#include "base/dcheck_is_on.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/format_macros.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
#include "base/no_destructor.h"
#include "base/notimplemented.h"
#include "base/notreached.h"
#include "base/ranges/algorithm.h"
#include "base/sequence_checker.h"
#include "base/strings/cstring_view.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/synchronization/lock.h"
#include "base/threading/scoped_blocking_call.h"
#include "base/time/time.h"
#include "base/trace_event/memory_dump_manager.h"
#include "base/trace_event/trace_event.h"
#include "base/tracing/protos/chrome_track_event.pbzero.h" // IWYU pragma: keep
#include "base/types/pass_key.h"
#include "build/build_config.h"
#include "sql/database_memory_dump_provider.h"
#include "sql/initialization.h"
#include "sql/internal_api_token.h"
#include "sql/meta_table.h"
#include "sql/sqlite_result_code.h"
#include "sql/sqlite_result_code_values.h"
#include "sql/statement.h"
#include "sql/statement_id.h"
#include "sql/transaction.h"
#include "third_party/perfetto/include/perfetto/tracing/traced_proto.h"
#include "third_party/sqlite/sqlite3.h"
#if BUILDFLAG(IS_WIN)
#include "base/containers/contains.h"
#endif
namespace sql {
namespace {
bool enable_mmap_by_default_ = true;
// The name of the main database associated with a sqlite3* connection.
//
// SQLite has the ability to ATTACH multiple databases to the same connection.
// As a consequence, some SQLite APIs require the connection-specific database
// name. This is the right name to be passed to such APIs.
static constexpr char kSqliteMainDatabaseName[] = "main";
// Magic path value telling sqlite3_open_v2() to open an in-memory database.
static constexpr char kSqliteOpenInMemoryPath[] = ":memory:";
// Spin for up to a second waiting for the lock to clear when setting
// up the database.
// TODO(shess): Better story on this. http://crbug.com/56559
const int kBusyTimeoutSeconds = 1;
// RAII-style wrapper that enables `writable_schema` until it goes out of scope.
// No error checking on the PRAGMA statements because it is reasonable to just
// forge ahead in case of an error. If turning it on fails, then most likely
// nothing will work, whereas if turning it off fails, it only matters if some
// code attempts to continue working with the database and tries to modify the
// sqlite_schema table (none of our code does this).
class ScopedWritableSchema {
public:
explicit ScopedWritableSchema(base::WeakPtr<Database> db)
: db_(std::move(db)) {
CHECK(db_->is_open());
std::ignore = db_->Execute("PRAGMA writable_schema=1");
}
~ScopedWritableSchema() {
// Database invalidates its WeakPtrs before closing the SQLite connection.
if (db_) {
CHECK(db_->is_open());
std::ignore = db_->Execute("PRAGMA writable_schema=0");
}
}
private:
const base::WeakPtr<Database> db_;
};
// Raze() helper that uses SQLite's online backup API.
//
// Returns the SQLite error code produced by sqlite3_backup_step(). SQLITE_DONE
// signals success. SQLITE_OK will never be returned.
//
// The implementation is tailored for the Raze() use case. In particular, the
// SQLite API use and and error handling is optimized for 1-page databases.
SqliteResultCode BackupDatabaseForRaze(sqlite3* source_db,
sqlite3* destination_db) {
DCHECK(source_db);
DCHECK(destination_db);
DCHECK_NE(source_db, destination_db);
// https://www.sqlite.org/backup.html has a high-level overview of SQLite's
// backup support. https://www.sqlite.org/c3ref/backup_finish.html describes
// the API.
static constexpr char kMainDatabaseName[] = "main";
sqlite3_backup* backup = sqlite3_backup_init(
destination_db, kMainDatabaseName, source_db, kMainDatabaseName);
if (!backup) {
// sqlite3_backup_init() fails if a transaction is ongoing. In particular,
// SQL statements that return multiple rows keep a read transaction open
// until all the Step() calls are executed.
return ToSqliteResultCode(chrome_sqlite3_extended_errcode(destination_db));
}
constexpr int kUnlimitedPageCount = -1; // Back up entire database.
auto sqlite_result_code =
ToSqliteResultCode(sqlite3_backup_step(backup, kUnlimitedPageCount));
DCHECK_NE(sqlite_result_code, SqliteResultCode::kOk)
<< "sqlite3_backup_step() returned SQLITE_OK (instead of SQLITE_DONE) "
<< "when asked to back up the entire database";
#if DCHECK_IS_ON()
if (sqlite_result_code == SqliteResultCode::kDone) {
// If successful, exactly one page should have been backed up.
DCHECK_EQ(sqlite3_backup_pagecount(backup), 1)
<< __func__ << " was intended to be used with 1-page databases";
}
#endif // DCHECK_IS_ON()
// sqlite3_backup_finish() releases the sqlite3_backup object.
//
// It returns an error code only if the backup encountered a permanent error.
// We use the the sqlite3_backup_step() result instead, because it also tells
// us about temporary errors, like SQLITE_BUSY.
//
// We pass the sqlite3_backup_finish() result code through
// ToSqliteResultCode() to catch codes that should never occur, like
// SQLITE_MISUSE.
std::ignore = ToSqliteResultCode(sqlite3_backup_finish(backup));
return sqlite_result_code;
}
bool ValidAttachmentPoint(std::string_view attachment_point) {
// SQLite could handle a much wider character set, with appropriate quoting.
//
// Chrome's constraint is easy to remember, and sufficient for the few
// existing use cases. ATTACH is a discouraged feature, so no new use cases
// are expected.
return base::ranges::all_of(attachment_point,
[](char ch) { return base::IsAsciiLower(ch); });
}
std::string AsUTF8ForSQL(const base::FilePath& path) {
#if BUILDFLAG(IS_WIN)
return base::WideToUTF8(path.value());
#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
return path.value();
#endif
}
} // namespace
// static
Database::ScopedErrorExpecterCallback* Database::current_expecter_cb_ = nullptr;
// static
bool Database::IsExpectedSqliteError(int sqlite_error_code) {
DCHECK_NE(sqlite_error_code, SQLITE_OK)
<< __func__ << " received non-error result code";
DCHECK_NE(sqlite_error_code, SQLITE_DONE)
<< __func__ << " received non-error result code";
DCHECK_NE(sqlite_error_code, SQLITE_ROW)
<< __func__ << " received non-error result code";
if (!current_expecter_cb_) {
return false;
}
return current_expecter_cb_->Run(sqlite_error_code);
}
// static
void Database::SetScopedErrorExpecter(
Database::ScopedErrorExpecterCallback* cb,
base::PassKey<test::ScopedErrorExpecter>) {
CHECK(!current_expecter_cb_);
current_expecter_cb_ = cb;
}
// static
void Database::ResetScopedErrorExpecter(
base::PassKey<test::ScopedErrorExpecter>) {
CHECK(current_expecter_cb_);
current_expecter_cb_ = nullptr;
}
// static
base::FilePath Database::JournalPath(const base::FilePath& db_path) {
return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-journal"));
}
// static
base::FilePath Database::WriteAheadLogPath(const base::FilePath& db_path) {
return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-wal"));
}
// static
base::FilePath Database::SharedMemoryFilePath(const base::FilePath& db_path) {
return base::FilePath(db_path.value() + FILE_PATH_LITERAL("-shm"));
}
base::WeakPtr<Database> Database::GetWeakPtr(InternalApiToken) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return weak_factory_.GetWeakPtr();
}
Database::StatementRef::StatementRef(Database* database,
sqlite3_stmt* stmt,
bool was_valid)
: database_(database), stmt_(stmt), was_valid_(was_valid) {
DCHECK_EQ(database == nullptr, stmt == nullptr);
if (database) {
database_->StatementRefCreated(this);
}
}
Database::StatementRef::~StatementRef() {
if (database_) {
database_->StatementRefDeleted(this);
}
Close(false);
}
void Database::StatementRef::Close(bool forced) {
if (stmt_) {
// Call to InitScopedBlockingCall() cannot go at the beginning of the
// function because Close() is called unconditionally from destructor to
// clean database_. And if this is inactive statement this won't cause any
// disk access and destructor most probably will be called on thread not
// allowing disk access.
// TODO([email protected]): This should move to the beginning
// of the function. http://crbug.com/136655.
std::optional<base::ScopedBlockingCall> scoped_blocking_call;
InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
// `stmt_` references memory loaned from the sqlite3 library. Stop
// referencing it from the raw_ptr<> before returning it. This avoids the
// raw_ptr<> becoming dangling.
sqlite3_stmt* statement = stmt_;
stmt_ = nullptr;
// sqlite3_finalize()'s result code is ignored because it reports the same
// error as the most recent sqlite3_step(). The result code is passed
// through ToSqliteResultCode() to catch issues like SQLITE_MISUSE.
std::ignore = ToSqliteResultCode(sqlite3_finalize(statement));
}
database_ = nullptr; // The Database may be getting deleted.
// Forced close is expected to happen from a statement error
// handler. In that case maintain the sense of |was_valid_| which
// previously held for this ref.
was_valid_ = was_valid_ && forced;
}
static_assert(DatabaseOptions::kDefaultPageSize == SQLITE_DEFAULT_PAGE_SIZE,
"DatabaseOptions::kDefaultPageSize must match the value "
"configured into SQLite");
DatabaseDiagnostics::DatabaseDiagnostics() = default;
DatabaseDiagnostics::~DatabaseDiagnostics() = default;
void DatabaseDiagnostics::WriteIntoTrace(
perfetto::TracedProto<TraceProto> context) const {
context->set_reported_sqlite_error_code(reported_sqlite_error_code);
context->set_error_code(error_code);
context->set_last_errno(last_errno);
context->set_sql_statement(sql_statement);
context->set_version(version);
for (const auto& sql : schema_sql_rows) {
context->add_schema_sql_rows(sql);
}
for (const auto& name : schema_other_row_names) {
context->add_schema_other_row_names(name);
}
context->set_has_valid_header(has_valid_header);
context->set_has_valid_schema(has_valid_schema);
context->set_error_message(error_message);
}
Database::Database() : Database(DatabaseOptions{}) {}
Database::Database(DatabaseOptions options)
: options_(options), mmap_disabled_(!enable_mmap_by_default_) {
DCHECK_GE(options.page_size, 512);
DCHECK_LE(options.page_size, 65536);
DCHECK(!(options.page_size & (options.page_size - 1)))
<< "page_size must be a power of two";
DCHECK(!options_.mmap_alt_status_discouraged ||
options_.enable_views_discouraged)
<< "mmap_alt_status requires views";
// It's valid to construct a database on a sequence and then pass it to a
// different sequence before usage.
DETACH_FROM_SEQUENCE(sequence_checker_);
}
Database::~Database() {
Close();
}
// static
void Database::DisableMmapByDefault() {
enable_mmap_by_default_ = false;
}
bool Database::Open(const base::FilePath& path) {
std::string path_string = AsUTF8ForSQL(path);
TRACE_EVENT1("sql", "Database::Open", "path", path_string);
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(!path.empty());
DCHECK_NE(path_string, kSqliteOpenInMemoryPath)
<< "Path conflicts with SQLite magic identifier";
if (OpenInternal(path_string)) {
return true;
}
// OpenInternal() may have run the error callback before returning false. If
// the error callback poisoned `this`, the database may have been recovered or
// razed, so a second attempt may succeed.
if (poisoned_) {
Close();
return OpenInternal(path_string);
}
// Otherwise, do not attempt to reopen.
return false;
}
bool Database::OpenInMemory() {
TRACE_EVENT0("sql", "Database::OpenInMemory");
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
in_memory_ = true;
return OpenInternal(kSqliteOpenInMemoryPath);
}
void Database::DetachFromSequence() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DETACH_FROM_SEQUENCE(sequence_checker_);
}
void Database::CloseInternal(bool forced) {
TRACE_EVENT0("sql", "Database::CloseInternal");
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// TODO(shess): Calling "PRAGMA journal_mode = DELETE" at this point
// will delete the -journal file. For ChromiumOS or other more
// embedded systems, this is probably not appropriate, whereas on
// desktop it might make some sense.
// sqlite3_close() needs all prepared statements to be finalized.
// Release cached statements.
statement_cache_.clear();
// With cached statements released, in-use statements will remain.
// Closing the database while statements are in use is an API
// violation, except for forced close (which happens from within a
// statement's error handler).
DCHECK(forced || open_statements_.empty());
// Deactivate any outstanding statements so sqlite3_close() works.
for (StatementRef* statement_ref : open_statements_) {
statement_ref->Close(forced);
}
open_statements_.clear();
if (is_open()) {
// Call to InitScopedBlockingCall() cannot go at the beginning of the
// function because Close() must be called from destructor to clean
// statement_cache_, it won't cause any disk access and it most probably
// will happen on thread not allowing disk access.
// TODO([email protected]): This should move to the beginning
// of the function. http://crbug.com/136655.
std::optional<base::ScopedBlockingCall> scoped_blocking_call;
InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
// Resetting acquires a lock to ensure no dump is happening on the database
// at the same time. Unregister takes ownership of provider and it is safe
// since the db is reset. memory_dump_provider_ could be null if db_ was
// poisoned.
if (memory_dump_provider_) {
memory_dump_provider_->ResetDatabase();
base::trace_event::MemoryDumpManager::GetInstance()
->UnregisterAndDeleteDumpProviderSoon(
std::move(memory_dump_provider_));
}
// Invalidate any `WeakPtr`s held by scoping helpers.
weak_factory_.InvalidateWeakPtrs();
sqlite3* raw_db = db_;
db_ = nullptr;
auto sqlite_result_code = ToSqliteResultCode(sqlite3_close(raw_db));
DCHECK_NE(sqlite_result_code, SqliteResultCode::kBusy)
<< "sqlite3_close() called while prepared statements are still alive";
DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
<< "sqlite3_close() failed in an unexpected way: "
<< sqlite3_errmsg(raw_db);
// Closing a SQLite database connection implicitly rolls back transactions.
// (See https://www.sqlite.org/c3ref/close.html for details.) Callers need
// not call `RollbackAllTransactions()`, but we still must account for the
// implicit rollback in our internal bookkeeping.
transaction_nesting_ = 0;
}
}
bool Database::is_open() const {
return static_cast<bool>(db_) && !poisoned_;
}
void Database::Close() {
TRACE_EVENT0("sql", "Database::Close");
// If the database was already closed by RazeAndPoison(), then no
// need to close again. Clear the |poisoned_| bit so that incorrect
// API calls are caught.
if (poisoned_) {
poisoned_ = false;
return;
}
CloseInternal(false);
}
void Database::Preload() {
TRACE_EVENT0("sql", "Database::Preload");
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!db_) {
DCHECK(poisoned_) << "Cannot preload null db";
return;
}
CHECK(!options_.exclusive_database_file_lock)
<< "Cannot preload an exclusively locked database.";
std::optional<base::ScopedBlockingCall> scoped_blocking_call;
InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
// Maximum number of bytes that will be prefetched from the database.
//
// This limit is very aggressive. The main trade-off involved is that having
// SQLite block on reading from disk has a high impact on Chrome startup cost
// for the databases that are on the critical path to startup. So, the limit
// must exceed the expected sizes of databases on the critical path.
constexpr int kPreReadSize = 128 * 1024 * 1024; // 128 MB
base::PreReadFile(DbPath(), /*is_executable=*/false, /*sequential=*/false,
kPreReadSize);
}
// SQLite keeps unused pages associated with a database in a cache. It asks
// the cache for pages by an id, and if the page is present and the database is
// unchanged, it considers the content of the page valid and doesn't read it
// from disk. When memory-mapped I/O is enabled, on read SQLite uses page
// structures created from the memory map data before consulting the cache. On
// write SQLite creates a new in-memory page structure, copies the data from the
// memory map, and later writes it, releasing the updated page back to the
// cache.
//
// This means that in memory-mapped mode, the contents of the cached pages are
// not re-used for reads, but they are re-used for writes if the re-written page
// is still in the cache. The implementation of sqlite3_db_release_memory() as
// of SQLite 3.8.7.4 frees all pages from pcaches associated with the
// database, so it should free these pages.
//
// Unfortunately, the zero page is also freed. That page is never accessed
// using memory-mapped I/O, and the cached copy can be re-used after verifying
// the file change counter on disk. Also, fresh pages from cache receive some
// pager-level initialization before they can be used. Since the information
// involved will immediately be accessed in various ways, it is unclear if the
// additional overhead is material, or just moving processor cache effects
// around.
//
// TODO(shess): It would be better to release the pages immediately when they
// are no longer needed. This would basically happen after SQLite commits a
// transaction. I had implemented a pcache wrapper to do this, but it involved
// layering violations, and it had to be setup before any other sqlite call,
// which was brittle. Also, for large files it would actually make sense to
// maintain the existing pcache behavior for blocks past the memory-mapped
// segment. I think drh would accept a reasonable implementation of the overall
// concept for upstreaming to SQLite core.
//
// TODO(shess): Another possibility would be to set the cache size small, which
// would keep the zero page around, plus some pre-initialized pages, and SQLite
// can manage things. The downside is that updates larger than the cache would
// spill to the journal. That could be compensated by setting cache_spill to
// false. The downside then is that it allows open-ended use of memory for
// large transactions.
void Database::ReleaseCacheMemoryIfNeeded(bool implicit_change_performed) {
TRACE_EVENT0("sql", "Database::ReleaseCacheMemoryIfNeeded");
// The database could have been closed during a transaction as part of error
// recovery.
if (!db_) {
DCHECK(poisoned_) << "Illegal use of Database without a db";
return;
}
// If memory-mapping is not enabled, the page cache helps performance.
if (!mmap_enabled_) {
return;
}
// On caller request, force the change comparison to fail. Done before the
// transaction-nesting test so that the signal can carry to transaction
// commit.
if (implicit_change_performed) {
--total_changes_at_last_release_;
}
// Cached pages may be re-used within the same transaction.
DCHECK_GE(transaction_nesting_, 0);
if (transaction_nesting_) {
return;
}
// If no changes have been made, skip flushing. This allows the first page of
// the database to remain in cache across multiple reads.
const int64_t total_changes = sqlite3_total_changes64(db_);
if (total_changes == total_changes_at_last_release_) {
return;
}
total_changes_at_last_release_ = total_changes;
// Passing the result code through ToSqliteResultCode() to catch issues such
// as SQLITE_MISUSE.
std::ignore = ToSqliteResultCode(sqlite3_db_release_memory(db_));
}
base::FilePath Database::DbPath() const {
if (!is_open()) {
return base::FilePath();
}
const char* path = sqlite3_db_filename(db_, "main");
if (!path) {
return base::FilePath();
}
const std::string_view db_path(path);
#if BUILDFLAG(IS_WIN)
return base::FilePath(base::UTF8ToWide(db_path));
#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
return base::FilePath(db_path);
#else
NOTREACHED();
#endif
}
std::string Database::CollectErrorInfo(int sqlite_error_code,
Statement* stmt,
DatabaseDiagnostics* diagnostics) const {
TRACE_EVENT0("sql", "Database::CollectErrorInfo");
DCHECK_NE(sqlite_error_code, SQLITE_OK)
<< __func__ << " received non-error result code";
DCHECK_NE(sqlite_error_code, SQLITE_DONE)
<< __func__ << " received non-error result code";
DCHECK_NE(sqlite_error_code, SQLITE_ROW)
<< __func__ << " received non-error result code";
// Buffer for accumulating debugging info about the error. Place
// more-relevant information earlier, in case things overflow the
// fixed-size reporting buffer.
std::string debug_info;
// The error message from the failed operation.
int error_code = GetErrorCode();
base::StringAppendF(&debug_info, "db error: %d/%s\n", error_code,
GetErrorMessage());
if (diagnostics) {
diagnostics->error_code = error_code;
diagnostics->error_message = GetErrorMessage();
}
// TODO(shess): |error| and |GetErrorCode()| should always be the same, but
// reading code does not entirely convince me. Remove if they turn out to be
// the same.
if (sqlite_error_code != GetErrorCode()) {
base::StringAppendF(&debug_info, "reported error: %d\n", sqlite_error_code);
}
// System error information. Interpretation of Windows errors is different
// from posix.
#if BUILDFLAG(IS_WIN)
int last_errno = GetLastErrno();
base::StringAppendF(&debug_info, "LastError: %d\n", last_errno);
if (diagnostics) {
diagnostics->last_errno = last_errno;
}
#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
int last_errno = GetLastErrno();
base::StringAppendF(&debug_info, "errno: %d\n", last_errno);
if (diagnostics) {
diagnostics->last_errno = last_errno;
}
#else
NOTREACHED(); // Add appropriate log info.
#endif
if (stmt) {
std::string sql_string = stmt->GetSQLStatement();
base::StringAppendF(&debug_info, "statement: %s\n", sql_string.c_str());
if (diagnostics) {
diagnostics->sql_statement = sql_string;
}
} else {
base::StringAppendF(&debug_info, "statement: NULL\n");
}
// SQLITE_ERROR often indicates some sort of mismatch between the statement
// and the schema, possibly due to a failed schema migration.
if (sqlite_error_code == SQLITE_ERROR) {
static constexpr char kVersionSql[] =
"SELECT value FROM meta WHERE key='version'";
sqlite3_stmt* sqlite_statement;
// When the number of bytes passed to sqlite3_prepare_v3() includes the null
// terminator, SQLite avoids a buffer copy.
int rc = sqlite3_prepare_v3(db_, kVersionSql, sizeof(kVersionSql),
SQLITE_PREPARE_NO_VTAB, &sqlite_statement,
/* pzTail= */ nullptr);
if (rc == SQLITE_OK) {
rc = sqlite3_step(sqlite_statement);
if (rc == SQLITE_ROW) {
int version = sqlite3_column_int(sqlite_statement, 0);
base::StringAppendF(&debug_info, "version: %d\n", version);
if (diagnostics) {
diagnostics->version = version;
}
} else if (rc == SQLITE_DONE) {
debug_info += "version: none\n";
} else {
base::StringAppendF(&debug_info, "version: error %d\n", rc);
}
sqlite3_finalize(sqlite_statement);
} else {
base::StringAppendF(&debug_info, "version: prepare error %d\n", rc);
}
// Get all the SQL from sqlite_schema.
debug_info += "schema:\n";
static constexpr char kSchemaSql[] =
"SELECT sql FROM sqlite_schema WHERE sql IS NOT NULL ORDER BY ROWID";
rc = sqlite3_prepare_v3(db_, kSchemaSql, sizeof(kSchemaSql),
SQLITE_PREPARE_NO_VTAB, &sqlite_statement,
/* pzTail= */ nullptr);
if (rc == SQLITE_OK) {
while ((rc = sqlite3_step(sqlite_statement)) == SQLITE_ROW) {
std::string text;
base::StringAppendF(&text, "%s",
reinterpret_cast<const char*>(
sqlite3_column_text(sqlite_statement, 0)));
debug_info += text + "\n";
if (diagnostics) {
diagnostics->schema_sql_rows.push_back(text);
}
}
if (rc != SQLITE_DONE) {
base::StringAppendF(&debug_info, "error %d\n", rc);
}
sqlite3_finalize(sqlite_statement);
} else {
base::StringAppendF(&debug_info, "prepare error %d\n", rc);
}
// Automatically generated indices have a NULL 'sql' column. For those rows,
// we log the name column instead.
debug_info += "schema rows with only name:\n";
static constexpr char kSchemaOtherRowNamesSql[] =
"SELECT name FROM sqlite_schema WHERE sql IS NULL ORDER BY ROWID";
rc = sqlite3_prepare_v3(db_, kSchemaOtherRowNamesSql,
sizeof(kSchemaOtherRowNamesSql),
SQLITE_PREPARE_NO_VTAB, &sqlite_statement,
/* pzTail= */ nullptr);
if (rc == SQLITE_OK) {
while ((rc = sqlite3_step(sqlite_statement)) == SQLITE_ROW) {
std::string text;
base::StringAppendF(&text, "%s",
reinterpret_cast<const char*>(
sqlite3_column_text(sqlite_statement, 0)));
debug_info += text + "\n";
if (diagnostics) {
diagnostics->schema_other_row_names.push_back(text);
}
}
if (rc != SQLITE_DONE) {
base::StringAppendF(&debug_info, "error %d\n", rc);
}
sqlite3_finalize(sqlite_statement);
} else {
base::StringAppendF(&debug_info, "prepare error %d\n", rc);
}
}
return debug_info;
}
// TODO(shess): Since this is only called in an error situation, it might be
// prudent to rewrite in terms of SQLite API calls, and mark the function const.
std::string Database::CollectCorruptionInfo() {
TRACE_EVENT0("sql", "Database::CollectCorruptionInfo");
// If the file cannot be accessed it is unlikely that an integrity check will
// turn up actionable information.
const base::FilePath db_path = DbPath();
int64_t db_size = -1;
if (!base::GetFileSize(db_path, &db_size) || db_size < 0) {
return std::string();
}
// Buffer for accumulating debugging info about the error. Place
// more-relevant information earlier, in case things overflow the
// fixed-size reporting buffer.
std::string debug_info;
base::StringAppendF(&debug_info, "SQLITE_CORRUPT, db size %" PRId64 "\n",
db_size);
// Only check files up to 8M to keep things from blocking too long.
const int64_t kMaxIntegrityCheckSize = 8192 * 1024;
if (db_size > kMaxIntegrityCheckSize) {
debug_info += "integrity_check skipped due to size\n";
} else {
std::vector<std::string> messages;
// TODO(shess): FullIntegrityCheck() splits into a vector while this joins
// into a string. Probably should be refactored.
const base::TimeTicks before = base::TimeTicks::Now();
FullIntegrityCheck(&messages);
base::StringAppendF(
&debug_info, "integrity_check %" PRId64 " ms, %" PRIuS " records:\n",
(base::TimeTicks::Now() - before).InMilliseconds(), messages.size());
// SQLite returns up to 100 messages by default, trim deeper to
// keep close to the 2000-character size limit for dumping.
const size_t kMaxMessages = 20;
for (size_t i = 0; i < kMaxMessages && i < messages.size(); ++i) {
base::StringAppendF(&debug_info, "%s\n", messages[i].c_str());
}
}
return debug_info;
}
bool Database::GetMmapAltStatus(int64_t* status) {
TRACE_EVENT0("sql", "Database::GetMmapAltStatus");
// The [meta] version uses a missing table as a signal for a fresh database.
// That will not work for the view, which would not exist in either a new or
// an existing database. A new database _should_ be only one page long, so
// just don't bother optimizing this case (start at offset 0).
// TODO(shess): Could the [meta] case also get simpler, then?
if (!DoesViewExist("MmapStatus")) {
*status = 0;
return true;
}
static constexpr char kMmapStatusSql[] = "SELECT * FROM MmapStatus";
Statement s(GetUniqueStatement(kMmapStatusSql));
if (s.Step()) {
*status = s.ColumnInt64(0);
}
return s.Succeeded();
}
bool Database::SetMmapAltStatus(int64_t status) {
Transaction transaction(this);
if (!transaction.Begin()) {
return false;
}
// View may not exist on first run.
if (!Execute("DROP VIEW IF EXISTS MmapStatus")) {
return false;
}
// Views live in the schema, so they cannot be parameterized. For an integer
// value, this construct should be safe from SQL injection, if the value
// becomes more complicated use "SELECT quote(?)" to generate a safe quoted
// value.
const std::string create_view_sql = base::StringPrintf(
"CREATE VIEW MmapStatus (value) AS SELECT %" PRId64, status);
if (!Execute(create_view_sql)) {
return false;
}
return transaction.Commit();
}
size_t Database::ComputeMmapSizeForOpen() {
TRACE_EVENT0("sql", "Database::ComputeMmapSizeForOpen");
std::optional<base::ScopedBlockingCall> scoped_blocking_call;
InitScopedBlockingCall(FROM_HERE, &scoped_blocking_call);
// How much to map if no errors are found. 50MB encompasses the 99th
// percentile of Chrome databases in the wild, so this should be good.
const size_t kMmapEverything = 256 * 1024 * 1024;
// Progress information is tracked in the [meta] table for databases which use
// sql::MetaTable, otherwise it is tracked in a special view.
// TODO(pwnall): Migrate all databases to using a meta table.
int64_t mmap_ofs = 0;
if (options_.mmap_alt_status_discouraged) {
if (!GetMmapAltStatus(&mmap_ofs)) {
return 0;
}
} else {
// If [meta] doesn't exist, yet, it's a new database, assume the best.
// sql::MetaTable::Init() will preload kMmapSuccess.
if (!MetaTable::DoesTableExist(this)) {
return kMmapEverything;
}
if (!MetaTable::GetMmapStatus(this, &mmap_ofs)) {
return 0;
}
}
// Database read failed in the past, don't memory map.
if (mmap_ofs == MetaTable::kMmapFailure) {
return 0;
}
if (mmap_ofs != MetaTable::kMmapSuccess) {
// Continue reading from previous offset.
DCHECK_GE(mmap_ofs, 0);
// GetSqliteVfsFile() returns null for in-memory and temporary databases.
// This is fine, we don't want to enable memory-mapping in those cases
// anyway.
//
// First, memory-mapping is a no-op for in-memory databases.
//
// Second, temporary databases are only used for corruption recovery, which
// occurs in response to I/O errors. An environment with heightened I/O
// errors translates into a higher risk of mmap-induced Chrome crashes.
sqlite3_int64 db_size = 0;
sqlite3_file* file = GetSqliteVfsFile();
if (!file || file->pMethods->xFileSize(file, &db_size) != SQLITE_OK) {
return 0;
}
// Read more of the database looking for errors. The VFS interface is used
// to assure that the reads are valid for SQLite. |g_reads_allowed| is used
// to limit checking to 20MB per run of Chromium.
//
// Read the data left, or |g_reads_allowed|, whichever is smaller.
// |g_reads_allowed| limits the total amount of I/O to spend verifying data
// in a single Chromium run.
sqlite3_int64 amount = db_size - mmap_ofs;
if (amount < 0) {
amount = 0;
}
if (amount > 0) {
static base::NoDestructor<base::Lock> lock;
base::AutoLock auto_lock(*lock);
static sqlite3_int64 g_reads_allowed = 20 * 1024 * 1024;
if (g_reads_allowed < amount) {
amount = g_reads_allowed;
}
g_reads_allowed -= amount;
}
// |amount| can be <= 0 if |g_reads_allowed| ran out of quota, or if the
// database was truncated after a previous pass.
if (amount <= 0 && mmap_ofs < db_size) {
DCHECK_EQ(0, amount);
} else {
static const int kPageSize = 4096;
char buf[kPageSize];
while (amount > 0) {
int rc = file->pMethods->xRead(file, buf, sizeof(buf), mmap_ofs);
if (rc == SQLITE_OK) {
mmap_ofs += sizeof(buf);
amount -= sizeof(buf);
} else if (rc == SQLITE_IOERR_SHORT_READ) {
// Reached EOF for a database with page size < |kPageSize|.
mmap_ofs = db_size;
break;
} else {
// TODO(shess): Consider calling OnSqliteError().
mmap_ofs = MetaTable::kMmapFailure;
break;
}
}
// Log these events after update to distinguish meta update failure.
if (mmap_ofs >= db_size) {
mmap_ofs = MetaTable::kMmapSuccess;
} else {
DCHECK(mmap_ofs > 0 || mmap_ofs == MetaTable::kMmapFailure);
}
if (options_.mmap_alt_status_discouraged) {
if (!SetMmapAltStatus(mmap_ofs)) {
return 0;
}
} else {
if (!MetaTable::SetMmapStatus(this, mmap_ofs)) {
return 0;
}
}
}
}
if (mmap_ofs == MetaTable::kMmapFailure) {
return 0;
}
if (mmap_ofs == MetaTable::kMmapSuccess) {
return kMmapEverything;
}
return mmap_ofs;
}
int Database::SqlitePrepareFlags() const {
return enable_virtual_tables_ ? 0 : SQLITE_PREPARE_NO_VTAB;
}
sqlite3_file* Database::GetSqliteVfsFile() {
CHECK(db_) << "Database not opened";
// sqlite3_file_control() accepts a null pointer to mean the "main" database
// attached to a connection. https://www.sqlite.org/c3ref/file_control.html
constexpr const char* kMainDatabaseName = nullptr;
sqlite3_file* result = nullptr;
auto sqlite_result_code = ToSqliteResultCode(sqlite3_file_control(
db_, kMainDatabaseName, SQLITE_FCNTL_FILE_POINTER, &result));
// SQLITE_FCNTL_FILE_POINTER is handled directly by SQLite, not by the VFS. It
// is only supposed to fail with SQLITE_ERROR if the database name is not
// recognized. However, "main" should always be recognized.
DCHECK_EQ(sqlite_result_code, SqliteResultCode::kOk)
<< "sqlite3_file_control(SQLITE_FCNTL_FILE_POINTER) failed";
// SQLite does not return null when called on an in-memory or temporary
// database. Instead, it returns returns a VFS file object with a null
// pMethods member.
DCHECK(result)
<< "sqlite3_file_control() succeded but returned a null sqlite3_file*";
if (!result->pMethods) {
// If this assumption fails, sql::Database will still function correctly,
// but will miss some configuration optimizations. The DCHECK is here to
// alert us (via test failures and ASAN canary builds) of such cases.
DCHECK_EQ(DbPath().AsUTF8Unsafe(), "")
<< "sqlite3_file_control() returned a sqlite3_file* with null pMethods "
<< "in a case when it shouldn't have.";
return nullptr;
}
return result;
}
void Database::TrimMemory() {
TRACE_EVENT0("sql", "Database::TrimMemory");