2 * Copyright (C) 2009 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "SQLiteFileSystem.h"
34 #include "PlatformBridge.h"
42 #include <sys/types.h>
45 using namespace WebCore;
47 // Chromium's Posix implementation of SQLite VFS.
48 // This is heavily based on SQLite's os_unix.c,
49 // without parts we don't need.
51 // Identifies a file by its device number and inode.
52 struct ChromiumFileId {
53 dev_t dev; // Device number.
54 ino_t ino; // Inode number.
57 // Information about file locks (one per open inode). Note that many open
58 // file descriptors may refer to the same inode.
59 struct ChromiumLockInfo {
60 ChromiumFileId lockKey; // File identifier.
61 int cnt; // Number of shared locks held.
62 int locktype; // Type of the lock.
63 int nRef; // Reference count.
65 // Double-linked list pointers.
66 ChromiumLockInfo* pNext;
67 ChromiumLockInfo* pPrev;
70 // Information about a file descriptor that cannot be closed immediately.
71 struct ChromiumUnusedFd {
72 int fd; // File descriptor.
73 int flags; // Flags this file descriptor was opened with.
74 ChromiumUnusedFd* pNext; // Next unused file descriptor on the same file.
77 // Information about an open inode. When we want to close an inode
78 // that still has locks, we defer the close until all locks are cleared.
79 struct ChromiumOpenInfo {
80 ChromiumFileId fileId; // The lookup key.
81 int nRef; // Reference count.
82 int nLock; // Number of outstanding locks.
83 ChromiumUnusedFd* pUnused; // List of file descriptors to close.
85 // Double-linked list pointers.
86 ChromiumOpenInfo* pNext;
87 ChromiumOpenInfo* pPrev;
90 // Keep track of locks and inodes in double-linked lists.
91 static struct ChromiumLockInfo* lockList = 0;
92 static struct ChromiumOpenInfo* openList = 0;
94 // Extension of sqlite3_file specific to the chromium VFS.
96 sqlite3_io_methods const* pMethod; // Implementation of sqlite3_file.
97 ChromiumOpenInfo* pOpen; // Information about all open file descriptors for this file.
98 ChromiumLockInfo* pLock; // Information about all locks for this file.
99 int h; // File descriptor.
100 int dirfd; // File descriptor for the file directory.
101 unsigned char locktype; // Type of the lock used for this file.
102 int lastErrno; // Value of errno for last operation on this file.
103 ChromiumUnusedFd* pUnused; // Information about unused file descriptors for this file.
106 // The following constants specify the range of bytes used for locking.
107 // SQLiteSharedSize is the number of bytes available in the pool from which
108 // a random byte is selected for a shared lock. The pool of bytes for
109 // shared locks begins at SQLiteSharedFirstByte.
110 // The values are the same as used by SQLite for compatibility.
111 static const off_t SQLitePendingByte = 0x40000000;
112 static const off_t SQLiteReservedByte = SQLitePendingByte + 1;
113 static const off_t SQLiteSharedFirstByte = SQLitePendingByte + 2;
114 static const off_t SQLiteSharedSize = 510;
116 // Maps a POSIX error code to an SQLite error code.
117 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr)
119 switch (posixError) {
129 // EACCES is like EAGAIN during locking operations.
130 if ((sqliteIOErr == SQLITE_IOERR_LOCK) ||
131 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
132 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
133 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK))
139 return SQLITE_IOERR_BLOCKED;
145 // Releases a ChromiumLockInfo structure previously allocated by findLockInfo().
146 static void releaseLockInfo(ChromiumLockInfo* pLock)
156 ASSERT(pLock->pPrev->pNext == pLock);
157 pLock->pPrev->pNext = pLock->pNext;
159 ASSERT(lockList == pLock);
160 lockList = pLock->pNext;
163 ASSERT(pLock->pNext->pPrev == pLock);
164 pLock->pNext->pPrev = pLock->pPrev;
170 // Releases a ChromiumOpenInfo structure previously allocated by findLockInfo().
171 static void releaseOpenInfo(ChromiumOpenInfo* pOpen)
181 ASSERT(pOpen->pPrev->pNext == pOpen);
182 pOpen->pPrev->pNext = pOpen->pNext;
184 ASSERT(openList == pOpen);
185 openList = pOpen->pNext;
188 ASSERT(pOpen->pNext->pPrev == pOpen);
189 pOpen->pNext->pPrev = pOpen->pPrev;
192 ASSERT(!pOpen->pUnused); // Make sure we're not leaking memory and file descriptors.
197 // Locates ChromiumLockInfo and ChromiumOpenInfo for given file descriptor (creating new ones if needed).
198 // Returns a SQLite error code.
199 static int findLockInfo(ChromiumFile* pFile, ChromiumLockInfo** ppLock, ChromiumOpenInfo** ppOpen)
203 int rc = fstat(fd, &statbuf);
205 pFile->lastErrno = errno;
207 if (pFile->lastErrno == EOVERFLOW)
214 // On OS X on an msdos/fat filesystems, the inode number is reported
215 // incorrectly for zero-size files. See http://www.sqlite.org/cvstrac/tktview?tn=3260.
216 // To work around this problem we always increase the file size to 1 by writing a single byte
217 // prior to accessing the inode number. The one byte written is an ASCII 'S' character which
218 // also happens to be the first byte in the header of every SQLite database. In this way,
219 // if there is a race condition such that another thread has already populated the first page
220 // of the database, no damage is done.
221 if (!statbuf.st_size) {
222 rc = write(fd, "S", 1);
225 rc = fstat(fd, &statbuf);
227 pFile->lastErrno = errno;
233 ChromiumFileId fileId;
234 memset(&fileId, 0, sizeof(fileId));
235 fileId.dev = statbuf.st_dev;
236 fileId.ino = statbuf.st_ino;
238 ChromiumLockInfo* pLock = 0;
242 while (pLock && memcmp(&fileId, &pLock->lockKey, sizeof(fileId)))
243 pLock = pLock->pNext;
247 pLock = static_cast<ChromiumLockInfo*>(sqlite3_malloc(sizeof(*pLock)));
250 pLock->lockKey = fileId;
254 pLock->pNext = lockList;
257 lockList->pPrev = pLock;
264 ChromiumOpenInfo* pOpen = openList;
265 while (pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)))
266 pOpen = pOpen->pNext;
270 pOpen = static_cast<ChromiumOpenInfo*>(sqlite3_malloc(sizeof(*pOpen)));
272 releaseLockInfo(pLock);
275 memset(pOpen, 0, sizeof(*pOpen));
276 pOpen->fileId = fileId;
278 pOpen->pNext = openList;
280 openList->pPrev = pOpen;
289 // Checks if there is a RESERVED lock held on the specified file by this or any other process.
290 // If the lock is held, sets pResOut to a non-zero value. Returns a SQLite error code.
291 static int chromiumCheckReservedLock(sqlite3_file* id, int* pResOut)
293 ChromiumFile* pFile = reinterpret_cast<ChromiumFile*>(id);
296 // Look for locks held by this process.
298 if (pFile->pLock->locktype > SQLITE_LOCK_SHARED)
301 // Look for locks held by other processes.
305 lock.l_whence = SEEK_SET;
306 lock.l_start = SQLiteReservedByte;
308 lock.l_type = F_WRLCK;
309 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
311 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
312 pFile->lastErrno = tErrno;
313 } else if (lock.l_type != F_UNLCK)
321 // Performs a file locking operation on a range of bytes in a file.
322 // The |op| parameter should be one of F_RFLCK, F_WRLCK or F_UNLCK.
323 // Returns a Unix error code, and also writes it to pErrcode.
324 static int rangeLock(ChromiumFile* pFile, int op, int* pErrcode)
328 lock.l_start = SQLiteSharedFirstByte;
329 lock.l_whence = SEEK_SET;
330 lock.l_len = SQLiteSharedSize;
331 int rc = fcntl(pFile->h, F_SETLK, &lock);
336 // Locks the file with the lock specified by parameter locktype - one
339 // (1) SQLITE_LOCK_SHARED
340 // (2) SQLITE_LOCK_RESERVED
341 // (3) SQLITE_LOCK_PENDING
342 // (4) SQLITE_LOCK_EXCLUSIVE
344 // Sometimes when requesting one lock state, additional lock states
345 // are inserted in between. The locking might fail on one of the later
346 // transitions leaving the lock state different from what it started but
347 // still short of its goal. The following chart shows the allowed
348 // transitions and the inserted intermediate states:
350 // UNLOCKED -> SHARED
351 // SHARED -> RESERVED
352 // SHARED -> (PENDING) -> EXCLUSIVE
353 // RESERVED -> (PENDING) -> EXCLUSIVE
354 // PENDING -> EXCLUSIVE
355 static int chromiumLock(sqlite3_file* id, int locktype)
357 // To obtain a SHARED lock, a read-lock is obtained on the 'pending
358 // byte'. If this is successful, a random byte from the 'shared byte
359 // range' is read-locked and the lock on the 'pending byte' released.
361 // A process may only obtain a RESERVED lock after it has a SHARED lock.
362 // A RESERVED lock is implemented by grabbing a write-lock on the
365 // A process may only obtain a PENDING lock after it has obtained a
366 // SHARED lock. A PENDING lock is implemented by obtaining a write-lock
367 // on the 'pending byte'. This ensures that no new SHARED locks can be
368 // obtained, but existing SHARED locks are allowed to persist. A process
369 // does not have to obtain a RESERVED lock on the way to a PENDING lock.
370 // This property is used by the algorithm for rolling back a journal file
373 // An EXCLUSIVE lock, obtained after a PENDING lock is held, is
374 // implemented by obtaining a write-lock on the entire 'shared byte
375 // range'. Since all other locks require a read-lock on one of the bytes
376 // within this range, this ensures that no other locks are held on the
384 ChromiumFile* pFile = reinterpret_cast<ChromiumFile*>(id);
387 ChromiumLockInfo* pLock = pFile->pLock;
389 // If there is already a lock of this type or more restrictive, do nothing.
390 if (pFile->locktype >= locktype)
393 // Make sure we never move from unlocked to anything higher than shared lock.
394 ASSERT(pFile->locktype != SQLITE_LOCK_NONE || locktype == SQLITE_LOCK_SHARED);
396 // Make sure we never request a pending lock.
397 ASSERT(locktype != SQLITE_LOCK_PENDING);
399 // Make sure a shared lock is always held when a RESERVED lock is requested.
400 ASSERT(locktype != SQLITE_LOCK_RESERVED || pFile->locktype == SQLITE_LOCK_SHARED);
402 // If some thread using this PID has a lock via a different ChromiumFile
403 // handle that precludes the requested lock, return BUSY.
404 if (pFile->locktype != pLock->locktype &&
405 (pLock->locktype >= SQLITE_LOCK_PENDING || locktype > SQLITE_LOCK_SHARED))
408 // If a SHARED lock is requested, and some thread using this PID already
409 // has a SHARED or RESERVED lock, then just increment reference counts.
410 if (locktype == SQLITE_LOCK_SHARED &&
411 (pLock->locktype == SQLITE_LOCK_SHARED || pLock->locktype == SQLITE_LOCK_RESERVED)) {
412 ASSERT(!pFile->locktype);
413 ASSERT(pLock->cnt > 0);
414 pFile->locktype = SQLITE_LOCK_SHARED;
416 pFile->pOpen->nLock++;
420 // A PENDING lock is needed before acquiring a SHARED lock and before
421 // acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
424 lock.l_whence = SEEK_SET;
425 if (locktype == SQLITE_LOCK_SHARED ||
426 (locktype == SQLITE_LOCK_EXCLUSIVE && pFile->locktype < SQLITE_LOCK_PENDING)) {
427 lock.l_type = (locktype == SQLITE_LOCK_SHARED ? F_RDLCK : F_WRLCK);
428 lock.l_start = SQLitePendingByte;
429 s = fcntl(pFile->h, F_SETLK, &lock);
432 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
433 if ((rc != SQLITE_OK) && (rc != SQLITE_BUSY))
434 pFile->lastErrno = tErrno;
439 if (locktype == SQLITE_LOCK_SHARED) {
441 ASSERT(!pLock->locktype);
443 s = rangeLock(pFile, F_RDLCK, &tErrno);
445 // Drop the temporary PENDING lock.
446 lock.l_start = SQLitePendingByte;
448 lock.l_type = F_UNLCK;
449 if (fcntl(pFile->h, F_SETLK, &lock)) {
452 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
453 if ((rc != SQLITE_OK) && (rc != SQLITE_BUSY))
454 pFile->lastErrno = tErrno;
459 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
460 if ((rc != SQLITE_OK) && (rc != SQLITE_BUSY))
461 pFile->lastErrno = tErrno;
463 pFile->locktype = SQLITE_LOCK_SHARED;
464 pFile->pOpen->nLock++;
467 } else if (locktype == SQLITE_LOCK_EXCLUSIVE && pLock->cnt > 1) {
468 // We are trying for an exclusive lock but another thread in the
469 // same process is still holding a shared lock.
472 // The request was for a RESERVED or EXCLUSIVE lock. It is
473 // assumed that there is a SHARED or greater lock on the file
475 ASSERT(pFile->locktype);
476 lock.l_type = F_WRLCK;
478 case SQLITE_LOCK_RESERVED:
479 lock.l_start = SQLiteReservedByte;
480 s = fcntl(pFile->h, F_SETLK, &lock);
483 case SQLITE_LOCK_EXCLUSIVE:
484 s = rangeLock(pFile, F_WRLCK, &tErrno);
487 ASSERT_NOT_REACHED();
490 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
491 if ((rc != SQLITE_OK) && (rc != SQLITE_BUSY))
492 pFile->lastErrno = tErrno;
496 if (rc == SQLITE_OK) {
497 pFile->locktype = locktype;
498 pLock->locktype = locktype;
499 } else if (locktype == SQLITE_LOCK_EXCLUSIVE) {
500 pFile->locktype = SQLITE_LOCK_PENDING;
501 pLock->locktype = SQLITE_LOCK_PENDING;
507 // Closes all file descriptors for given ChromiumFile for which the close has been deferred.
508 // Returns a SQLite error code.
509 static int closePendingFds(ChromiumFile* pFile)
512 ChromiumOpenInfo* pOpen = pFile->pOpen;
513 ChromiumUnusedFd* pError = 0;
514 ChromiumUnusedFd* pNext;
515 for (ChromiumUnusedFd* p = pOpen->pUnused; p; p = pNext) {
518 pFile->lastErrno = errno;
519 rc = SQLITE_IOERR_CLOSE;
525 pOpen->pUnused = pError;
529 // Lowers the locking level on file descriptor.
530 // locktype must be either SQLITE_LOCK_NONE or SQLITE_LOCK_SHARED.
531 static int chromiumUnlock(sqlite3_file* id, int locktype)
533 ChromiumFile* pFile = reinterpret_cast<ChromiumFile*>(id);
535 ASSERT(locktype <= SQLITE_LOCK_SHARED);
537 if (pFile->locktype <= locktype)
540 ChromiumLockInfo* pLock = pFile->pLock;
548 if (pFile->locktype > SQLITE_LOCK_SHARED) {
549 ASSERT(pLock->locktype == pFile->locktype);
551 if (locktype == SQLITE_LOCK_SHARED && rangeLock(pFile, F_RDLCK, &tErrno) == -1) {
552 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
553 if ((rc != SQLITE_OK) && (rc != SQLITE_BUSY))
554 pFile->lastErrno = tErrno;
556 pFile->locktype = locktype;
559 lock.l_type = F_UNLCK;
560 lock.l_whence = SEEK_SET;
561 lock.l_start = SQLitePendingByte;
563 if (fcntl(h, F_SETLK, &lock) != -1)
564 pLock->locktype = SQLITE_LOCK_SHARED;
567 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
568 if ((rc != SQLITE_OK) && (rc != SQLITE_BUSY))
569 pFile->lastErrno = tErrno;
571 pFile->locktype = locktype;
575 if (locktype == SQLITE_LOCK_NONE) {
576 struct ChromiumOpenInfo *pOpen;
580 // Release the lock using an OS call only when all threads in this same process have released the lock.
582 lock.l_type = F_UNLCK;
583 lock.l_whence = SEEK_SET;
584 lock.l_start = lock.l_len = 0L;
585 if (fcntl(h, F_SETLK, &lock) != -1)
586 pLock->locktype = SQLITE_LOCK_NONE;
589 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
590 if ((rc != SQLITE_OK) && (rc != SQLITE_BUSY))
591 pFile->lastErrno = tErrno;
592 pLock->locktype = SQLITE_LOCK_NONE;
593 pFile->locktype = SQLITE_LOCK_NONE;
597 pOpen = pFile->pOpen;
599 ASSERT(pOpen->nLock >= 0);
601 int rc2 = closePendingFds(pFile);
608 pFile->locktype = locktype;
612 // Closes all file handles for given ChromiumFile and sets all its fields to 0.
613 // Returns a SQLite error code.
614 static int chromiumCloseNoLock(sqlite3_file* id)
616 ChromiumFile* pFile = reinterpret_cast<ChromiumFile*>(id);
619 if (pFile->dirfd >= 0) {
620 if (close(pFile->dirfd)) {
621 pFile->lastErrno = errno;
622 return SQLITE_IOERR_DIR_CLOSE;
626 if (pFile->h >= 0 && close(pFile->h)) {
627 pFile->lastErrno = errno;
628 return SQLITE_IOERR_CLOSE;
630 sqlite3_free(pFile->pUnused);
631 memset(pFile, 0, sizeof(ChromiumFile));
635 // Closes a ChromiumFile, including locking operations. Returns a SQLite error code.
636 static int chromiumClose(sqlite3_file* id)
641 ChromiumFile* pFile = reinterpret_cast<ChromiumFile*>(id);
642 chromiumUnlock(id, SQLITE_LOCK_NONE);
643 if (pFile->pOpen && pFile->pOpen->nLock) {
644 // If there are outstanding locks, do not actually close the file just
645 // yet because that would clear those locks.
646 ChromiumOpenInfo* pOpen = pFile->pOpen;
647 ChromiumUnusedFd* p = pFile->pUnused;
648 p->pNext = pOpen->pUnused;
653 releaseLockInfo(pFile->pLock);
654 releaseOpenInfo(pFile->pOpen);
655 return chromiumCloseNoLock(id);
658 static int chromiumCheckReservedLockNoop(sqlite3_file*, int* pResOut)
664 static int chromiumLockNoop(sqlite3_file*, int)
669 static int chromiumUnlockNoop(sqlite3_file*, int)
674 // Seeks to the requested offset and reads up to |cnt| bytes into |pBuf|. Returns number of bytes actually read.
675 static int seekAndRead(ChromiumFile* id, sqlite3_int64 offset, void* pBuf, int cnt)
677 sqlite_int64 newOffset = lseek(id->h, offset, SEEK_SET);
678 if (newOffset != offset) {
679 id->lastErrno = (newOffset == -1) ? errno : 0;
682 int got = read(id->h, pBuf, cnt);
684 id->lastErrno = errno;
688 // Reads data from file into a buffer. Returns a SQLite error code.
689 static int chromiumRead(sqlite3_file* id, void* pBuf, int amt, sqlite3_int64 offset)
691 ChromiumFile* pFile = reinterpret_cast<ChromiumFile*>(id);
694 // The bytes in the locking range should never be read.
695 ASSERT(!pFile->pUnused || offset >= SQLitePendingByte + 512 || offset + amt <= SQLitePendingByte);
697 int got = seekAndRead(pFile, offset, pBuf, amt);
702 return SQLITE_IOERR_READ;
704 // Unread parts of the buffer must be zero-filled.
705 memset(&(reinterpret_cast<char*>(pBuf))[got], 0, amt - got);
706 pFile->lastErrno = 0;
707 return SQLITE_IOERR_SHORT_READ;
710 // Seeks to the requested offset and writes up to |cnt| bytes. Returns number of bytes actually written.
711 static int seekAndWrite(ChromiumFile* id, sqlite_int64 offset, const void* pBuf, int cnt)
713 sqlite_int64 newOffset = lseek(id->h, offset, SEEK_SET);
714 if (newOffset != offset) {
715 id->lastErrno = (newOffset == -1) ? errno : 0;
718 int got = write(id->h, pBuf, cnt);
720 id->lastErrno = errno;
724 // Writes data from buffer into a file. Returns a SQLite error code.
725 static int chromiumWrite(sqlite3_file* id, const void* pBuf, int amt, sqlite3_int64 offset)
727 ChromiumFile* pFile = reinterpret_cast<ChromiumFile*>(id);
731 // The bytes in the locking range should never be written.
732 ASSERT(!pFile->pUnused || offset >= SQLitePendingByte + 512 || offset + amt <= SQLitePendingByte);
735 while (amt > 0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt)) > 0) {
738 pBuf = &(reinterpret_cast<const char*>(pBuf))[wrote];
742 return SQLITE_IOERR_WRITE;
743 pFile->lastErrno = 0;
749 static bool syncWrapper(int fd, bool fullSync)
752 bool success = false;
754 success = !fcntl(fd, F_FULLFSYNC, 0);
756 success = !fsync(fd);
759 return !fdatasync(fd);
763 // Makes sure all writes to a particular file are committed to disk. Returns a SQLite error code.
764 static int chromiumSync(sqlite3_file* id, int flags)
766 ASSERT((flags & 0x0F) == SQLITE_SYNC_NORMAL || (flags & 0x0F) == SQLITE_SYNC_FULL);
768 ChromiumFile* pFile = reinterpret_cast<ChromiumFile*>(id);
771 bool isFullSync = ((flags & 0x0F) == SQLITE_SYNC_FULL);
773 if (!syncWrapper(pFile->h, isFullSync)) {
774 pFile->lastErrno = errno;
775 return SQLITE_IOERR_FSYNC;
778 if (pFile->dirfd >= 0) {
781 // Ignore directory sync failures, see http://www.sqlite.org/cvstrac/tktview?tn=1657.
782 syncWrapper(pFile->dirfd, false);
785 if (!close(pFile->dirfd))
788 pFile->lastErrno = errno;
789 return SQLITE_IOERR_DIR_CLOSE;
796 // Truncates an open file to the specified size. Returns a SQLite error code.
797 static int chromiumTruncate(sqlite3_file* id, sqlite_int64 nByte)
799 ChromiumFile* pFile = reinterpret_cast<ChromiumFile*>(id);
802 if (ftruncate(pFile->h, nByte)) {
803 pFile->lastErrno = errno;
804 return SQLITE_IOERR_TRUNCATE;
810 // Determines the size of a file in bytes. Returns a SQLite error code.
811 static int chromiumFileSize(sqlite3_file* id, sqlite_int64* pSize)
813 ChromiumFile* pFile = reinterpret_cast<ChromiumFile*>(id);
817 if (fstat(pFile->h, &buf)) {
818 pFile->lastErrno = errno;
819 return SQLITE_IOERR_FSTAT;
821 *pSize = buf.st_size;
823 // When opening a zero-size database, findLockInfo writes a single byte into that file
824 // in order to work around a bug in the OS X msdos filesystem. In order to avoid problems
825 // with upper layers, we need to report this file size as zero even though it is really 1.
826 // See http://www.sqlite.org/cvstrac/tktview?tn=3260.
833 static int chromiumFileControl(sqlite3_file* id, int op, void* pArg)
835 ChromiumFile* pFile = reinterpret_cast<ChromiumFile*>(id);
839 case SQLITE_FCNTL_LOCKSTATE:
840 *reinterpret_cast<int*>(pArg) = pFile->locktype;
842 case SQLITE_LAST_ERRNO:
843 *reinterpret_cast<int*>(pArg) = pFile->lastErrno;
849 // Same as SQLITE_DEFAULT_SECTOR_SIZE from sqlite's os.h.
850 static const int SQLiteDefaultSectorSize = 512;
852 static int chromiumSectorSize(sqlite3_file*)
854 return SQLiteDefaultSectorSize;
857 static int chromiumDeviceCharacteristics(sqlite3_file*)
862 static const sqlite3_io_methods posixIoMethods = {
872 chromiumCheckReservedLock,
875 chromiumDeviceCharacteristics
878 static const sqlite3_io_methods nolockIoMethods = {
888 chromiumCheckReservedLockNoop,
891 chromiumDeviceCharacteristics
894 // Initializes a ChromiumFile. Returns a SQLite error code.
895 static int fillInChromiumFile(sqlite3_vfs* pVfs, int h, int dirfd, sqlite3_file* pId, const char* zFilename, int noLock)
897 ChromiumFile* pNew = reinterpret_cast<ChromiumFile*>(pId);
899 ASSERT(!pNew->pLock);
900 ASSERT(!pNew->pOpen);
906 const sqlite3_io_methods* pLockingStyle;
908 pLockingStyle = &nolockIoMethods;
910 pLockingStyle = &posixIoMethods;
911 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
912 if (rc != SQLITE_OK) {
913 // If an error occured in findLockInfo(), close the file descriptor
914 // immediately. This can happen in two scenarios:
916 // (a) A call to fstat() failed.
917 // (b) A malloc failed.
919 // Scenario (b) may only occur if the process is holding no other
920 // file descriptors open on the same file. If there were other file
921 // descriptors on this file, then no malloc would be required by
922 // findLockInfo(). If this is the case, it is quite safe to close
923 // handle h - as it is guaranteed that no posix locks will be released
926 // If scenario (a) caused the error then things are not so safe. The
927 // implicit assumption here is that if fstat() fails, things are in
928 // such bad shape that dropping a lock or two doesn't matter much.
935 if (rc != SQLITE_OK) {
941 pNew->pMethod = pLockingStyle;
945 // Searches for an unused file descriptor that was opened on the database
946 // file identified by zPath with matching flags. Returns 0 if not found.
947 static ChromiumUnusedFd* findReusableFd(const char* zPath, int flags)
949 ChromiumUnusedFd* pUnused = 0;
952 if (!stat(zPath, &sStat)) {
954 id.dev = sStat.st_dev;
955 id.ino = sStat.st_ino;
957 ChromiumOpenInfo* pO = 0;
958 for (pO = openList; pO && memcmp(&id, &pO->fileId, sizeof(id)); pO = pO->pNext) { }
960 ChromiumUnusedFd** pp;
961 for (pp = &pO->pUnused; *pp && (*pp)->flags != flags; pp = &((*pp)->pNext)) { }
964 *pp = pUnused->pNext;
972 // vfs - pointer to the sqlite3_vfs object.
973 // fileName - the name of the file.
974 // id - the structure that will manipulate the newly opened file.
975 // desiredFlags - the desired open mode flags.
976 // usedFlags - the actual open mode flags that were used.
977 static int chromiumOpen(sqlite3_vfs* vfs, const char* fileName,
978 sqlite3_file* id, int desiredFlags, int* usedFlags)
980 // The mask 0x00007F00 gives us the 7 bits that determine the type of the file SQLite is trying to open.
981 int fileType = desiredFlags & 0x00007F00;
983 memset(id, 0, sizeof(ChromiumFile));
984 ChromiumFile* chromiumFile = reinterpret_cast<ChromiumFile*>(id);
986 if (fileType == SQLITE_OPEN_MAIN_DB) {
987 ChromiumUnusedFd* unusedFd = findReusableFd(fileName, desiredFlags);
991 unusedFd = static_cast<ChromiumUnusedFd*>(sqlite3_malloc(sizeof(*unusedFd)));
995 chromiumFile->pUnused = unusedFd;
999 fd = PlatformBridge::databaseOpenFile(fileName, desiredFlags);
1000 if ((fd < 0) && (desiredFlags & SQLITE_OPEN_READWRITE)) {
1001 int newFlags = (desiredFlags & ~(SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE)) | SQLITE_OPEN_READONLY;
1002 fd = PlatformBridge::databaseOpenFile(fileName, newFlags);
1006 sqlite3_free(chromiumFile->pUnused);
1007 return SQLITE_CANTOPEN;
1011 *usedFlags = desiredFlags;
1012 if (chromiumFile->pUnused) {
1013 chromiumFile->pUnused->fd = fd;
1014 chromiumFile->pUnused->flags = desiredFlags;
1017 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
1019 int noLock = (fileType != SQLITE_OPEN_MAIN_DB);
1020 int rc = fillInChromiumFile(vfs, fd, -1, id, fileName, noLock);
1021 if (rc != SQLITE_OK)
1022 sqlite3_free(chromiumFile->pUnused);
1026 // Deletes the given file.
1028 // vfs - pointer to the sqlite3_vfs object.
1029 // fileName - the name of the file.
1030 // syncDir - determines if the directory to which this file belongs
1031 // should be synched after the file is deleted.
1032 static int chromiumDelete(sqlite3_vfs*, const char* fileName, int syncDir)
1034 return PlatformBridge::databaseDeleteFile(fileName, syncDir);
1037 // Check the existance and status of the given file.
1039 // vfs - pointer to the sqlite3_vfs object.
1040 // fileName - the name of the file.
1041 // flag - the type of test to make on this file.
1042 // res - the result.
1043 static int chromiumAccess(sqlite3_vfs*, const char* fileName, int flag, int* res)
1045 int attr = static_cast<int>(PlatformBridge::databaseGetFileAttributes(fileName));
1052 case SQLITE_ACCESS_EXISTS:
1053 *res = 1; // if the file doesn't exist, attr < 0
1055 case SQLITE_ACCESS_READWRITE:
1056 *res = (attr & W_OK) && (attr & R_OK);
1058 case SQLITE_ACCESS_READ:
1059 *res = (attr & R_OK);
1062 return SQLITE_ERROR;
1068 // Turns a relative pathname into a full pathname.
1070 // vfs - pointer to the sqlite3_vfs object.
1071 // relativePath - the relative path.
1072 // bufSize - the size of the output buffer in bytes.
1073 // absolutePath - the output buffer where the absolute path will be stored.
1074 static int chromiumFullPathname(sqlite3_vfs* vfs, const char* relativePath,
1075 int, char* absolutePath)
1077 // The renderer process doesn't need to know the absolute path of the file
1078 sqlite3_snprintf(vfs->mxPathname, absolutePath, "%s", relativePath);
1082 #ifndef SQLITE_OMIT_LOAD_EXTENSION
1083 // We disallow loading DSOs inside the renderer process, so the following procedures are no-op.
1084 static void* chromiumDlOpen(sqlite3_vfs*, const char*)
1089 static void chromiumDlError(sqlite3_vfs*, int, char*)
1093 static void (*chromiumDlSym(sqlite3_vfs*, void*, const char*))()
1098 static void chromiumDlClose(sqlite3_vfs*, void*)
1102 #define chromiumDlOpen 0
1103 #define chromiumDlError 0
1104 #define chromiumDlSym 0
1105 #define chromiumDlClose 0
1106 #endif // SQLITE_OMIT_LOAD_EXTENSION
1108 // Generates a seed for SQLite's PRNG.
1109 static int chromiumRandomness(sqlite3_vfs*, int nBuf, char *zBuf)
1111 ASSERT(static_cast<size_t>(nBuf) >= (sizeof(time_t) + sizeof(int)));
1113 memset(zBuf, 0, nBuf);
1114 int fd = open("/dev/urandom", O_RDONLY);
1118 memcpy(zBuf, &t, sizeof(t));
1120 memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
1121 return sizeof(t) + sizeof(pid);
1123 nBuf = read(fd, zBuf, nBuf);
1128 // Sleeps for at least |microseconds|, and returns the actual
1129 // amount of time spent sleeping (in microseconds).
1130 static int chromiumSleep(sqlite3_vfs*, int microseconds)
1133 usleep(microseconds);
1134 return microseconds;
1136 // Round to the nearest second.
1137 int seconds = (microseconds + 999999) / 1000000;
1139 return seconds * 1000000;
1143 // Retrieves the current system time (UTC).
1144 static int chromiumCurrentTime(sqlite3_vfs*, double* now)
1146 struct timeval timeval;
1147 gettimeofday(&timeval, 0);
1148 *now = 2440587.5 + timeval.tv_sec / 86400.0 + timeval.tv_usec / 86400000000.0;
1152 // This is not yet implemented in SQLite core.
1153 static int chromiumGetLastError(sqlite3_vfs*, int, char*)
1158 // Same as MAX_PATHNAME from sqlite's os_unix.c.
1159 static const int chromiumMaxPathname = 512;
1163 void SQLiteFileSystem::registerSQLiteVFS()
1165 static sqlite3_vfs chromium_vfs = {
1167 sizeof(ChromiumFile),
1168 chromiumMaxPathname,
1175 chromiumFullPathname,
1182 chromiumCurrentTime,
1183 chromiumGetLastError
1185 sqlite3_vfs_register(&chromium_vfs, 0);
1188 } // namespace WebCore