Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(371)

Side by Side Diff: sql/connection.cc

Issue 1426743006: [sql] Validate database files before enabling memory-mapping. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Rename helper and address truncate case. Created 5 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « sql/connection.h ('k') | tools/metrics/histograms/histograms.xml » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "sql/connection.h" 5 #include "sql/connection.h"
6 6
7 #include <string.h> 7 #include <string.h>
8 8
9 #include "base/bind.h" 9 #include "base/bind.h"
10 #include "base/debug/dump_without_crashing.h" 10 #include "base/debug/dump_without_crashing.h"
(...skipping 172 matching lines...) Expand 10 before | Expand all | Expand 10 after
183 183
184 // TODO(shess): NULL in file->pMethods has been observed on android_dbg 184 // TODO(shess): NULL in file->pMethods has been observed on android_dbg
185 // content_unittests, even though it should not be possible. 185 // content_unittests, even though it should not be possible.
186 // http://crbug.com/329982 186 // http://crbug.com/329982
187 if (!*file || !(*file)->pMethods) 187 if (!*file || !(*file)->pMethods)
188 return SQLITE_ERROR; 188 return SQLITE_ERROR;
189 189
190 return rc; 190 return rc;
191 } 191 }
192 192
193 // Convenience to get the sqlite3_file* and the size for the "main" database.
194 int GetSqlite3FileAndSize(sqlite3* db,
195 sqlite3_file** file, sqlite3_int64* db_size) {
196 int rc = GetSqlite3File(db, file);
197 if (rc != SQLITE_OK)
198 return rc;
199
200 return (*file)->pMethods->xFileSize(*file, db_size);
201 }
202
193 // This should match UMA_HISTOGRAM_MEDIUM_TIMES(). 203 // This should match UMA_HISTOGRAM_MEDIUM_TIMES().
194 base::HistogramBase* GetMediumTimeHistogram(const std::string& name) { 204 base::HistogramBase* GetMediumTimeHistogram(const std::string& name) {
195 return base::Histogram::FactoryTimeGet( 205 return base::Histogram::FactoryTimeGet(
196 name, 206 name,
197 base::TimeDelta::FromMilliseconds(10), 207 base::TimeDelta::FromMilliseconds(10),
198 base::TimeDelta::FromMinutes(3), 208 base::TimeDelta::FromMinutes(3),
199 50, 209 50,
200 base::HistogramBase::kUmaTargetedHistogramFlag); 210 base::HistogramBase::kUmaTargetedHistogramFlag);
201 } 211 }
202 212
(...skipping 305 matching lines...) Expand 10 before | Expand all | Expand 10 after
508 } 518 }
509 519
510 // Use local settings if provided, otherwise use documented defaults. The 520 // Use local settings if provided, otherwise use documented defaults. The
511 // actual results could be fetching via PRAGMA calls. 521 // actual results could be fetching via PRAGMA calls.
512 const int page_size = page_size_ ? page_size_ : 1024; 522 const int page_size = page_size_ ? page_size_ : 1024;
513 sqlite3_int64 preload_size = page_size * (cache_size_ ? cache_size_ : 2000); 523 sqlite3_int64 preload_size = page_size * (cache_size_ ? cache_size_ : 2000);
514 if (preload_size < 1) 524 if (preload_size < 1)
515 return; 525 return;
516 526
517 sqlite3_file* file = NULL; 527 sqlite3_file* file = NULL;
518 int rc = GetSqlite3File(db_, &file); 528 sqlite3_int64 file_size = 0;
529 int rc = GetSqlite3FileAndSize(db_, &file, &file_size);
519 if (rc != SQLITE_OK) 530 if (rc != SQLITE_OK)
520 return; 531 return;
521 532
522 sqlite3_int64 file_size = 0;
523 rc = file->pMethods->xFileSize(file, &file_size);
524 if (rc != SQLITE_OK)
525 return;
526
527 // Don't preload more than the file contains. 533 // Don't preload more than the file contains.
528 if (preload_size > file_size) 534 if (preload_size > file_size)
529 preload_size = file_size; 535 preload_size = file_size;
530 536
531 scoped_ptr<char[]> buf(new char[page_size]); 537 scoped_ptr<char[]> buf(new char[page_size]);
532 for (sqlite3_int64 pos = 0; pos < preload_size; pos += page_size) { 538 for (sqlite3_int64 pos = 0; pos < preload_size; pos += page_size) {
533 rc = file->pMethods->xRead(file, buf.get(), page_size, pos); 539 rc = file->pMethods->xRead(file, buf.get(), page_size, pos);
540
541 // TODO(shess): Consider calling OnSqliteError().
534 if (rc != SQLITE_OK) 542 if (rc != SQLITE_OK)
535 return; 543 return;
536 } 544 }
537 } 545 }
538 546
539 // SQLite keeps unused pages associated with a connection in a cache. It asks 547 // SQLite keeps unused pages associated with a connection in a cache. It asks
540 // the cache for pages by an id, and if the page is present and the database is 548 // the cache for pages by an id, and if the page is present and the database is
541 // unchanged, it considers the content of the page valid and doesn't read it 549 // unchanged, it considers the content of the page valid and doesn't read it
542 // from disk. When memory-mapped I/O is enabled, on read SQLite uses page 550 // from disk. When memory-mapped I/O is enabled, on read SQLite uses page
543 // structures created from the memory map data before consulting the cache. On 551 // structures created from the memory map data before consulting the cache. On
(...skipping 304 matching lines...) Expand 10 before | Expand all | Expand 10 after
848 // keep close to the 2000-character size limit for dumping. 856 // keep close to the 2000-character size limit for dumping.
849 const size_t kMaxMessages = 20; 857 const size_t kMaxMessages = 20;
850 for (size_t i = 0; i < kMaxMessages && i < messages.size(); ++i) { 858 for (size_t i = 0; i < kMaxMessages && i < messages.size(); ++i) {
851 base::StringAppendF(&debug_info, "%s\n", messages[i].c_str()); 859 base::StringAppendF(&debug_info, "%s\n", messages[i].c_str());
852 } 860 }
853 } 861 }
854 862
855 return debug_info; 863 return debug_info;
856 } 864 }
857 865
866 size_t Connection::GetAppropriateMmapSize() {
867 AssertIOAllowed();
868
869 // TODO(shess): Using sql::MetaTable seems indicated, but mixing
870 // sql::MetaTable and direct access seems error-prone. It might make sense to
871 // simply integrate sql::MetaTable functionality into sql::Connection.
872
873 #if defined(OS_IOS)
874 // iOS SQLite does not support memory mapping.
875 return 0;
876 #endif
877
878 // If the database doesn't have a place to track progress, assume the worst.
879 // This will happen when new databases are created.
880 if (!DoesTableExist("meta")) {
881 RecordOneEvent(EVENT_MMAP_META_MISSING);
882 return 0;
883 }
884
885 // Key into meta table to get status from a previous run. The value
886 // represents how much data in bytes has successfully been read from the
887 // database. |kMmapFailure| indicates that there was a read error and the
888 // database should not be memory-mapped, while |kMmapSuccess| indicates that
889 // the entire file was read at some point and can be memory-mapped without
890 // constraint.
891 const char* kMmapStatusKey = "mmap_status";
892 static const sqlite3_int64 kMmapFailure = -2;
893 static const sqlite3_int64 kMmapSuccess = -1;
894
895 // Start reading from 0 unless status is found in meta table.
896 sqlite3_int64 mmap_ofs = 0;
897
898 // Retrieve the current status. It is fine for the status to be missing
899 // entirely, but any error prevents memory-mapping.
900 {
901 const char* kMmapStatusSql = "SELECT value FROM meta WHERE key = ?";
902 Statement s(GetUniqueStatement(kMmapStatusSql));
903 s.BindString(0, kMmapStatusKey);
904 if (s.Step()) {
905 mmap_ofs = s.ColumnInt64(0);
906 } else if (!s.Succeeded()) {
907 RecordOneEvent(EVENT_MMAP_META_FAILURE_READ);
908 return 0;
909 }
910 }
911
912 // Database read failed in the past, don't memory map.
913 if (mmap_ofs == kMmapFailure) {
914 RecordOneEvent(EVENT_MMAP_FAILED);
915 return 0;
916 } else if (mmap_ofs != kMmapSuccess) {
917 // Continue reading from previous offset.
918 DCHECK_GE(mmap_ofs, 0);
919
920 // TODO(shess): Could this reading code be shared with Preload()? It would
921 // require locking twice (this code wouldn't be able to access |db_size| so
922 // the helper would have to return amount read).
923
924 // Read more of the database looking for errors. The VFS interface is used
925 // to assure that the reads are valid for SQLite. |g_reads_allowed| is used
926 // to limit checking to 20MB per run of Chromium.
927 sqlite3_file* file = NULL;
928 sqlite3_int64 db_size = 0;
929 if (SQLITE_OK != GetSqlite3FileAndSize(db_, &file, &db_size)) {
Scott Hess - ex-Googler 2015/11/05 18:25:07 I made this change because I found myself ponderin
930 RecordOneEvent(EVENT_MMAP_VFS_FAILURE);
931 return 0;
932 }
933
934 // Read the data left, or |g_reads_allowed|, whichever is smaller.
935 // |g_reads_allowed| limits the total amount of I/O to spend verifying data
936 // in a single Chromium run.
937 sqlite3_int64 amount = db_size - mmap_ofs;
938 if (amount < 0)
939 amount = 0;
940 if (amount > 0) {
941 base::AutoLock lock(g_sqlite_init_lock.Get());
942 static sqlite3_int64 g_reads_allowed = 20 * 1024 * 1024;
943 if (g_reads_allowed < amount)
944 amount = g_reads_allowed;
945 g_reads_allowed -= amount;
946 }
947
948 // |amount| can be <= 0 if |g_reads_allowed| ran out of quota, or if the
949 // database was truncated after a previous pass.
950 if (amount <= 0 && mmap_ofs < db_size) {
Scott Hess - ex-Googler 2015/11/05 18:25:07 Took this approach because replicating a subset of
951 DCHECK_EQ(0, amount);
952 RecordOneEvent(EVENT_MMAP_SUCCESS_NO_PROGRESS);
953 } else {
954 static const int kPageSize = 4096;
955 char buf[kPageSize];
956 while (amount > 0) {
957 int rc = file->pMethods->xRead(file, buf, sizeof(buf), mmap_ofs);
958 if (rc == SQLITE_OK) {
959 mmap_ofs += sizeof(buf);
960 amount -= sizeof(buf);
961 } else if (rc == SQLITE_IOERR_SHORT_READ) {
962 // Reached EOF for a database with page size < |kPageSize|.
963 mmap_ofs = db_size;
964 break;
965 } else {
966 // TODO(shess): Consider calling OnSqliteError().
967 mmap_ofs = kMmapFailure;
968 break;
969 }
970 }
971
972 // Log these events after update to distinguish meta update failure.
973 Events event;
974 if (mmap_ofs >= db_size) {
975 mmap_ofs = kMmapSuccess;
976 event = EVENT_MMAP_SUCCESS_NEW;
977 } else if (mmap_ofs > 0) {
978 event = EVENT_MMAP_SUCCESS_PARTIAL;
979 } else {
980 DCHECK_EQ(kMmapFailure, mmap_ofs);
981 event = EVENT_MMAP_FAILED_NEW;
982 }
983
984 const char* kMmapUpdateStatusSql = "REPLACE INTO meta VALUES (?, ?)";
985 Statement s(GetUniqueStatement(kMmapUpdateStatusSql));
986 s.BindString(0, kMmapStatusKey);
987 s.BindInt64(1, mmap_ofs);
988 if (!s.Run()) {
989 RecordOneEvent(EVENT_MMAP_META_FAILURE_UPDATE);
990 return 0;
991 }
992
993 RecordOneEvent(event);
994 }
995 }
996
997 if (mmap_ofs == kMmapFailure)
998 return 0;
999 if (mmap_ofs == kMmapSuccess)
1000 return 256 * 1024 * 1024;
1001 return mmap_ofs;
1002 }
1003
858 void Connection::TrimMemory(bool aggressively) { 1004 void Connection::TrimMemory(bool aggressively) {
859 if (!db_) 1005 if (!db_)
860 return; 1006 return;
861 1007
862 // TODO(shess): investigate using sqlite3_db_release_memory() when possible. 1008 // TODO(shess): investigate using sqlite3_db_release_memory() when possible.
863 int original_cache_size; 1009 int original_cache_size;
864 { 1010 {
865 Statement sql_get_original(GetUniqueStatement("PRAGMA cache_size")); 1011 Statement sql_get_original(GetUniqueStatement("PRAGMA cache_size"));
866 if (!sql_get_original.Step()) { 1012 if (!sql_get_original.Step()) {
867 DLOG(WARNING) << "Could not get cache size " << GetErrorMessage(); 1013 DLOG(WARNING) << "Could not get cache size " << GetErrorMessage();
(...skipping 753 matching lines...) Expand 10 before | Expand all | Expand 10 after
1621 1767
1622 // http://www.sqlite.org/pragma.html#pragma_journal_mode 1768 // http://www.sqlite.org/pragma.html#pragma_journal_mode
1623 // DELETE (default) - delete -journal file to commit. 1769 // DELETE (default) - delete -journal file to commit.
1624 // TRUNCATE - truncate -journal file to commit. 1770 // TRUNCATE - truncate -journal file to commit.
1625 // PERSIST - zero out header of -journal file to commit. 1771 // PERSIST - zero out header of -journal file to commit.
1626 // TRUNCATE should be faster than DELETE because it won't need directory 1772 // TRUNCATE should be faster than DELETE because it won't need directory
1627 // changes for each transaction. PERSIST may break the spirit of using 1773 // changes for each transaction. PERSIST may break the spirit of using
1628 // secure_delete. 1774 // secure_delete.
1629 ignore_result(Execute("PRAGMA journal_mode = TRUNCATE")); 1775 ignore_result(Execute("PRAGMA journal_mode = TRUNCATE"));
1630 1776
1631 // Enable memory-mapped access. This value will be capped by
1632 // SQLITE_MAX_MMAP_SIZE, which could be different between 32-bit and 64-bit
1633 // platforms.
1634 mmap_enabled_ = false;
1635 if (!mmap_disabled_)
1636 ignore_result(Execute("PRAGMA mmap_size = 268435456")); // 256MB.
1637 {
1638 Statement s(GetUniqueStatement("PRAGMA mmap_size"));
1639 if (s.Step() && s.ColumnInt64(0) > 0)
1640 mmap_enabled_ = true;
1641 }
1642
1643 const base::TimeDelta kBusyTimeout = 1777 const base::TimeDelta kBusyTimeout =
1644 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds); 1778 base::TimeDelta::FromSeconds(kBusyTimeoutSeconds);
1645 1779
1646 if (page_size_ != 0) { 1780 if (page_size_ != 0) {
1647 // Enforce SQLite restrictions on |page_size_|. 1781 // Enforce SQLite restrictions on |page_size_|.
1648 DCHECK(!(page_size_ & (page_size_ - 1))) 1782 DCHECK(!(page_size_ & (page_size_ - 1)))
1649 << " page_size_ " << page_size_ << " is not a power of two."; 1783 << " page_size_ " << page_size_ << " is not a power of two.";
1650 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h 1784 const int kSqliteMaxPageSize = 32768; // from sqliteLimit.h
1651 DCHECK_LE(page_size_, kSqliteMaxPageSize); 1785 DCHECK_LE(page_size_, kSqliteMaxPageSize);
1652 const std::string sql = 1786 const std::string sql =
1653 base::StringPrintf("PRAGMA page_size=%d", page_size_); 1787 base::StringPrintf("PRAGMA page_size=%d", page_size_);
1654 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout)); 1788 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
1655 } 1789 }
1656 1790
1657 if (cache_size_ != 0) { 1791 if (cache_size_ != 0) {
1658 const std::string sql = 1792 const std::string sql =
1659 base::StringPrintf("PRAGMA cache_size=%d", cache_size_); 1793 base::StringPrintf("PRAGMA cache_size=%d", cache_size_);
1660 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout)); 1794 ignore_result(ExecuteWithTimeout(sql.c_str(), kBusyTimeout));
1661 } 1795 }
1662 1796
1663 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) { 1797 if (!ExecuteWithTimeout("PRAGMA secure_delete=ON", kBusyTimeout)) {
1664 bool was_poisoned = poisoned_; 1798 bool was_poisoned = poisoned_;
1665 Close(); 1799 Close();
1666 if (was_poisoned && retry_flag == RETRY_ON_POISON) 1800 if (was_poisoned && retry_flag == RETRY_ON_POISON)
1667 return OpenInternal(file_name, NO_RETRY); 1801 return OpenInternal(file_name, NO_RETRY);
1668 return false; 1802 return false;
1669 } 1803 }
1670 1804
1805 // Enable memory-mapped access. The explicit-disable case is because SQLite
1806 // can be built to default-enable mmap. GetAppropriateMmapSize() calculates a
1807 // safe range to memory-map based on past regular I/O. This value will be
1808 // capped by SQLITE_MAX_MMAP_SIZE, which could be different between 32-bit and
1809 // 64-bit platforms.
1810 size_t mmap_size = mmap_disabled_ ? 0 : GetAppropriateMmapSize();
1811 std::string mmap_sql =
1812 base::StringPrintf("PRAGMA mmap_size = %" PRIuS, mmap_size);
1813 ignore_result(Execute(mmap_sql.c_str()));
1814
1815 // Determine if memory-mapping has actually been enabled. The Execute() above
1816 // can succeed without changing the amount mapped.
1817 mmap_enabled_ = false;
1818 {
1819 Statement s(GetUniqueStatement("PRAGMA mmap_size"));
1820 if (s.Step() && s.ColumnInt64(0) > 0)
1821 mmap_enabled_ = true;
1822 }
1823
1671 return true; 1824 return true;
1672 } 1825 }
1673 1826
1674 void Connection::DoRollback() { 1827 void Connection::DoRollback() {
1675 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK")); 1828 Statement rollback(GetCachedStatement(SQL_FROM_HERE, "ROLLBACK"));
1676 1829
1677 // Collect the rollback time manually, sql::Statement would register it as 1830 // Collect the rollback time manually, sql::Statement would register it as
1678 // query time only. 1831 // query time only.
1679 const base::TimeTicks before = Now(); 1832 const base::TimeTicks before = Now();
1680 rollback.RunWithoutTimers(); 1833 rollback.RunWithoutTimers();
(...skipping 119 matching lines...) Expand 10 before | Expand all | Expand 10 after
1800 ignore_result(Execute(kNoWritableSchema)); 1953 ignore_result(Execute(kNoWritableSchema));
1801 1954
1802 return ret; 1955 return ret;
1803 } 1956 }
1804 1957
1805 base::TimeTicks TimeSource::Now() { 1958 base::TimeTicks TimeSource::Now() {
1806 return base::TimeTicks::Now(); 1959 return base::TimeTicks::Now();
1807 } 1960 }
1808 1961
1809 } // namespace sql 1962 } // namespace sql
OLDNEW
« no previous file with comments | « sql/connection.h ('k') | tools/metrics/histograms/histograms.xml » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698