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

Side by Side Diff: third_party/sqlite/src/src/os_unix.c

Issue 5626002: Update sqlite to 3.7.3. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src/third_party/sqlite/src
Patch Set: Update version in doc. Created 10 years 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 | Annotate | Revision Log
OLDNEW
1 /* 1 /*
2 ** 2004 May 22 2 ** 2004 May 22
3 ** 3 **
4 ** The author disclaims copyright to this source code. In place of 4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing: 5 ** a legal notice, here is a blessing:
6 ** 6 **
7 ** May you do good and not evil. 7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others. 8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give. 9 ** May you share freely, never taking more than you give.
10 ** 10 **
(...skipping 101 matching lines...) Expand 10 before | Expand all | Expand 10 after
112 /* 112 /*
113 ** standard include files. 113 ** standard include files.
114 */ 114 */
115 #include <sys/types.h> 115 #include <sys/types.h>
116 #include <sys/stat.h> 116 #include <sys/stat.h>
117 #include <fcntl.h> 117 #include <fcntl.h>
118 #include <unistd.h> 118 #include <unistd.h>
119 #include <time.h> 119 #include <time.h>
120 #include <sys/time.h> 120 #include <sys/time.h>
121 #include <errno.h> 121 #include <errno.h>
122 #include <sys/mman.h>
122 123
123 #if SQLITE_ENABLE_LOCKING_STYLE 124 #if SQLITE_ENABLE_LOCKING_STYLE
124 # include <sys/ioctl.h> 125 # include <sys/ioctl.h>
125 # if OS_VXWORKS 126 # if OS_VXWORKS
126 # include <semaphore.h> 127 # include <semaphore.h>
127 # include <limits.h> 128 # include <limits.h>
128 # else 129 # else
129 # include <sys/file.h> 130 # include <sys/file.h>
130 # include <sys/param.h> 131 # include <sys/param.h>
131 # include <sys/mount.h>
132 # endif 132 # endif
133 #endif /* SQLITE_ENABLE_LOCKING_STYLE */ 133 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
134 134
135 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
136 # include <sys/mount.h>
137 #endif
138
139 /*
140 ** Allowed values of unixFile.fsFlags
141 */
142 #define SQLITE_FSFLAGS_IS_MSDOS 0x1
143
135 /* 144 /*
136 ** If we are to be thread-safe, include the pthreads header and define 145 ** If we are to be thread-safe, include the pthreads header and define
137 ** the SQLITE_UNIX_THREADS macro. 146 ** the SQLITE_UNIX_THREADS macro.
138 */ 147 */
139 #if SQLITE_THREADSAFE 148 #if SQLITE_THREADSAFE
140 # include <pthread.h> 149 # include <pthread.h>
141 # define SQLITE_UNIX_THREADS 1 150 # define SQLITE_UNIX_THREADS 1
142 #endif 151 #endif
143 152
144 /* 153 /*
(...skipping 14 matching lines...) Expand all
159 ** Maximum supported path-length. 168 ** Maximum supported path-length.
160 */ 169 */
161 #define MAX_PATHNAME 512 170 #define MAX_PATHNAME 512
162 171
163 /* 172 /*
164 ** Only set the lastErrno if the error code is a real error and not 173 ** Only set the lastErrno if the error code is a real error and not
165 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK 174 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
166 */ 175 */
167 #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY)) 176 #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
168 177
178 /* Forward references */
179 typedef struct unixShm unixShm; /* Connection shared memory */
180 typedef struct unixShmNode unixShmNode; /* Shared memory instance */
181 typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
182 typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
169 183
170 /* 184 /*
171 ** Sometimes, after a file handle is closed by SQLite, the file descriptor 185 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
172 ** cannot be closed immediately. In these cases, instances of the following 186 ** cannot be closed immediately. In these cases, instances of the following
173 ** structure are used to store the file descriptor while waiting for an 187 ** structure are used to store the file descriptor while waiting for an
174 ** opportunity to either close or reuse it. 188 ** opportunity to either close or reuse it.
175 */ 189 */
176 typedef struct UnixUnusedFd UnixUnusedFd;
177 struct UnixUnusedFd { 190 struct UnixUnusedFd {
178 int fd; /* File descriptor to close */ 191 int fd; /* File descriptor to close */
179 int flags; /* Flags this file descriptor was opened with */ 192 int flags; /* Flags this file descriptor was opened with */
180 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */ 193 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
181 }; 194 };
182 195
183 /* 196 /*
184 ** The unixFile structure is subclass of sqlite3_file specific to the unix 197 ** The unixFile structure is subclass of sqlite3_file specific to the unix
185 ** VFS implementations. 198 ** VFS implementations.
186 */ 199 */
187 typedef struct unixFile unixFile; 200 typedef struct unixFile unixFile;
188 struct unixFile { 201 struct unixFile {
189 sqlite3_io_methods const *pMethod; /* Always the first entry */ 202 sqlite3_io_methods const *pMethod; /* Always the first entry */
190 struct unixOpenCnt *pOpen; /* Info about all open fd's on this inode */ 203 unixInodeInfo *pInode; /* Info about locks on this inode */
191 struct unixLockInfo *pLock; /* Info about locks on this inode */ 204 int h; /* The file descriptor */
192 int h; /* The file descriptor */ 205 int dirfd; /* File descriptor for the directory */
193 int dirfd; /* File descriptor for the directory */ 206 unsigned char eFileLock; /* The type of lock held on this fd */
194 unsigned char locktype; /* The type of lock held on this fd */ 207 int lastErrno; /* The unix errno from last I/O error */
195 int lastErrno; /* The unix errno from the last I/O error */ 208 void *lockingContext; /* Locking style specific state */
196 void *lockingContext; /* Locking style specific state */ 209 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
197 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */ 210 int fileFlags; /* Miscellanous flags */
198 int fileFlags; /* Miscellanous flags */ 211 const char *zPath; /* Name of the file */
212 unixShm *pShm; /* Shared memory segment information */
213 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
199 #if SQLITE_ENABLE_LOCKING_STYLE 214 #if SQLITE_ENABLE_LOCKING_STYLE
200 int openFlags; /* The flags specified at open() */ 215 int openFlags; /* The flags specified at open() */
201 #endif 216 #endif
202 #if SQLITE_THREADSAFE && defined(__linux__) 217 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
203 pthread_t tid; /* The thread that "owns" this unixFile */ 218 unsigned fsFlags; /* cached details from statfs() */
204 #endif 219 #endif
205 #if OS_VXWORKS 220 #if OS_VXWORKS
206 int isDelete; /* Delete on close if true */ 221 int isDelete; /* Delete on close if true */
207 struct vxworksFileId *pId; /* Unique file ID */ 222 struct vxworksFileId *pId; /* Unique file ID */
208 #endif 223 #endif
209 #ifndef NDEBUG 224 #ifndef NDEBUG
210 /* The next group of variables are used to track whether or not the 225 /* The next group of variables are used to track whether or not the
211 ** transaction counter in bytes 24-27 of database files are updated 226 ** transaction counter in bytes 24-27 of database files are updated
212 ** whenever any part of the database changes. An assertion fault will 227 ** whenever any part of the database changes. An assertion fault will
213 ** occur if a file is updated without also updating the transaction 228 ** occur if a file is updated without also updating the transaction
214 ** counter. This test is made to avoid new problems similar to the 229 ** counter. This test is made to avoid new problems similar to the
215 ** one described by ticket #3584. 230 ** one described by ticket #3584.
216 */ 231 */
217 unsigned char transCntrChng; /* True if the transaction counter changed */ 232 unsigned char transCntrChng; /* True if the transaction counter changed */
(...skipping 51 matching lines...) Expand 10 before | Expand all | Expand 10 after
269 */ 284 */
270 #if SQLITE_THREADSAFE 285 #if SQLITE_THREADSAFE
271 #define threadid pthread_self() 286 #define threadid pthread_self()
272 #else 287 #else
273 #define threadid 0 288 #define threadid 0
274 #endif 289 #endif
275 290
276 291
277 /* 292 /*
278 ** Helper functions to obtain and relinquish the global mutex. The 293 ** Helper functions to obtain and relinquish the global mutex. The
279 ** global mutex is used to protect the unixOpenCnt, unixLockInfo and 294 ** global mutex is used to protect the unixInodeInfo and
280 ** vxworksFileId objects used by this file, all of which may be 295 ** vxworksFileId objects used by this file, all of which may be
281 ** shared by multiple threads. 296 ** shared by multiple threads.
282 ** 297 **
283 ** Function unixMutexHeld() is used to assert() that the global mutex 298 ** Function unixMutexHeld() is used to assert() that the global mutex
284 ** is held when required. This function is only used as part of assert() 299 ** is held when required. This function is only used as part of assert()
285 ** statements. e.g. 300 ** statements. e.g.
286 ** 301 **
287 ** unixEnterMutex() 302 ** unixEnterMutex()
288 ** assert( unixMutexHeld() ); 303 ** assert( unixMutexHeld() );
289 ** unixEnterLeave() 304 ** unixEnterLeave()
(...skipping 10 matching lines...) Expand all
300 } 315 }
301 #endif 316 #endif
302 317
303 318
304 #ifdef SQLITE_DEBUG 319 #ifdef SQLITE_DEBUG
305 /* 320 /*
306 ** Helper function for printing out trace information from debugging 321 ** Helper function for printing out trace information from debugging
307 ** binaries. This returns the string represetation of the supplied 322 ** binaries. This returns the string represetation of the supplied
308 ** integer lock-type. 323 ** integer lock-type.
309 */ 324 */
310 static const char *locktypeName(int locktype){ 325 static const char *azFileLock(int eFileLock){
311 switch( locktype ){ 326 switch( eFileLock ){
312 case NO_LOCK: return "NONE"; 327 case NO_LOCK: return "NONE";
313 case SHARED_LOCK: return "SHARED"; 328 case SHARED_LOCK: return "SHARED";
314 case RESERVED_LOCK: return "RESERVED"; 329 case RESERVED_LOCK: return "RESERVED";
315 case PENDING_LOCK: return "PENDING"; 330 case PENDING_LOCK: return "PENDING";
316 case EXCLUSIVE_LOCK: return "EXCLUSIVE"; 331 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
317 } 332 }
318 return "ERROR"; 333 return "ERROR";
319 } 334 }
320 #endif 335 #endif
321 336
(...skipping 316 matching lines...) Expand 10 before | Expand all | Expand 10 after
638 ** 653 **
639 ** Any attempt to lock or unlock a file first checks the locking 654 ** Any attempt to lock or unlock a file first checks the locking
640 ** structure. The fcntl() system call is only invoked to set a 655 ** structure. The fcntl() system call is only invoked to set a
641 ** POSIX lock if the internal lock structure transitions between 656 ** POSIX lock if the internal lock structure transitions between
642 ** a locked and an unlocked state. 657 ** a locked and an unlocked state.
643 ** 658 **
644 ** But wait: there are yet more problems with POSIX advisory locks. 659 ** But wait: there are yet more problems with POSIX advisory locks.
645 ** 660 **
646 ** If you close a file descriptor that points to a file that has locks, 661 ** If you close a file descriptor that points to a file that has locks,
647 ** all locks on that file that are owned by the current process are 662 ** all locks on that file that are owned by the current process are
648 ** released. To work around this problem, each unixFile structure contains 663 ** released. To work around this problem, each unixInodeInfo object
649 ** a pointer to an unixOpenCnt structure. There is one unixOpenCnt structure 664 ** maintains a count of the number of pending locks on tha inode.
650 ** per open inode, which means that multiple unixFile can point to a single 665 ** When an attempt is made to close an unixFile, if there are
651 ** unixOpenCnt. When an attempt is made to close an unixFile, if there are
652 ** other unixFile open on the same inode that are holding locks, the call 666 ** other unixFile open on the same inode that are holding locks, the call
653 ** to close() the file descriptor is deferred until all of the locks clear. 667 ** to close() the file descriptor is deferred until all of the locks clear.
654 ** The unixOpenCnt structure keeps a list of file descriptors that need to 668 ** The unixInodeInfo structure keeps a list of file descriptors that need to
655 ** be closed and that list is walked (and cleared) when the last lock 669 ** be closed and that list is walked (and cleared) when the last lock
656 ** clears. 670 ** clears.
657 ** 671 **
658 ** Yet another problem: LinuxThreads do not play well with posix locks. 672 ** Yet another problem: LinuxThreads do not play well with posix locks.
659 ** 673 **
660 ** Many older versions of linux use the LinuxThreads library which is 674 ** Many older versions of linux use the LinuxThreads library which is
661 ** not posix compliant. Under LinuxThreads, a lock created by thread 675 ** not posix compliant. Under LinuxThreads, a lock created by thread
662 ** A cannot be modified or overridden by a different thread B. 676 ** A cannot be modified or overridden by a different thread B.
663 ** Only thread A can modify the lock. Locking behavior is correct 677 ** Only thread A can modify the lock. Locking behavior is correct
664 ** if the appliation uses the newer Native Posix Thread Library (NPTL) 678 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
665 ** on linux - with NPTL a lock created by thread A can override locks 679 ** on linux - with NPTL a lock created by thread A can override locks
666 ** in thread B. But there is no way to know at compile-time which 680 ** in thread B. But there is no way to know at compile-time which
667 ** threading library is being used. So there is no way to know at 681 ** threading library is being used. So there is no way to know at
668 ** compile-time whether or not thread A can override locks on thread B. 682 ** compile-time whether or not thread A can override locks on thread B.
669 ** We have to do a run-time check to discover the behavior of the 683 ** One has to do a run-time check to discover the behavior of the
670 ** current process. 684 ** current process.
671 ** 685 **
672 ** On systems where thread A is unable to modify locks created by 686 ** SQLite used to support LinuxThreads. But support for LinuxThreads
673 ** thread B, we have to keep track of which thread created each 687 ** was dropped beginning with version 3.7.0. SQLite will still work with
674 ** lock. Hence there is an extra field in the key to the unixLockInfo 688 ** LinuxThreads provided that (1) there is no more than one connection
675 ** structure to record this information. And on those systems it 689 ** per database file in the same process and (2) database connections
676 ** is illegal to begin a transaction in one thread and finish it 690 ** do not move across threads.
677 ** in another. For this latter restriction, there is no work-around.
678 ** It is a limitation of LinuxThreads.
679 */ 691 */
680 692
681 /* 693 /*
682 ** Set or check the unixFile.tid field. This field is set when an unixFile
683 ** is first opened. All subsequent uses of the unixFile verify that the
684 ** same thread is operating on the unixFile. Some operating systems do
685 ** not allow locks to be overridden by other threads and that restriction
686 ** means that sqlite3* database handles cannot be moved from one thread
687 ** to another while locks are held.
688 **
689 ** Version 3.3.1 (2006-01-15): unixFile can be moved from one thread to
690 ** another as long as we are running on a system that supports threads
691 ** overriding each others locks (which is now the most common behavior)
692 ** or if no locks are held. But the unixFile.pLock field needs to be
693 ** recomputed because its key includes the thread-id. See the
694 ** transferOwnership() function below for additional information
695 */
696 #if SQLITE_THREADSAFE && defined(__linux__)
697 # define SET_THREADID(X) (X)->tid = pthread_self()
698 # define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
699 !pthread_equal((X)->tid, pthread_self()))
700 #else
701 # define SET_THREADID(X)
702 # define CHECK_THREADID(X) 0
703 #endif
704
705 /*
706 ** An instance of the following structure serves as the key used 694 ** An instance of the following structure serves as the key used
707 ** to locate a particular unixOpenCnt structure given its inode. This 695 ** to locate a particular unixInodeInfo object.
708 ** is the same as the unixLockKey except that the thread ID is omitted.
709 */ 696 */
710 struct unixFileId { 697 struct unixFileId {
711 dev_t dev; /* Device number */ 698 dev_t dev; /* Device number */
712 #if OS_VXWORKS 699 #if OS_VXWORKS
713 struct vxworksFileId *pId; /* Unique file ID for vxworks. */ 700 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
714 #else 701 #else
715 ino_t ino; /* Inode number */ 702 ino_t ino; /* Inode number */
716 #endif 703 #endif
717 }; 704 };
718 705
719 /* 706 /*
720 ** An instance of the following structure serves as the key used
721 ** to locate a particular unixLockInfo structure given its inode.
722 **
723 ** If threads cannot override each others locks (LinuxThreads), then we
724 ** set the unixLockKey.tid field to the thread ID. If threads can override
725 ** each others locks (Posix and NPTL) then tid is always set to zero.
726 ** tid is omitted if we compile without threading support or on an OS
727 ** other than linux.
728 */
729 struct unixLockKey {
730 struct unixFileId fid; /* Unique identifier for the file */
731 #if SQLITE_THREADSAFE && defined(__linux__)
732 pthread_t tid; /* Thread ID of lock owner. Zero if not using LinuxThreads */
733 #endif
734 };
735
736 /*
737 ** An instance of the following structure is allocated for each open 707 ** An instance of the following structure is allocated for each open
738 ** inode. Or, on LinuxThreads, there is one of these structures for 708 ** inode. Or, on LinuxThreads, there is one of these structures for
739 ** each inode opened by each thread. 709 ** each inode opened by each thread.
740 ** 710 **
741 ** A single inode can have multiple file descriptors, so each unixFile 711 ** A single inode can have multiple file descriptors, so each unixFile
742 ** structure contains a pointer to an instance of this object and this 712 ** structure contains a pointer to an instance of this object and this
743 ** object keeps a count of the number of unixFile pointing to it. 713 ** object keeps a count of the number of unixFile pointing to it.
744 */ 714 */
745 struct unixLockInfo { 715 struct unixInodeInfo {
746 struct unixLockKey lockKey; /* The lookup key */ 716 struct unixFileId fileId; /* The lookup key */
747 int cnt; /* Number of SHARED locks held */ 717 int nShared; /* Number of SHARED locks held */
748 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */ 718 int eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
749 int nRef; /* Number of pointers to this structure */ 719 int nRef; /* Number of pointers to this structure */
750 struct unixLockInfo *pNext; /* List of all unixLockInfo objects */ 720 unixShmNode *pShmNode; /* Shared memory associated with this inode */
751 struct unixLockInfo *pPrev; /* .... doubly linked */ 721 int nLock; /* Number of outstanding file locks */
722 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
723 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
724 unixInodeInfo *pPrev; /* .... doubly linked */
725 #if defined(SQLITE_ENABLE_LOCKING_STYLE)
726 unsigned long long sharedByte; /* for AFP simulated shared lock */
727 #endif
728 #if OS_VXWORKS
729 sem_t *pSem; /* Named POSIX semaphore */
730 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
731 #endif
752 }; 732 };
753 733
754 /* 734 /*
755 ** An instance of the following structure is allocated for each open 735 ** A lists of all unixInodeInfo objects.
756 ** inode. This structure keeps track of the number of locks on that
757 ** inode. If a close is attempted against an inode that is holding
758 ** locks, the close is deferred until all locks clear by adding the
759 ** file descriptor to be closed to the pending list.
760 **
761 ** TODO: Consider changing this so that there is only a single file
762 ** descriptor for each open file, even when it is opened multiple times.
763 ** The close() system call would only occur when the last database
764 ** using the file closes.
765 */ 736 */
766 struct unixOpenCnt { 737 static unixInodeInfo *inodeList = 0;
767 struct unixFileId fileId; /* The lookup key */
768 int nRef; /* Number of pointers to this structure */
769 int nLock; /* Number of outstanding locks */
770 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
771 #if OS_VXWORKS
772 sem_t *pSem; /* Named POSIX semaphore */
773 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
774 #endif
775 struct unixOpenCnt *pNext, *pPrev; /* List of all unixOpenCnt objects */
776 };
777 738
778 /* 739 /*
779 ** Lists of all unixLockInfo and unixOpenCnt objects. These used to be hash 740 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
780 ** tables. But the number of objects is rarely more than a dozen and 741 ** If all such file descriptors are closed without error, the list is
781 ** never exceeds a few thousand. And lookup is not on a critical 742 ** cleared and SQLITE_OK returned.
782 ** path so a simple linked list will suffice. 743 **
783 */ 744 ** Otherwise, if an error occurs, then successfully closed file descriptor
784 static struct unixLockInfo *lockList = 0; 745 ** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
785 static struct unixOpenCnt *openList = 0; 746 ** not deleted and SQLITE_IOERR_CLOSE returned.
747 */
748 static int closePendingFds(unixFile *pFile){
749 int rc = SQLITE_OK;
750 unixInodeInfo *pInode = pFile->pInode;
751 UnixUnusedFd *pError = 0;
752 UnixUnusedFd *p;
753 UnixUnusedFd *pNext;
754 for(p=pInode->pUnused; p; p=pNext){
755 pNext = p->pNext;
756 if( close(p->fd) ){
757 pFile->lastErrno = errno;
758 rc = SQLITE_IOERR_CLOSE;
759 p->pNext = pError;
760 pError = p;
761 }else{
762 sqlite3_free(p);
763 }
764 }
765 pInode->pUnused = pError;
766 return rc;
767 }
786 768
787 /* 769 /*
788 ** This variable remembers whether or not threads can override each others 770 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
789 ** locks.
790 **
791 ** 0: No. Threads cannot override each others locks. (LinuxThreads)
792 ** 1: Yes. Threads can override each others locks. (Posix & NLPT)
793 ** -1: We don't know yet.
794 **
795 ** On some systems, we know at compile-time if threads can override each
796 ** others locks. On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
797 ** will be set appropriately. On other systems, we have to check at
798 ** runtime. On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
799 ** undefined.
800 **
801 ** This variable normally has file scope only. But during testing, we make
802 ** it a global so that the test code can change its value in order to verify
803 ** that the right stuff happens in either case.
804 */
805 #if SQLITE_THREADSAFE && defined(__linux__)
806 # ifndef SQLITE_THREAD_OVERRIDE_LOCK
807 # define SQLITE_THREAD_OVERRIDE_LOCK -1
808 # endif
809 # ifdef SQLITE_TEST
810 int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
811 # else
812 static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
813 # endif
814 #endif
815
816 /*
817 ** This structure holds information passed into individual test
818 ** threads by the testThreadLockingBehavior() routine.
819 */
820 struct threadTestData {
821 int fd; /* File to be locked */
822 struct flock lock; /* The locking operation */
823 int result; /* Result of the locking operation */
824 };
825
826 #if SQLITE_THREADSAFE && defined(__linux__)
827 /*
828 ** This function is used as the main routine for a thread launched by
829 ** testThreadLockingBehavior(). It tests whether the shared-lock obtained
830 ** by the main thread in testThreadLockingBehavior() conflicts with a
831 ** hypothetical write-lock obtained by this thread on the same file.
832 **
833 ** The write-lock is not actually acquired, as this is not possible if
834 ** the file is open in read-only mode (see ticket #3472).
835 */
836 static void *threadLockingTest(void *pArg){
837 struct threadTestData *pData = (struct threadTestData*)pArg;
838 pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
839 return pArg;
840 }
841 #endif /* SQLITE_THREADSAFE && defined(__linux__) */
842
843
844 #if SQLITE_THREADSAFE && defined(__linux__)
845 /*
846 ** This procedure attempts to determine whether or not threads
847 ** can override each others locks then sets the
848 ** threadsOverrideEachOthersLocks variable appropriately.
849 */
850 static void testThreadLockingBehavior(int fd_orig){
851 int fd;
852 int rc;
853 struct threadTestData d;
854 struct flock l;
855 pthread_t t;
856
857 fd = dup(fd_orig);
858 if( fd<0 ) return;
859 memset(&l, 0, sizeof(l));
860 l.l_type = F_RDLCK;
861 l.l_len = 1;
862 l.l_start = 0;
863 l.l_whence = SEEK_SET;
864 rc = fcntl(fd_orig, F_SETLK, &l);
865 if( rc!=0 ) return;
866 memset(&d, 0, sizeof(d));
867 d.fd = fd;
868 d.lock = l;
869 d.lock.l_type = F_WRLCK;
870 if( pthread_create(&t, 0, threadLockingTest, &d)==0 ){
871 pthread_join(t, 0);
872 }
873 close(fd);
874 if( d.result!=0 ) return;
875 threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
876 }
877 #endif /* SQLITE_THREADSAFE && defined(__linux__) */
878
879 /*
880 ** Release a unixLockInfo structure previously allocated by findLockInfo().
881 ** 771 **
882 ** The mutex entered using the unixEnterMutex() function must be held 772 ** The mutex entered using the unixEnterMutex() function must be held
883 ** when this function is called. 773 ** when this function is called.
884 */ 774 */
885 static void releaseLockInfo(struct unixLockInfo *pLock){ 775 static void releaseInodeInfo(unixFile *pFile){
776 unixInodeInfo *pInode = pFile->pInode;
886 assert( unixMutexHeld() ); 777 assert( unixMutexHeld() );
887 if( pLock ){ 778 if( pInode ){
888 pLock->nRef--; 779 pInode->nRef--;
889 if( pLock->nRef==0 ){ 780 if( pInode->nRef==0 ){
890 if( pLock->pPrev ){ 781 assert( pInode->pShmNode==0 );
891 assert( pLock->pPrev->pNext==pLock ); 782 closePendingFds(pFile);
892 pLock->pPrev->pNext = pLock->pNext; 783 if( pInode->pPrev ){
784 assert( pInode->pPrev->pNext==pInode );
785 pInode->pPrev->pNext = pInode->pNext;
893 }else{ 786 }else{
894 assert( lockList==pLock ); 787 assert( inodeList==pInode );
895 lockList = pLock->pNext; 788 inodeList = pInode->pNext;
896 } 789 }
897 if( pLock->pNext ){ 790 if( pInode->pNext ){
898 assert( pLock->pNext->pPrev==pLock ); 791 assert( pInode->pNext->pPrev==pInode );
899 pLock->pNext->pPrev = pLock->pPrev; 792 pInode->pNext->pPrev = pInode->pPrev;
900 } 793 }
901 sqlite3_free(pLock); 794 sqlite3_free(pInode);
902 } 795 }
903 } 796 }
904 } 797 }
905 798
906 /* 799 /*
907 ** Release a unixOpenCnt structure previously allocated by findLockInfo(). 800 ** Given a file descriptor, locate the unixInodeInfo object that
908 ** 801 ** describes that file descriptor. Create a new one if necessary. The
909 ** The mutex entered using the unixEnterMutex() function must be held 802 ** return value might be uninitialized if an error occurs.
910 ** when this function is called.
911 */
912 static void releaseOpenCnt(struct unixOpenCnt *pOpen){
913 assert( unixMutexHeld() );
914 if( pOpen ){
915 pOpen->nRef--;
916 if( pOpen->nRef==0 ){
917 if( pOpen->pPrev ){
918 assert( pOpen->pPrev->pNext==pOpen );
919 pOpen->pPrev->pNext = pOpen->pNext;
920 }else{
921 assert( openList==pOpen );
922 openList = pOpen->pNext;
923 }
924 if( pOpen->pNext ){
925 assert( pOpen->pNext->pPrev==pOpen );
926 pOpen->pNext->pPrev = pOpen->pPrev;
927 }
928 #if SQLITE_THREADSAFE && defined(__linux__)
929 assert( !pOpen->pUnused || threadsOverrideEachOthersLocks==0 );
930 #endif
931
932 /* If pOpen->pUnused is not null, then memory and file-descriptors
933 ** are leaked.
934 **
935 ** This will only happen if, under Linuxthreads, the user has opened
936 ** a transaction in one thread, then attempts to close the database
937 ** handle from another thread (without first unlocking the db file).
938 ** This is a misuse. */
939 sqlite3_free(pOpen);
940 }
941 }
942 }
943
944 /*
945 ** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
946 ** describes that file descriptor. Create new ones if necessary. The
947 ** return values might be uninitialized if an error occurs.
948 ** 803 **
949 ** The mutex entered using the unixEnterMutex() function must be held 804 ** The mutex entered using the unixEnterMutex() function must be held
950 ** when this function is called. 805 ** when this function is called.
951 ** 806 **
952 ** Return an appropriate error code. 807 ** Return an appropriate error code.
953 */ 808 */
954 static int findLockInfo( 809 static int findInodeInfo(
955 unixFile *pFile, /* Unix file with file desc used in the key */ 810 unixFile *pFile, /* Unix file with file desc used in the key */
956 struct unixLockInfo **ppLock, /* Return the unixLockInfo structure here */ 811 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
957 struct unixOpenCnt **ppOpen /* Return the unixOpenCnt structure here */
958 ){ 812 ){
959 int rc; /* System call return code */ 813 int rc; /* System call return code */
960 int fd; /* The file descriptor for pFile */ 814 int fd; /* The file descriptor for pFile */
961 struct unixLockKey lockKey; /* Lookup key for the unixLockInfo structure */ 815 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
962 struct unixFileId fileId; /* Lookup key for the unixOpenCnt struct */
963 struct stat statbuf; /* Low-level file information */ 816 struct stat statbuf; /* Low-level file information */
964 struct unixLockInfo *pLock = 0;/* Candidate unixLockInfo object */ 817 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
965 struct unixOpenCnt *pOpen; /* Candidate unixOpenCnt object */
966 818
967 assert( unixMutexHeld() ); 819 assert( unixMutexHeld() );
968 820
969 /* Get low-level information about the file that we can used to 821 /* Get low-level information about the file that we can used to
970 ** create a unique name for the file. 822 ** create a unique name for the file.
971 */ 823 */
972 fd = pFile->h; 824 fd = pFile->h;
973 rc = fstat(fd, &statbuf); 825 rc = fstat(fd, &statbuf);
974 if( rc!=0 ){ 826 if( rc!=0 ){
975 pFile->lastErrno = errno; 827 pFile->lastErrno = errno;
976 #ifdef EOVERFLOW 828 #ifdef EOVERFLOW
977 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS; 829 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
978 #endif 830 #endif
979 return SQLITE_IOERR; 831 return SQLITE_IOERR;
980 } 832 }
981 833
982 #ifdef __APPLE__ 834 #ifdef __APPLE__
983 /* On OS X on an msdos filesystem, the inode number is reported 835 /* On OS X on an msdos filesystem, the inode number is reported
984 ** incorrectly for zero-size files. See ticket #3260. To work 836 ** incorrectly for zero-size files. See ticket #3260. To work
985 ** around this problem (we consider it a bug in OS X, not SQLite) 837 ** around this problem (we consider it a bug in OS X, not SQLite)
986 ** we always increase the file size to 1 by writing a single byte 838 ** we always increase the file size to 1 by writing a single byte
987 ** prior to accessing the inode number. The one byte written is 839 ** prior to accessing the inode number. The one byte written is
988 ** an ASCII 'S' character which also happens to be the first byte 840 ** an ASCII 'S' character which also happens to be the first byte
989 ** in the header of every SQLite database. In this way, if there 841 ** in the header of every SQLite database. In this way, if there
990 ** is a race condition such that another thread has already populated 842 ** is a race condition such that another thread has already populated
991 ** the first page of the database, no damage is done. 843 ** the first page of the database, no damage is done.
992 */ 844 */
993 if( statbuf.st_size==0 ){ 845 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
994 rc = write(fd, "S", 1); 846 rc = write(fd, "S", 1);
995 if( rc!=1 ){ 847 if( rc!=1 ){
848 pFile->lastErrno = errno;
996 return SQLITE_IOERR; 849 return SQLITE_IOERR;
997 } 850 }
998 rc = fstat(fd, &statbuf); 851 rc = fstat(fd, &statbuf);
999 if( rc!=0 ){ 852 if( rc!=0 ){
1000 pFile->lastErrno = errno; 853 pFile->lastErrno = errno;
1001 return SQLITE_IOERR; 854 return SQLITE_IOERR;
1002 } 855 }
1003 } 856 }
1004 #endif 857 #endif
1005 858
1006 memset(&lockKey, 0, sizeof(lockKey)); 859 memset(&fileId, 0, sizeof(fileId));
1007 lockKey.fid.dev = statbuf.st_dev; 860 fileId.dev = statbuf.st_dev;
1008 #if OS_VXWORKS 861 #if OS_VXWORKS
1009 lockKey.fid.pId = pFile->pId; 862 fileId.pId = pFile->pId;
1010 #else 863 #else
1011 lockKey.fid.ino = statbuf.st_ino; 864 fileId.ino = statbuf.st_ino;
1012 #endif 865 #endif
1013 #if SQLITE_THREADSAFE && defined(__linux__) 866 pInode = inodeList;
1014 if( threadsOverrideEachOthersLocks<0 ){ 867 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
1015 testThreadLockingBehavior(fd); 868 pInode = pInode->pNext;
1016 } 869 }
1017 lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self(); 870 if( pInode==0 ){
1018 #endif 871 pInode = sqlite3_malloc( sizeof(*pInode) );
1019 fileId = lockKey.fid; 872 if( pInode==0 ){
1020 if( ppLock!=0 ){ 873 return SQLITE_NOMEM;
1021 pLock = lockList;
1022 while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
1023 pLock = pLock->pNext;
1024 } 874 }
1025 if( pLock==0 ){ 875 memset(pInode, 0, sizeof(*pInode));
1026 pLock = sqlite3_malloc( sizeof(*pLock) ); 876 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
1027 if( pLock==0 ){ 877 pInode->nRef = 1;
1028 rc = SQLITE_NOMEM; 878 pInode->pNext = inodeList;
1029 goto exit_findlockinfo; 879 pInode->pPrev = 0;
1030 } 880 if( inodeList ) inodeList->pPrev = pInode;
1031 pLock->lockKey = lockKey; 881 inodeList = pInode;
1032 pLock->nRef = 1; 882 }else{
1033 pLock->cnt = 0; 883 pInode->nRef++;
1034 pLock->locktype = 0;
1035 pLock->pNext = lockList;
1036 pLock->pPrev = 0;
1037 if( lockList ) lockList->pPrev = pLock;
1038 lockList = pLock;
1039 }else{
1040 pLock->nRef++;
1041 }
1042 *ppLock = pLock;
1043 } 884 }
1044 if( ppOpen!=0 ){ 885 *ppInode = pInode;
1045 pOpen = openList; 886 return SQLITE_OK;
1046 while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
1047 pOpen = pOpen->pNext;
1048 }
1049 if( pOpen==0 ){
1050 pOpen = sqlite3_malloc( sizeof(*pOpen) );
1051 if( pOpen==0 ){
1052 releaseLockInfo(pLock);
1053 rc = SQLITE_NOMEM;
1054 goto exit_findlockinfo;
1055 }
1056 memset(pOpen, 0, sizeof(*pOpen));
1057 pOpen->fileId = fileId;
1058 pOpen->nRef = 1;
1059 pOpen->pNext = openList;
1060 if( openList ) openList->pPrev = pOpen;
1061 openList = pOpen;
1062 }else{
1063 pOpen->nRef++;
1064 }
1065 *ppOpen = pOpen;
1066 }
1067
1068 exit_findlockinfo:
1069 return rc;
1070 } 887 }
1071 888
1072 /*
1073 ** If we are currently in a different thread than the thread that the
1074 ** unixFile argument belongs to, then transfer ownership of the unixFile
1075 ** over to the current thread.
1076 **
1077 ** A unixFile is only owned by a thread on systems that use LinuxThreads.
1078 **
1079 ** Ownership transfer is only allowed if the unixFile is currently unlocked.
1080 ** If the unixFile is locked and an ownership is wrong, then return
1081 ** SQLITE_MISUSE. SQLITE_OK is returned if everything works.
1082 */
1083 #if SQLITE_THREADSAFE && defined(__linux__)
1084 static int transferOwnership(unixFile *pFile){
1085 int rc;
1086 pthread_t hSelf;
1087 if( threadsOverrideEachOthersLocks ){
1088 /* Ownership transfers not needed on this system */
1089 return SQLITE_OK;
1090 }
1091 hSelf = pthread_self();
1092 if( pthread_equal(pFile->tid, hSelf) ){
1093 /* We are still in the same thread */
1094 OSTRACE1("No-transfer, same thread\n");
1095 return SQLITE_OK;
1096 }
1097 if( pFile->locktype!=NO_LOCK ){
1098 /* We cannot change ownership while we are holding a lock! */
1099 return SQLITE_MISUSE;
1100 }
1101 OSTRACE4("Transfer ownership of %d from %d to %d\n",
1102 pFile->h, pFile->tid, hSelf);
1103 pFile->tid = hSelf;
1104 if (pFile->pLock != NULL) {
1105 releaseLockInfo(pFile->pLock);
1106 rc = findLockInfo(pFile, &pFile->pLock, 0);
1107 OSTRACE5("LOCK %d is now %s(%s,%d)\n", pFile->h,
1108 locktypeName(pFile->locktype),
1109 locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
1110 return rc;
1111 } else {
1112 return SQLITE_OK;
1113 }
1114 }
1115 #else /* if not SQLITE_THREADSAFE */
1116 /* On single-threaded builds, ownership transfer is a no-op */
1117 # define transferOwnership(X) SQLITE_OK
1118 #endif /* SQLITE_THREADSAFE */
1119
1120 889
1121 /* 890 /*
1122 ** This routine checks if there is a RESERVED lock held on the specified 891 ** This routine checks if there is a RESERVED lock held on the specified
1123 ** file by this or any other process. If such a lock is held, set *pResOut 892 ** file by this or any other process. If such a lock is held, set *pResOut
1124 ** to a non-zero value otherwise *pResOut is set to zero. The return value 893 ** to a non-zero value otherwise *pResOut is set to zero. The return value
1125 ** is set to SQLITE_OK unless an I/O error occurs during lock checking. 894 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
1126 */ 895 */
1127 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){ 896 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
1128 int rc = SQLITE_OK; 897 int rc = SQLITE_OK;
1129 int reserved = 0; 898 int reserved = 0;
1130 unixFile *pFile = (unixFile*)id; 899 unixFile *pFile = (unixFile*)id;
1131 900
1132 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); 901 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1133 902
1134 assert( pFile ); 903 assert( pFile );
1135 unixEnterMutex(); /* Because pFile->pLock is shared across threads */ 904 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
1136 905
1137 /* Check if a thread in this process holds such a lock */ 906 /* Check if a thread in this process holds such a lock */
1138 if( pFile->pLock->locktype>SHARED_LOCK ){ 907 if( pFile->pInode->eFileLock>SHARED_LOCK ){
1139 reserved = 1; 908 reserved = 1;
1140 } 909 }
1141 910
1142 /* Otherwise see if some other process holds it. 911 /* Otherwise see if some other process holds it.
1143 */ 912 */
1144 #ifndef __DJGPP__ 913 #ifndef __DJGPP__
1145 if( !reserved ){ 914 if( !reserved ){
1146 struct flock lock; 915 struct flock lock;
1147 lock.l_whence = SEEK_SET; 916 lock.l_whence = SEEK_SET;
1148 lock.l_start = RESERVED_BYTE; 917 lock.l_start = RESERVED_BYTE;
1149 lock.l_len = 1; 918 lock.l_len = 1;
1150 lock.l_type = F_WRLCK; 919 lock.l_type = F_WRLCK;
1151 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) { 920 if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
1152 int tErrno = errno; 921 int tErrno = errno;
1153 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK); 922 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
1154 pFile->lastErrno = tErrno; 923 pFile->lastErrno = tErrno;
1155 } else if( lock.l_type!=F_UNLCK ){ 924 } else if( lock.l_type!=F_UNLCK ){
1156 reserved = 1; 925 reserved = 1;
1157 } 926 }
1158 } 927 }
1159 #endif 928 #endif
1160 929
1161 unixLeaveMutex(); 930 unixLeaveMutex();
1162 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved); 931 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
1163 932
1164 *pResOut = reserved; 933 *pResOut = reserved;
1165 return rc; 934 return rc;
1166 } 935 }
1167 936
1168 /* 937 /*
1169 ** Perform a file locking operation on a range of bytes in a file. 938 ** Lock the file with the lock specified by parameter eFileLock - one
1170 ** The "op" parameter should be one of F_RDLCK, F_WRLCK, or F_UNLCK.
1171 ** Return 0 on success or -1 for failure. On failure, write the error
1172 ** code into *pErrcode.
1173 **
1174 ** If the SQLITE_WHOLE_FILE_LOCKING bit is clear, then only lock
1175 ** the range of bytes on the locking page between SHARED_FIRST and
1176 ** SHARED_SIZE. If SQLITE_WHOLE_FILE_LOCKING is set, then lock all
1177 ** bytes from 0 up to but not including PENDING_BYTE, and all bytes
1178 ** that follow SHARED_FIRST.
1179 **
1180 ** In other words, of SQLITE_WHOLE_FILE_LOCKING if false (the historical
1181 ** default case) then only lock a small range of bytes from SHARED_FIRST
1182 ** through SHARED_FIRST+SHARED_SIZE-1. But if SQLITE_WHOLE_FILE_LOCKING is
1183 ** true then lock every byte in the file except for PENDING_BYTE and
1184 ** RESERVED_BYTE.
1185 **
1186 ** SQLITE_WHOLE_FILE_LOCKING=true overlaps SQLITE_WHOLE_FILE_LOCKING=false
1187 ** and so the locking schemes are compatible. One type of lock will
1188 ** effectively exclude the other type. The reason for using the
1189 ** SQLITE_WHOLE_FILE_LOCKING=true is that by indicating the full range
1190 ** of bytes to be read or written, we give hints to NFS to help it
1191 ** maintain cache coherency. On the other hand, whole file locking
1192 ** is slower, so we don't want to use it except for NFS.
1193 */
1194 static int rangeLock(unixFile *pFile, int op, int *pErrcode){
1195 struct flock lock;
1196 int rc;
1197 lock.l_type = op;
1198 lock.l_start = SHARED_FIRST;
1199 lock.l_whence = SEEK_SET;
1200 if( (pFile->fileFlags & SQLITE_WHOLE_FILE_LOCKING)==0 ){
1201 lock.l_len = SHARED_SIZE;
1202 rc = fcntl(pFile->h, F_SETLK, &lock);
1203 *pErrcode = errno;
1204 }else{
1205 lock.l_len = 0;
1206 rc = fcntl(pFile->h, F_SETLK, &lock);
1207 *pErrcode = errno;
1208 if( NEVER(op==F_UNLCK) || rc!=(-1) ){
1209 lock.l_start = 0;
1210 lock.l_len = PENDING_BYTE;
1211 rc = fcntl(pFile->h, F_SETLK, &lock);
1212 if( ALWAYS(op!=F_UNLCK) && rc==(-1) ){
1213 *pErrcode = errno;
1214 lock.l_type = F_UNLCK;
1215 lock.l_start = SHARED_FIRST;
1216 lock.l_len = 0;
1217 fcntl(pFile->h, F_SETLK, &lock);
1218 }
1219 }
1220 }
1221 return rc;
1222 }
1223
1224 /*
1225 ** Lock the file with the lock specified by parameter locktype - one
1226 ** of the following: 939 ** of the following:
1227 ** 940 **
1228 ** (1) SHARED_LOCK 941 ** (1) SHARED_LOCK
1229 ** (2) RESERVED_LOCK 942 ** (2) RESERVED_LOCK
1230 ** (3) PENDING_LOCK 943 ** (3) PENDING_LOCK
1231 ** (4) EXCLUSIVE_LOCK 944 ** (4) EXCLUSIVE_LOCK
1232 ** 945 **
1233 ** Sometimes when requesting one lock state, additional lock states 946 ** Sometimes when requesting one lock state, additional lock states
1234 ** are inserted in between. The locking might fail on one of the later 947 ** are inserted in between. The locking might fail on one of the later
1235 ** transitions leaving the lock state different from what it started but 948 ** transitions leaving the lock state different from what it started but
1236 ** still short of its goal. The following chart shows the allowed 949 ** still short of its goal. The following chart shows the allowed
1237 ** transitions and the inserted intermediate states: 950 ** transitions and the inserted intermediate states:
1238 ** 951 **
1239 ** UNLOCKED -> SHARED 952 ** UNLOCKED -> SHARED
1240 ** SHARED -> RESERVED 953 ** SHARED -> RESERVED
1241 ** SHARED -> (PENDING) -> EXCLUSIVE 954 ** SHARED -> (PENDING) -> EXCLUSIVE
1242 ** RESERVED -> (PENDING) -> EXCLUSIVE 955 ** RESERVED -> (PENDING) -> EXCLUSIVE
1243 ** PENDING -> EXCLUSIVE 956 ** PENDING -> EXCLUSIVE
1244 ** 957 **
1245 ** This routine will only increase a lock. Use the sqlite3OsUnlock() 958 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
1246 ** routine to lower a locking level. 959 ** routine to lower a locking level.
1247 */ 960 */
1248 static int unixLock(sqlite3_file *id, int locktype){ 961 static int unixLock(sqlite3_file *id, int eFileLock){
1249 /* The following describes the implementation of the various locks and 962 /* The following describes the implementation of the various locks and
1250 ** lock transitions in terms of the POSIX advisory shared and exclusive 963 ** lock transitions in terms of the POSIX advisory shared and exclusive
1251 ** lock primitives (called read-locks and write-locks below, to avoid 964 ** lock primitives (called read-locks and write-locks below, to avoid
1252 ** confusion with SQLite lock names). The algorithms are complicated 965 ** confusion with SQLite lock names). The algorithms are complicated
1253 ** slightly in order to be compatible with windows systems simultaneously 966 ** slightly in order to be compatible with windows systems simultaneously
1254 ** accessing the same database file, in case that is ever required. 967 ** accessing the same database file, in case that is ever required.
1255 ** 968 **
1256 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved 969 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
1257 ** byte', each single bytes at well known offsets, and the 'shared byte 970 ** byte', each single bytes at well known offsets, and the 'shared byte
1258 ** range', a range of 510 bytes at a well known offset. 971 ** range', a range of 510 bytes at a well known offset.
(...skipping 20 matching lines...) Expand all
1279 ** within this range, this ensures that no other locks are held on the 992 ** within this range, this ensures that no other locks are held on the
1280 ** database. 993 ** database.
1281 ** 994 **
1282 ** The reason a single byte cannot be used instead of the 'shared byte 995 ** The reason a single byte cannot be used instead of the 'shared byte
1283 ** range' is that some versions of windows do not support read-locks. By 996 ** range' is that some versions of windows do not support read-locks. By
1284 ** locking a random byte from a range, concurrent SHARED locks may exist 997 ** locking a random byte from a range, concurrent SHARED locks may exist
1285 ** even if the locking primitive used is always a write-lock. 998 ** even if the locking primitive used is always a write-lock.
1286 */ 999 */
1287 int rc = SQLITE_OK; 1000 int rc = SQLITE_OK;
1288 unixFile *pFile = (unixFile*)id; 1001 unixFile *pFile = (unixFile*)id;
1289 struct unixLockInfo *pLock = pFile->pLock; 1002 unixInodeInfo *pInode = pFile->pInode;
1290 struct flock lock; 1003 struct flock lock;
1291 int s = 0; 1004 int s = 0;
1292 int tErrno; 1005 int tErrno = 0;
1293 1006
1294 assert( pFile ); 1007 assert( pFile );
1295 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d\n", pFile->h, 1008 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
1296 locktypeName(locktype), locktypeName(pFile->locktype), 1009 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
1297 locktypeName(pLock->locktype), pLock->cnt , getpid()); 1010 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
1298 1011
1299 /* If there is already a lock of this type or more restrictive on the 1012 /* If there is already a lock of this type or more restrictive on the
1300 ** unixFile, do nothing. Don't use the end_lock: exit path, as 1013 ** unixFile, do nothing. Don't use the end_lock: exit path, as
1301 ** unixEnterMutex() hasn't been called yet. 1014 ** unixEnterMutex() hasn't been called yet.
1302 */ 1015 */
1303 if( pFile->locktype>=locktype ){ 1016 if( pFile->eFileLock>=eFileLock ){
1304 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h, 1017 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
1305 locktypeName(locktype)); 1018 azFileLock(eFileLock)));
1306 return SQLITE_OK; 1019 return SQLITE_OK;
1307 } 1020 }
1308 1021
1309 /* Make sure the locking sequence is correct. 1022 /* Make sure the locking sequence is correct.
1310 ** (1) We never move from unlocked to anything higher than shared lock. 1023 ** (1) We never move from unlocked to anything higher than shared lock.
1311 ** (2) SQLite never explicitly requests a pendig lock. 1024 ** (2) SQLite never explicitly requests a pendig lock.
1312 ** (3) A shared lock is always held when a reserve lock is requested. 1025 ** (3) A shared lock is always held when a reserve lock is requested.
1313 */ 1026 */
1314 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK ); 1027 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
1315 assert( locktype!=PENDING_LOCK ); 1028 assert( eFileLock!=PENDING_LOCK );
1316 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK ); 1029 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
1317 1030
1318 /* This mutex is needed because pFile->pLock is shared across threads 1031 /* This mutex is needed because pFile->pInode is shared across threads
1319 */ 1032 */
1320 unixEnterMutex(); 1033 unixEnterMutex();
1321 1034 pInode = pFile->pInode;
1322 /* Make sure the current thread owns the pFile.
1323 */
1324 rc = transferOwnership(pFile);
1325 if( rc!=SQLITE_OK ){
1326 unixLeaveMutex();
1327 return rc;
1328 }
1329 pLock = pFile->pLock;
1330 1035
1331 /* If some thread using this PID has a lock via a different unixFile* 1036 /* If some thread using this PID has a lock via a different unixFile*
1332 ** handle that precludes the requested lock, return BUSY. 1037 ** handle that precludes the requested lock, return BUSY.
1333 */ 1038 */
1334 if( (pFile->locktype!=pLock->locktype && 1039 if( (pFile->eFileLock!=pInode->eFileLock &&
1335 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK)) 1040 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
1336 ){ 1041 ){
1337 rc = SQLITE_BUSY; 1042 rc = SQLITE_BUSY;
1338 goto end_lock; 1043 goto end_lock;
1339 } 1044 }
1340 1045
1341 /* If a SHARED lock is requested, and some thread using this PID already 1046 /* If a SHARED lock is requested, and some thread using this PID already
1342 ** has a SHARED or RESERVED lock, then increment reference counts and 1047 ** has a SHARED or RESERVED lock, then increment reference counts and
1343 ** return SQLITE_OK. 1048 ** return SQLITE_OK.
1344 */ 1049 */
1345 if( locktype==SHARED_LOCK && 1050 if( eFileLock==SHARED_LOCK &&
1346 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){ 1051 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
1347 assert( locktype==SHARED_LOCK ); 1052 assert( eFileLock==SHARED_LOCK );
1348 assert( pFile->locktype==0 ); 1053 assert( pFile->eFileLock==0 );
1349 assert( pLock->cnt>0 ); 1054 assert( pInode->nShared>0 );
1350 pFile->locktype = SHARED_LOCK; 1055 pFile->eFileLock = SHARED_LOCK;
1351 pLock->cnt++; 1056 pInode->nShared++;
1352 pFile->pOpen->nLock++; 1057 pInode->nLock++;
1353 goto end_lock; 1058 goto end_lock;
1354 } 1059 }
1355 1060
1356 1061
1357 /* A PENDING lock is needed before acquiring a SHARED lock and before 1062 /* A PENDING lock is needed before acquiring a SHARED lock and before
1358 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will 1063 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
1359 ** be released. 1064 ** be released.
1360 */ 1065 */
1361 lock.l_len = 1L; 1066 lock.l_len = 1L;
1362 lock.l_whence = SEEK_SET; 1067 lock.l_whence = SEEK_SET;
1363 if( locktype==SHARED_LOCK 1068 if( eFileLock==SHARED_LOCK
1364 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK) 1069 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
1365 ){ 1070 ){
1366 lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK); 1071 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
1367 lock.l_start = PENDING_BYTE; 1072 lock.l_start = PENDING_BYTE;
1368 s = fcntl(pFile->h, F_SETLK, &lock); 1073 s = fcntl(pFile->h, F_SETLK, &lock);
1369 if( s==(-1) ){ 1074 if( s==(-1) ){
1370 tErrno = errno; 1075 tErrno = errno;
1371 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 1076 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1372 if( IS_LOCK_ERROR(rc) ){ 1077 if( IS_LOCK_ERROR(rc) ){
1373 pFile->lastErrno = tErrno; 1078 pFile->lastErrno = tErrno;
1374 } 1079 }
1375 goto end_lock; 1080 goto end_lock;
1376 } 1081 }
1377 } 1082 }
1378 1083
1379 1084
1380 /* If control gets to this point, then actually go ahead and make 1085 /* If control gets to this point, then actually go ahead and make
1381 ** operating system calls for the specified lock. 1086 ** operating system calls for the specified lock.
1382 */ 1087 */
1383 if( locktype==SHARED_LOCK ){ 1088 if( eFileLock==SHARED_LOCK ){
1384 assert( pLock->cnt==0 ); 1089 assert( pInode->nShared==0 );
1385 assert( pLock->locktype==0 ); 1090 assert( pInode->eFileLock==0 );
1386 1091
1387 /* Now get the read-lock */ 1092 /* Now get the read-lock */
1388 s = rangeLock(pFile, F_RDLCK, &tErrno); 1093 lock.l_start = SHARED_FIRST;
1389 1094 lock.l_len = SHARED_SIZE;
1095 if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
1096 tErrno = errno;
1097 }
1390 /* Drop the temporary PENDING lock */ 1098 /* Drop the temporary PENDING lock */
1391 lock.l_start = PENDING_BYTE; 1099 lock.l_start = PENDING_BYTE;
1392 lock.l_len = 1L; 1100 lock.l_len = 1L;
1393 lock.l_type = F_UNLCK; 1101 lock.l_type = F_UNLCK;
1394 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){ 1102 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
1395 if( s != -1 ){ 1103 if( s != -1 ){
1396 /* This could happen with a network mount */ 1104 /* This could happen with a network mount */
1397 tErrno = errno; 1105 tErrno = errno;
1398 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 1106 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1399 if( IS_LOCK_ERROR(rc) ){ 1107 if( IS_LOCK_ERROR(rc) ){
1400 pFile->lastErrno = tErrno; 1108 pFile->lastErrno = tErrno;
1401 } 1109 }
1402 goto end_lock; 1110 goto end_lock;
1403 } 1111 }
1404 } 1112 }
1405 if( s==(-1) ){ 1113 if( s==(-1) ){
1406 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 1114 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1407 if( IS_LOCK_ERROR(rc) ){ 1115 if( IS_LOCK_ERROR(rc) ){
1408 pFile->lastErrno = tErrno; 1116 pFile->lastErrno = tErrno;
1409 } 1117 }
1410 }else{ 1118 }else{
1411 pFile->locktype = SHARED_LOCK; 1119 pFile->eFileLock = SHARED_LOCK;
1412 pFile->pOpen->nLock++; 1120 pInode->nLock++;
1413 pLock->cnt = 1; 1121 pInode->nShared = 1;
1414 } 1122 }
1415 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){ 1123 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
1416 /* We are trying for an exclusive lock but another thread in this 1124 /* We are trying for an exclusive lock but another thread in this
1417 ** same process is still holding a shared lock. */ 1125 ** same process is still holding a shared lock. */
1418 rc = SQLITE_BUSY; 1126 rc = SQLITE_BUSY;
1419 }else{ 1127 }else{
1420 /* The request was for a RESERVED or EXCLUSIVE lock. It is 1128 /* The request was for a RESERVED or EXCLUSIVE lock. It is
1421 ** assumed that there is a SHARED or greater lock on the file 1129 ** assumed that there is a SHARED or greater lock on the file
1422 ** already. 1130 ** already.
1423 */ 1131 */
1424 assert( 0!=pFile->locktype ); 1132 assert( 0!=pFile->eFileLock );
1425 lock.l_type = F_WRLCK; 1133 lock.l_type = F_WRLCK;
1426 switch( locktype ){ 1134 switch( eFileLock ){
1427 case RESERVED_LOCK: 1135 case RESERVED_LOCK:
1428 lock.l_start = RESERVED_BYTE; 1136 lock.l_start = RESERVED_BYTE;
1429 s = fcntl(pFile->h, F_SETLK, &lock);
1430 tErrno = errno;
1431 break; 1137 break;
1432 case EXCLUSIVE_LOCK: 1138 case EXCLUSIVE_LOCK:
1433 s = rangeLock(pFile, F_WRLCK, &tErrno); 1139 lock.l_start = SHARED_FIRST;
1140 lock.l_len = SHARED_SIZE;
1434 break; 1141 break;
1435 default: 1142 default:
1436 assert(0); 1143 assert(0);
1437 } 1144 }
1145 s = fcntl(pFile->h, F_SETLK, &lock);
1438 if( s==(-1) ){ 1146 if( s==(-1) ){
1147 tErrno = errno;
1439 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 1148 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1440 if( IS_LOCK_ERROR(rc) ){ 1149 if( IS_LOCK_ERROR(rc) ){
1441 pFile->lastErrno = tErrno; 1150 pFile->lastErrno = tErrno;
1442 } 1151 }
1443 } 1152 }
1444 } 1153 }
1445 1154
1446 1155
1447 #ifndef NDEBUG 1156 #ifndef NDEBUG
1448 /* Set up the transaction-counter change checking flags when 1157 /* Set up the transaction-counter change checking flags when
1449 ** transitioning from a SHARED to a RESERVED lock. The change 1158 ** transitioning from a SHARED to a RESERVED lock. The change
1450 ** from SHARED to RESERVED marks the beginning of a normal 1159 ** from SHARED to RESERVED marks the beginning of a normal
1451 ** write operation (not a hot journal rollback). 1160 ** write operation (not a hot journal rollback).
1452 */ 1161 */
1453 if( rc==SQLITE_OK 1162 if( rc==SQLITE_OK
1454 && pFile->locktype<=SHARED_LOCK 1163 && pFile->eFileLock<=SHARED_LOCK
1455 && locktype==RESERVED_LOCK 1164 && eFileLock==RESERVED_LOCK
1456 ){ 1165 ){
1457 pFile->transCntrChng = 0; 1166 pFile->transCntrChng = 0;
1458 pFile->dbUpdate = 0; 1167 pFile->dbUpdate = 0;
1459 pFile->inNormalWrite = 1; 1168 pFile->inNormalWrite = 1;
1460 } 1169 }
1461 #endif 1170 #endif
1462 1171
1463 1172
1464 if( rc==SQLITE_OK ){ 1173 if( rc==SQLITE_OK ){
1465 pFile->locktype = locktype; 1174 pFile->eFileLock = eFileLock;
1466 pLock->locktype = locktype; 1175 pInode->eFileLock = eFileLock;
1467 }else if( locktype==EXCLUSIVE_LOCK ){ 1176 }else if( eFileLock==EXCLUSIVE_LOCK ){
1468 pFile->locktype = PENDING_LOCK; 1177 pFile->eFileLock = PENDING_LOCK;
1469 pLock->locktype = PENDING_LOCK; 1178 pInode->eFileLock = PENDING_LOCK;
1470 } 1179 }
1471 1180
1472 end_lock: 1181 end_lock:
1473 unixLeaveMutex(); 1182 unixLeaveMutex();
1474 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype), 1183 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
1475 rc==SQLITE_OK ? "ok" : "failed"); 1184 rc==SQLITE_OK ? "ok" : "failed"));
1476 return rc; 1185 return rc;
1477 } 1186 }
1478 1187
1479 /*
1480 ** Close all file descriptors accumuated in the unixOpenCnt->pUnused list.
1481 ** If all such file descriptors are closed without error, the list is
1482 ** cleared and SQLITE_OK returned.
1483 **
1484 ** Otherwise, if an error occurs, then successfully closed file descriptor
1485 ** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
1486 ** not deleted and SQLITE_IOERR_CLOSE returned.
1487 */
1488 static int closePendingFds(unixFile *pFile){
1489 int rc = SQLITE_OK;
1490 struct unixOpenCnt *pOpen = pFile->pOpen;
1491 UnixUnusedFd *pError = 0;
1492 UnixUnusedFd *p;
1493 UnixUnusedFd *pNext;
1494 for(p=pOpen->pUnused; p; p=pNext){
1495 pNext = p->pNext;
1496 if( close(p->fd) ){
1497 pFile->lastErrno = errno;
1498 rc = SQLITE_IOERR_CLOSE;
1499 p->pNext = pError;
1500 pError = p;
1501 }else{
1502 sqlite3_free(p);
1503 }
1504 }
1505 pOpen->pUnused = pError;
1506 return rc;
1507 }
1508
1509 /* 1188 /*
1510 ** Add the file descriptor used by file handle pFile to the corresponding 1189 ** Add the file descriptor used by file handle pFile to the corresponding
1511 ** pUnused list. 1190 ** pUnused list.
1512 */ 1191 */
1513 static void setPendingFd(unixFile *pFile){ 1192 static void setPendingFd(unixFile *pFile){
1514 struct unixOpenCnt *pOpen = pFile->pOpen; 1193 unixInodeInfo *pInode = pFile->pInode;
1515 UnixUnusedFd *p = pFile->pUnused; 1194 UnixUnusedFd *p = pFile->pUnused;
1516 p->pNext = pOpen->pUnused; 1195 p->pNext = pInode->pUnused;
1517 pOpen->pUnused = p; 1196 pInode->pUnused = p;
1518 pFile->h = -1; 1197 pFile->h = -1;
1519 pFile->pUnused = 0; 1198 pFile->pUnused = 0;
1520 } 1199 }
1521 1200
1522 /* 1201 /*
1523 ** Lower the locking level on file descriptor pFile to locktype. locktype 1202 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
1524 ** must be either NO_LOCK or SHARED_LOCK. 1203 ** must be either NO_LOCK or SHARED_LOCK.
1525 ** 1204 **
1526 ** If the locking level of the file descriptor is already at or below 1205 ** If the locking level of the file descriptor is already at or below
1527 ** the requested locking level, this routine is a no-op. 1206 ** the requested locking level, this routine is a no-op.
1207 **
1208 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
1209 ** the byte range is divided into 2 parts and the first part is unlocked then
1210 ** set to a read lock, then the other part is simply unlocked. This works
1211 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
1212 ** remove the write lock on a region when a read lock is set.
1528 */ 1213 */
1529 static int unixUnlock(sqlite3_file *id, int locktype){ 1214 static int _posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
1530 unixFile *pFile = (unixFile*)id; /* The open file */ 1215 unixFile *pFile = (unixFile*)id;
1531 struct unixLockInfo *pLock; /* Structure describing current lock state */ 1216 unixInodeInfo *pInode;
1532 struct flock lock; /* Information passed into fcntl() */ 1217 struct flock lock;
1533 int rc = SQLITE_OK; /* Return code from this interface */ 1218 int rc = SQLITE_OK;
1534 int h; /* The underlying file descriptor */ 1219 int h;
1535 int tErrno; /* Error code from system call errors */ 1220 int tErrno; /* Error code from system call errors */
1536 1221
1537 assert( pFile ); 1222 assert( pFile );
1538 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype, 1223 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
1539 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid()); 1224 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
1225 getpid()));
1540 1226
1541 assert( locktype<=SHARED_LOCK ); 1227 assert( eFileLock<=SHARED_LOCK );
1542 if( pFile->locktype<=locktype ){ 1228 if( pFile->eFileLock<=eFileLock ){
1543 return SQLITE_OK; 1229 return SQLITE_OK;
1544 } 1230 }
1545 if( CHECK_THREADID(pFile) ){
1546 return SQLITE_MISUSE;
1547 }
1548 unixEnterMutex(); 1231 unixEnterMutex();
1549 h = pFile->h; 1232 h = pFile->h;
1550 pLock = pFile->pLock; 1233 pInode = pFile->pInode;
1551 assert( pLock->cnt!=0 ); 1234 assert( pInode->nShared!=0 );
1552 if( pFile->locktype>SHARED_LOCK ){ 1235 if( pFile->eFileLock>SHARED_LOCK ){
1553 assert( pLock->locktype==pFile->locktype ); 1236 assert( pInode->eFileLock==pFile->eFileLock );
1554 SimulateIOErrorBenign(1); 1237 SimulateIOErrorBenign(1);
1555 SimulateIOError( h=(-1) ) 1238 SimulateIOError( h=(-1) )
1556 SimulateIOErrorBenign(0); 1239 SimulateIOErrorBenign(0);
1557 1240
1558 #ifndef NDEBUG 1241 #ifndef NDEBUG
1559 /* When reducing a lock such that other processes can start 1242 /* When reducing a lock such that other processes can start
1560 ** reading the database file again, make sure that the 1243 ** reading the database file again, make sure that the
1561 ** transaction counter was updated if any part of the database 1244 ** transaction counter was updated if any part of the database
1562 ** file changed. If the transaction counter is not updated, 1245 ** file changed. If the transaction counter is not updated,
1563 ** other connections to the same file might not realize that 1246 ** other connections to the same file might not realize that
1564 ** the file has changed and hence might not know to flush their 1247 ** the file has changed and hence might not know to flush their
1565 ** cache. The use of a stale cache can lead to database corruption. 1248 ** cache. The use of a stale cache can lead to database corruption.
1566 */ 1249 */
1250 #if 0
1567 assert( pFile->inNormalWrite==0 1251 assert( pFile->inNormalWrite==0
1568 || pFile->dbUpdate==0 1252 || pFile->dbUpdate==0
1569 || pFile->transCntrChng==1 ); 1253 || pFile->transCntrChng==1 );
1254 #endif
1570 pFile->inNormalWrite = 0; 1255 pFile->inNormalWrite = 0;
1571 #endif 1256 #endif
1572 1257
1573 1258 /* downgrading to a shared lock on NFS involves clearing the write lock
1574 if( locktype==SHARED_LOCK ){ 1259 ** before establishing the readlock - to avoid a race condition we downgrade
1575 if( rangeLock(pFile, F_RDLCK, &tErrno)==(-1) ){ 1260 ** the lock in 2 blocks, so that part of the range will be covered by a
1576 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK); 1261 ** write lock until the rest is covered by a read lock:
1577 if( IS_LOCK_ERROR(rc) ){ 1262 ** 1: [WWWWW]
1578 pFile->lastErrno = tErrno; 1263 ** 2: [....W]
1264 ** 3: [RRRRW]
1265 ** 4: [RRRR.]
1266 */
1267 if( eFileLock==SHARED_LOCK ){
1268 if( handleNFSUnlock ){
1269 off_t divSize = SHARED_SIZE - 1;
1270
1271 lock.l_type = F_UNLCK;
1272 lock.l_whence = SEEK_SET;
1273 lock.l_start = SHARED_FIRST;
1274 lock.l_len = divSize;
1275 if( fcntl(h, F_SETLK, &lock)==(-1) ){
1276 tErrno = errno;
1277 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1278 if( IS_LOCK_ERROR(rc) ){
1279 pFile->lastErrno = tErrno;
1280 }
1281 goto end_unlock;
1579 } 1282 }
1580 goto end_unlock; 1283 lock.l_type = F_RDLCK;
1284 lock.l_whence = SEEK_SET;
1285 lock.l_start = SHARED_FIRST;
1286 lock.l_len = divSize;
1287 if( fcntl(h, F_SETLK, &lock)==(-1) ){
1288 tErrno = errno;
1289 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1290 if( IS_LOCK_ERROR(rc) ){
1291 pFile->lastErrno = tErrno;
1292 }
1293 goto end_unlock;
1294 }
1295 lock.l_type = F_UNLCK;
1296 lock.l_whence = SEEK_SET;
1297 lock.l_start = SHARED_FIRST+divSize;
1298 lock.l_len = SHARED_SIZE-divSize;
1299 if( fcntl(h, F_SETLK, &lock)==(-1) ){
1300 tErrno = errno;
1301 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1302 if( IS_LOCK_ERROR(rc) ){
1303 pFile->lastErrno = tErrno;
1304 }
1305 goto end_unlock;
1306 }
1307 }else{
1308 lock.l_type = F_RDLCK;
1309 lock.l_whence = SEEK_SET;
1310 lock.l_start = SHARED_FIRST;
1311 lock.l_len = SHARED_SIZE;
1312 if( fcntl(h, F_SETLK, &lock)==(-1) ){
1313 tErrno = errno;
1314 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
1315 if( IS_LOCK_ERROR(rc) ){
1316 pFile->lastErrno = tErrno;
1317 }
1318 goto end_unlock;
1319 }
1581 } 1320 }
1582 } 1321 }
1583 lock.l_type = F_UNLCK; 1322 lock.l_type = F_UNLCK;
1584 lock.l_whence = SEEK_SET; 1323 lock.l_whence = SEEK_SET;
1585 lock.l_start = PENDING_BYTE; 1324 lock.l_start = PENDING_BYTE;
1586 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE ); 1325 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
1587 if( fcntl(h, F_SETLK, &lock)!=(-1) ){ 1326 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
1588 pLock->locktype = SHARED_LOCK; 1327 pInode->eFileLock = SHARED_LOCK;
1589 }else{ 1328 }else{
1590 tErrno = errno; 1329 tErrno = errno;
1591 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 1330 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1592 if( IS_LOCK_ERROR(rc) ){ 1331 if( IS_LOCK_ERROR(rc) ){
1593 pFile->lastErrno = tErrno; 1332 pFile->lastErrno = tErrno;
1594 } 1333 }
1595 goto end_unlock; 1334 goto end_unlock;
1596 } 1335 }
1597 } 1336 }
1598 if( locktype==NO_LOCK ){ 1337 if( eFileLock==NO_LOCK ){
1599 struct unixOpenCnt *pOpen;
1600
1601 /* Decrement the shared lock counter. Release the lock using an 1338 /* Decrement the shared lock counter. Release the lock using an
1602 ** OS call only when all threads in this same process have released 1339 ** OS call only when all threads in this same process have released
1603 ** the lock. 1340 ** the lock.
1604 */ 1341 */
1605 pLock->cnt--; 1342 pInode->nShared--;
1606 if( pLock->cnt==0 ){ 1343 if( pInode->nShared==0 ){
1607 lock.l_type = F_UNLCK; 1344 lock.l_type = F_UNLCK;
1608 lock.l_whence = SEEK_SET; 1345 lock.l_whence = SEEK_SET;
1609 lock.l_start = lock.l_len = 0L; 1346 lock.l_start = lock.l_len = 0L;
1610 SimulateIOErrorBenign(1); 1347 SimulateIOErrorBenign(1);
1611 SimulateIOError( h=(-1) ) 1348 SimulateIOError( h=(-1) )
1612 SimulateIOErrorBenign(0); 1349 SimulateIOErrorBenign(0);
1613 if( fcntl(h, F_SETLK, &lock)!=(-1) ){ 1350 if( fcntl(h, F_SETLK, &lock)!=(-1) ){
1614 pLock->locktype = NO_LOCK; 1351 pInode->eFileLock = NO_LOCK;
1615 }else{ 1352 }else{
1616 tErrno = errno; 1353 tErrno = errno;
1617 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 1354 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1618 if( IS_LOCK_ERROR(rc) ){ 1355 if( IS_LOCK_ERROR(rc) ){
1619 pFile->lastErrno = tErrno; 1356 pFile->lastErrno = tErrno;
1620 } 1357 }
1621 pLock->locktype = NO_LOCK; 1358 pInode->eFileLock = NO_LOCK;
1622 pFile->locktype = NO_LOCK; 1359 pFile->eFileLock = NO_LOCK;
1623 } 1360 }
1624 } 1361 }
1625 1362
1626 /* Decrement the count of locks against this same file. When the 1363 /* Decrement the count of locks against this same file. When the
1627 ** count reaches zero, close any other file descriptors whose close 1364 ** count reaches zero, close any other file descriptors whose close
1628 ** was deferred because of outstanding locks. 1365 ** was deferred because of outstanding locks.
1629 */ 1366 */
1630 pOpen = pFile->pOpen; 1367 pInode->nLock--;
1631 pOpen->nLock--; 1368 assert( pInode->nLock>=0 );
1632 assert( pOpen->nLock>=0 ); 1369 if( pInode->nLock==0 ){
1633 if( pOpen->nLock==0 ){
1634 int rc2 = closePendingFds(pFile); 1370 int rc2 = closePendingFds(pFile);
1635 if( rc==SQLITE_OK ){ 1371 if( rc==SQLITE_OK ){
1636 rc = rc2; 1372 rc = rc2;
1637 } 1373 }
1638 } 1374 }
1639 } 1375 }
1640 1376
1641 end_unlock: 1377 end_unlock:
1642 unixLeaveMutex(); 1378 unixLeaveMutex();
1643 if( rc==SQLITE_OK ) pFile->locktype = locktype; 1379 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
1644 return rc; 1380 return rc;
1645 } 1381 }
1646 1382
1647 /* 1383 /*
1384 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
1385 ** must be either NO_LOCK or SHARED_LOCK.
1386 **
1387 ** If the locking level of the file descriptor is already at or below
1388 ** the requested locking level, this routine is a no-op.
1389 */
1390 static int unixUnlock(sqlite3_file *id, int eFileLock){
1391 return _posixUnlock(id, eFileLock, 0);
1392 }
1393
1394 /*
1648 ** This function performs the parts of the "close file" operation 1395 ** This function performs the parts of the "close file" operation
1649 ** common to all locking schemes. It closes the directory and file 1396 ** common to all locking schemes. It closes the directory and file
1650 ** handles, if they are valid, and sets all fields of the unixFile 1397 ** handles, if they are valid, and sets all fields of the unixFile
1651 ** structure to 0. 1398 ** structure to 0.
1652 ** 1399 **
1653 ** It is *not* necessary to hold the mutex when this routine is called, 1400 ** It is *not* necessary to hold the mutex when this routine is called,
1654 ** even on VxWorks. A mutex will be acquired on VxWorks by the 1401 ** even on VxWorks. A mutex will be acquired on VxWorks by the
1655 ** vxworksReleaseFileId() routine. 1402 ** vxworksReleaseFileId() routine.
1656 */ 1403 */
1657 static int closeUnixFile(sqlite3_file *id){ 1404 static int closeUnixFile(sqlite3_file *id){
(...skipping 17 matching lines...) Expand all
1675 } 1422 }
1676 #if OS_VXWORKS 1423 #if OS_VXWORKS
1677 if( pFile->pId ){ 1424 if( pFile->pId ){
1678 if( pFile->isDelete ){ 1425 if( pFile->isDelete ){
1679 unlink(pFile->pId->zCanonicalName); 1426 unlink(pFile->pId->zCanonicalName);
1680 } 1427 }
1681 vxworksReleaseFileId(pFile->pId); 1428 vxworksReleaseFileId(pFile->pId);
1682 pFile->pId = 0; 1429 pFile->pId = 0;
1683 } 1430 }
1684 #endif 1431 #endif
1685 OSTRACE2("CLOSE %-3d\n", pFile->h); 1432 OSTRACE(("CLOSE %-3d\n", pFile->h));
1686 OpenCounter(-1); 1433 OpenCounter(-1);
1687 sqlite3_free(pFile->pUnused); 1434 sqlite3_free(pFile->pUnused);
1688 memset(pFile, 0, sizeof(unixFile)); 1435 memset(pFile, 0, sizeof(unixFile));
1689 } 1436 }
1690 return SQLITE_OK; 1437 return SQLITE_OK;
1691 } 1438 }
1692 1439
1693 /* 1440 /*
1694 ** Close a file. 1441 ** Close a file.
1695 */ 1442 */
1696 static int unixClose(sqlite3_file *id){ 1443 static int unixClose(sqlite3_file *id){
1697 int rc = SQLITE_OK; 1444 int rc = SQLITE_OK;
1698 if( id ){ 1445 if( id ){
1699 unixFile *pFile = (unixFile *)id; 1446 unixFile *pFile = (unixFile *)id;
1700 unixUnlock(id, NO_LOCK); 1447 unixUnlock(id, NO_LOCK);
1701 unixEnterMutex(); 1448 unixEnterMutex();
1702 if( pFile->pOpen && pFile->pOpen->nLock ){ 1449 if( pFile->pInode && pFile->pInode->nLock ){
1703 /* If there are outstanding locks, do not actually close the file just 1450 /* If there are outstanding locks, do not actually close the file just
1704 ** yet because that would clear those locks. Instead, add the file 1451 ** yet because that would clear those locks. Instead, add the file
1705 ** descriptor to pOpen->pUnused list. It will be automatically closed 1452 ** descriptor to pInode->pUnused list. It will be automatically closed
1706 ** when the last lock is cleared. 1453 ** when the last lock is cleared.
1707 */ 1454 */
1708 setPendingFd(pFile); 1455 setPendingFd(pFile);
1709 } 1456 }
1710 releaseLockInfo(pFile->pLock); 1457 releaseInodeInfo(pFile);
1711 releaseOpenCnt(pFile->pOpen);
1712 rc = closeUnixFile(id); 1458 rc = closeUnixFile(id);
1713 unixLeaveMutex(); 1459 unixLeaveMutex();
1714 } 1460 }
1715 return rc; 1461 return rc;
1716 } 1462 }
1717 1463
1718 /************** End of the posix advisory lock implementation ***************** 1464 /************** End of the posix advisory lock implementation *****************
1719 ******************************************************************************/ 1465 ******************************************************************************/
1720 1466
1721 /****************************************************************************** 1467 /******************************************************************************
(...skipping 78 matching lines...) Expand 10 before | Expand all | Expand 10 after
1800 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) { 1546 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
1801 int rc = SQLITE_OK; 1547 int rc = SQLITE_OK;
1802 int reserved = 0; 1548 int reserved = 0;
1803 unixFile *pFile = (unixFile*)id; 1549 unixFile *pFile = (unixFile*)id;
1804 1550
1805 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); 1551 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1806 1552
1807 assert( pFile ); 1553 assert( pFile );
1808 1554
1809 /* Check if a thread in this process holds such a lock */ 1555 /* Check if a thread in this process holds such a lock */
1810 if( pFile->locktype>SHARED_LOCK ){ 1556 if( pFile->eFileLock>SHARED_LOCK ){
1811 /* Either this connection or some other connection in the same process 1557 /* Either this connection or some other connection in the same process
1812 ** holds a lock on the file. No need to check further. */ 1558 ** holds a lock on the file. No need to check further. */
1813 reserved = 1; 1559 reserved = 1;
1814 }else{ 1560 }else{
1815 /* The lock is held if and only if the lockfile exists */ 1561 /* The lock is held if and only if the lockfile exists */
1816 const char *zLockFile = (const char*)pFile->lockingContext; 1562 const char *zLockFile = (const char*)pFile->lockingContext;
1817 reserved = access(zLockFile, 0)==0; 1563 reserved = access(zLockFile, 0)==0;
1818 } 1564 }
1819 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved); 1565 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
1820 *pResOut = reserved; 1566 *pResOut = reserved;
1821 return rc; 1567 return rc;
1822 } 1568 }
1823 1569
1824 /* 1570 /*
1825 ** Lock the file with the lock specified by parameter locktype - one 1571 ** Lock the file with the lock specified by parameter eFileLock - one
1826 ** of the following: 1572 ** of the following:
1827 ** 1573 **
1828 ** (1) SHARED_LOCK 1574 ** (1) SHARED_LOCK
1829 ** (2) RESERVED_LOCK 1575 ** (2) RESERVED_LOCK
1830 ** (3) PENDING_LOCK 1576 ** (3) PENDING_LOCK
1831 ** (4) EXCLUSIVE_LOCK 1577 ** (4) EXCLUSIVE_LOCK
1832 ** 1578 **
1833 ** Sometimes when requesting one lock state, additional lock states 1579 ** Sometimes when requesting one lock state, additional lock states
1834 ** are inserted in between. The locking might fail on one of the later 1580 ** are inserted in between. The locking might fail on one of the later
1835 ** transitions leaving the lock state different from what it started but 1581 ** transitions leaving the lock state different from what it started but
1836 ** still short of its goal. The following chart shows the allowed 1582 ** still short of its goal. The following chart shows the allowed
1837 ** transitions and the inserted intermediate states: 1583 ** transitions and the inserted intermediate states:
1838 ** 1584 **
1839 ** UNLOCKED -> SHARED 1585 ** UNLOCKED -> SHARED
1840 ** SHARED -> RESERVED 1586 ** SHARED -> RESERVED
1841 ** SHARED -> (PENDING) -> EXCLUSIVE 1587 ** SHARED -> (PENDING) -> EXCLUSIVE
1842 ** RESERVED -> (PENDING) -> EXCLUSIVE 1588 ** RESERVED -> (PENDING) -> EXCLUSIVE
1843 ** PENDING -> EXCLUSIVE 1589 ** PENDING -> EXCLUSIVE
1844 ** 1590 **
1845 ** This routine will only increase a lock. Use the sqlite3OsUnlock() 1591 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
1846 ** routine to lower a locking level. 1592 ** routine to lower a locking level.
1847 ** 1593 **
1848 ** With dotfile locking, we really only support state (4): EXCLUSIVE. 1594 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
1849 ** But we track the other locking levels internally. 1595 ** But we track the other locking levels internally.
1850 */ 1596 */
1851 static int dotlockLock(sqlite3_file *id, int locktype) { 1597 static int dotlockLock(sqlite3_file *id, int eFileLock) {
1852 unixFile *pFile = (unixFile*)id; 1598 unixFile *pFile = (unixFile*)id;
1853 int fd; 1599 int fd;
1854 char *zLockFile = (char *)pFile->lockingContext; 1600 char *zLockFile = (char *)pFile->lockingContext;
1855 int rc = SQLITE_OK; 1601 int rc = SQLITE_OK;
1856 1602
1857 1603
1858 /* If we have any lock, then the lock file already exists. All we have 1604 /* If we have any lock, then the lock file already exists. All we have
1859 ** to do is adjust our internal record of the lock level. 1605 ** to do is adjust our internal record of the lock level.
1860 */ 1606 */
1861 if( pFile->locktype > NO_LOCK ){ 1607 if( pFile->eFileLock > NO_LOCK ){
1862 pFile->locktype = locktype; 1608 pFile->eFileLock = eFileLock;
1863 #if !OS_VXWORKS 1609 #if !OS_VXWORKS
1864 /* Always update the timestamp on the old file */ 1610 /* Always update the timestamp on the old file */
1865 utimes(zLockFile, NULL); 1611 utimes(zLockFile, NULL);
1866 #endif 1612 #endif
1867 return SQLITE_OK; 1613 return SQLITE_OK;
1868 } 1614 }
1869 1615
1870 /* grab an exclusive lock */ 1616 /* grab an exclusive lock */
1871 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600); 1617 fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
1872 if( fd<0 ){ 1618 if( fd<0 ){
1873 /* failed to open/create the file, someone else may have stolen the lock */ 1619 /* failed to open/create the file, someone else may have stolen the lock */
1874 int tErrno = errno; 1620 int tErrno = errno;
1875 if( EEXIST == tErrno ){ 1621 if( EEXIST == tErrno ){
1876 rc = SQLITE_BUSY; 1622 rc = SQLITE_BUSY;
1877 } else { 1623 } else {
1878 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 1624 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
1879 if( IS_LOCK_ERROR(rc) ){ 1625 if( IS_LOCK_ERROR(rc) ){
1880 pFile->lastErrno = tErrno; 1626 pFile->lastErrno = tErrno;
1881 } 1627 }
1882 } 1628 }
1883 return rc; 1629 return rc;
1884 } 1630 }
1885 if( close(fd) ){ 1631 if( close(fd) ){
1886 pFile->lastErrno = errno; 1632 pFile->lastErrno = errno;
1887 rc = SQLITE_IOERR_CLOSE; 1633 rc = SQLITE_IOERR_CLOSE;
1888 } 1634 }
1889 1635
1890 /* got it, set the type and return ok */ 1636 /* got it, set the type and return ok */
1891 pFile->locktype = locktype; 1637 pFile->eFileLock = eFileLock;
1892 return rc; 1638 return rc;
1893 } 1639 }
1894 1640
1895 /* 1641 /*
1896 ** Lower the locking level on file descriptor pFile to locktype. locktype 1642 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
1897 ** must be either NO_LOCK or SHARED_LOCK. 1643 ** must be either NO_LOCK or SHARED_LOCK.
1898 ** 1644 **
1899 ** If the locking level of the file descriptor is already at or below 1645 ** If the locking level of the file descriptor is already at or below
1900 ** the requested locking level, this routine is a no-op. 1646 ** the requested locking level, this routine is a no-op.
1901 ** 1647 **
1902 ** When the locking level reaches NO_LOCK, delete the lock file. 1648 ** When the locking level reaches NO_LOCK, delete the lock file.
1903 */ 1649 */
1904 static int dotlockUnlock(sqlite3_file *id, int locktype) { 1650 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
1905 unixFile *pFile = (unixFile*)id; 1651 unixFile *pFile = (unixFile*)id;
1906 char *zLockFile = (char *)pFile->lockingContext; 1652 char *zLockFile = (char *)pFile->lockingContext;
1907 1653
1908 assert( pFile ); 1654 assert( pFile );
1909 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype, 1655 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
1910 » pFile->locktype, getpid()); 1656 » pFile->eFileLock, getpid()));
1911 assert( locktype<=SHARED_LOCK ); 1657 assert( eFileLock<=SHARED_LOCK );
1912 1658
1913 /* no-op if possible */ 1659 /* no-op if possible */
1914 if( pFile->locktype==locktype ){ 1660 if( pFile->eFileLock==eFileLock ){
1915 return SQLITE_OK; 1661 return SQLITE_OK;
1916 } 1662 }
1917 1663
1918 /* To downgrade to shared, simply update our internal notion of the 1664 /* To downgrade to shared, simply update our internal notion of the
1919 ** lock state. No need to mess with the file on disk. 1665 ** lock state. No need to mess with the file on disk.
1920 */ 1666 */
1921 if( locktype==SHARED_LOCK ){ 1667 if( eFileLock==SHARED_LOCK ){
1922 pFile->locktype = SHARED_LOCK; 1668 pFile->eFileLock = SHARED_LOCK;
1923 return SQLITE_OK; 1669 return SQLITE_OK;
1924 } 1670 }
1925 1671
1926 /* To fully unlock the database, delete the lock file */ 1672 /* To fully unlock the database, delete the lock file */
1927 assert( locktype==NO_LOCK ); 1673 assert( eFileLock==NO_LOCK );
1928 if( unlink(zLockFile) ){ 1674 if( unlink(zLockFile) ){
1929 int rc = 0; 1675 int rc = 0;
1930 int tErrno = errno; 1676 int tErrno = errno;
1931 if( ENOENT != tErrno ){ 1677 if( ENOENT != tErrno ){
1932 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 1678 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
1933 } 1679 }
1934 if( IS_LOCK_ERROR(rc) ){ 1680 if( IS_LOCK_ERROR(rc) ){
1935 pFile->lastErrno = tErrno; 1681 pFile->lastErrno = tErrno;
1936 } 1682 }
1937 return rc; 1683 return rc;
1938 } 1684 }
1939 pFile->locktype = NO_LOCK; 1685 pFile->eFileLock = NO_LOCK;
1940 return SQLITE_OK; 1686 return SQLITE_OK;
1941 } 1687 }
1942 1688
1943 /* 1689 /*
1944 ** Close a file. Make sure the lock has been released before closing. 1690 ** Close a file. Make sure the lock has been released before closing.
1945 */ 1691 */
1946 static int dotlockClose(sqlite3_file *id) { 1692 static int dotlockClose(sqlite3_file *id) {
1947 int rc; 1693 int rc;
1948 if( id ){ 1694 if( id ){
1949 unixFile *pFile = (unixFile*)id; 1695 unixFile *pFile = (unixFile*)id;
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after
1982 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){ 1728 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
1983 int rc = SQLITE_OK; 1729 int rc = SQLITE_OK;
1984 int reserved = 0; 1730 int reserved = 0;
1985 unixFile *pFile = (unixFile*)id; 1731 unixFile *pFile = (unixFile*)id;
1986 1732
1987 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); 1733 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
1988 1734
1989 assert( pFile ); 1735 assert( pFile );
1990 1736
1991 /* Check if a thread in this process holds such a lock */ 1737 /* Check if a thread in this process holds such a lock */
1992 if( pFile->locktype>SHARED_LOCK ){ 1738 if( pFile->eFileLock>SHARED_LOCK ){
1993 reserved = 1; 1739 reserved = 1;
1994 } 1740 }
1995 1741
1996 /* Otherwise see if some other process holds it. */ 1742 /* Otherwise see if some other process holds it. */
1997 if( !reserved ){ 1743 if( !reserved ){
1998 /* attempt to get the lock */ 1744 /* attempt to get the lock */
1999 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB); 1745 int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
2000 if( !lrc ){ 1746 if( !lrc ){
2001 /* got the lock, unlock it */ 1747 /* got the lock, unlock it */
2002 lrc = flock(pFile->h, LOCK_UN); 1748 lrc = flock(pFile->h, LOCK_UN);
(...skipping 10 matching lines...) Expand all
2013 int tErrno = errno; 1759 int tErrno = errno;
2014 reserved = 1; 1760 reserved = 1;
2015 /* someone else might have it reserved */ 1761 /* someone else might have it reserved */
2016 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 1762 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2017 if( IS_LOCK_ERROR(lrc) ){ 1763 if( IS_LOCK_ERROR(lrc) ){
2018 pFile->lastErrno = tErrno; 1764 pFile->lastErrno = tErrno;
2019 rc = lrc; 1765 rc = lrc;
2020 } 1766 }
2021 } 1767 }
2022 } 1768 }
2023 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved); 1769 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
2024 1770
2025 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS 1771 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2026 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){ 1772 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2027 rc = SQLITE_OK; 1773 rc = SQLITE_OK;
2028 reserved=1; 1774 reserved=1;
2029 } 1775 }
2030 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */ 1776 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2031 *pResOut = reserved; 1777 *pResOut = reserved;
2032 return rc; 1778 return rc;
2033 } 1779 }
2034 1780
2035 /* 1781 /*
2036 ** Lock the file with the lock specified by parameter locktype - one 1782 ** Lock the file with the lock specified by parameter eFileLock - one
2037 ** of the following: 1783 ** of the following:
2038 ** 1784 **
2039 ** (1) SHARED_LOCK 1785 ** (1) SHARED_LOCK
2040 ** (2) RESERVED_LOCK 1786 ** (2) RESERVED_LOCK
2041 ** (3) PENDING_LOCK 1787 ** (3) PENDING_LOCK
2042 ** (4) EXCLUSIVE_LOCK 1788 ** (4) EXCLUSIVE_LOCK
2043 ** 1789 **
2044 ** Sometimes when requesting one lock state, additional lock states 1790 ** Sometimes when requesting one lock state, additional lock states
2045 ** are inserted in between. The locking might fail on one of the later 1791 ** are inserted in between. The locking might fail on one of the later
2046 ** transitions leaving the lock state different from what it started but 1792 ** transitions leaving the lock state different from what it started but
2047 ** still short of its goal. The following chart shows the allowed 1793 ** still short of its goal. The following chart shows the allowed
2048 ** transitions and the inserted intermediate states: 1794 ** transitions and the inserted intermediate states:
2049 ** 1795 **
2050 ** UNLOCKED -> SHARED 1796 ** UNLOCKED -> SHARED
2051 ** SHARED -> RESERVED 1797 ** SHARED -> RESERVED
2052 ** SHARED -> (PENDING) -> EXCLUSIVE 1798 ** SHARED -> (PENDING) -> EXCLUSIVE
2053 ** RESERVED -> (PENDING) -> EXCLUSIVE 1799 ** RESERVED -> (PENDING) -> EXCLUSIVE
2054 ** PENDING -> EXCLUSIVE 1800 ** PENDING -> EXCLUSIVE
2055 ** 1801 **
2056 ** flock() only really support EXCLUSIVE locks. We track intermediate 1802 ** flock() only really support EXCLUSIVE locks. We track intermediate
2057 ** lock states in the sqlite3_file structure, but all locks SHARED or 1803 ** lock states in the sqlite3_file structure, but all locks SHARED or
2058 ** above are really EXCLUSIVE locks and exclude all other processes from 1804 ** above are really EXCLUSIVE locks and exclude all other processes from
2059 ** access the file. 1805 ** access the file.
2060 ** 1806 **
2061 ** This routine will only increase a lock. Use the sqlite3OsUnlock() 1807 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2062 ** routine to lower a locking level. 1808 ** routine to lower a locking level.
2063 */ 1809 */
2064 static int flockLock(sqlite3_file *id, int locktype) { 1810 static int flockLock(sqlite3_file *id, int eFileLock) {
2065 int rc = SQLITE_OK; 1811 int rc = SQLITE_OK;
2066 unixFile *pFile = (unixFile*)id; 1812 unixFile *pFile = (unixFile*)id;
2067 1813
2068 assert( pFile ); 1814 assert( pFile );
2069 1815
2070 /* if we already have a lock, it is exclusive. 1816 /* if we already have a lock, it is exclusive.
2071 ** Just adjust level and punt on outta here. */ 1817 ** Just adjust level and punt on outta here. */
2072 if (pFile->locktype > NO_LOCK) { 1818 if (pFile->eFileLock > NO_LOCK) {
2073 pFile->locktype = locktype; 1819 pFile->eFileLock = eFileLock;
2074 return SQLITE_OK; 1820 return SQLITE_OK;
2075 } 1821 }
2076 1822
2077 /* grab an exclusive lock */ 1823 /* grab an exclusive lock */
2078 1824
2079 if (flock(pFile->h, LOCK_EX | LOCK_NB)) { 1825 if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
2080 int tErrno = errno; 1826 int tErrno = errno;
2081 /* didn't get, must be busy */ 1827 /* didn't get, must be busy */
2082 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 1828 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
2083 if( IS_LOCK_ERROR(rc) ){ 1829 if( IS_LOCK_ERROR(rc) ){
2084 pFile->lastErrno = tErrno; 1830 pFile->lastErrno = tErrno;
2085 } 1831 }
2086 } else { 1832 } else {
2087 /* got it, set the type and return ok */ 1833 /* got it, set the type and return ok */
2088 pFile->locktype = locktype; 1834 pFile->eFileLock = eFileLock;
2089 } 1835 }
2090 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype), 1836 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
2091 rc==SQLITE_OK ? "ok" : "failed"); 1837 rc==SQLITE_OK ? "ok" : "failed"));
2092 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS 1838 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2093 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){ 1839 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
2094 rc = SQLITE_BUSY; 1840 rc = SQLITE_BUSY;
2095 } 1841 }
2096 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */ 1842 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2097 return rc; 1843 return rc;
2098 } 1844 }
2099 1845
2100 1846
2101 /* 1847 /*
2102 ** Lower the locking level on file descriptor pFile to locktype. locktype 1848 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2103 ** must be either NO_LOCK or SHARED_LOCK. 1849 ** must be either NO_LOCK or SHARED_LOCK.
2104 ** 1850 **
2105 ** If the locking level of the file descriptor is already at or below 1851 ** If the locking level of the file descriptor is already at or below
2106 ** the requested locking level, this routine is a no-op. 1852 ** the requested locking level, this routine is a no-op.
2107 */ 1853 */
2108 static int flockUnlock(sqlite3_file *id, int locktype) { 1854 static int flockUnlock(sqlite3_file *id, int eFileLock) {
2109 unixFile *pFile = (unixFile*)id; 1855 unixFile *pFile = (unixFile*)id;
2110 1856
2111 assert( pFile ); 1857 assert( pFile );
2112 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype, 1858 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
2113 pFile->locktype, getpid()); 1859 pFile->eFileLock, getpid()));
2114 assert( locktype<=SHARED_LOCK ); 1860 assert( eFileLock<=SHARED_LOCK );
2115 1861
2116 /* no-op if possible */ 1862 /* no-op if possible */
2117 if( pFile->locktype==locktype ){ 1863 if( pFile->eFileLock==eFileLock ){
2118 return SQLITE_OK; 1864 return SQLITE_OK;
2119 } 1865 }
2120 1866
2121 /* shared can just be set because we always have an exclusive */ 1867 /* shared can just be set because we always have an exclusive */
2122 if (locktype==SHARED_LOCK) { 1868 if (eFileLock==SHARED_LOCK) {
2123 pFile->locktype = locktype; 1869 pFile->eFileLock = eFileLock;
2124 return SQLITE_OK; 1870 return SQLITE_OK;
2125 } 1871 }
2126 1872
2127 /* no, really, unlock. */ 1873 /* no, really, unlock. */
2128 int rc = flock(pFile->h, LOCK_UN); 1874 int rc = flock(pFile->h, LOCK_UN);
2129 if (rc) { 1875 if (rc) {
2130 int r, tErrno = errno; 1876 int r, tErrno = errno;
2131 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 1877 r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2132 if( IS_LOCK_ERROR(r) ){ 1878 if( IS_LOCK_ERROR(r) ){
2133 pFile->lastErrno = tErrno; 1879 pFile->lastErrno = tErrno;
2134 } 1880 }
2135 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS 1881 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
2136 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){ 1882 if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
2137 r = SQLITE_BUSY; 1883 r = SQLITE_BUSY;
2138 } 1884 }
2139 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */ 1885 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
2140 1886
2141 return r; 1887 return r;
2142 } else { 1888 } else {
2143 pFile->locktype = NO_LOCK; 1889 pFile->eFileLock = NO_LOCK;
2144 return SQLITE_OK; 1890 return SQLITE_OK;
2145 } 1891 }
2146 } 1892 }
2147 1893
2148 /* 1894 /*
2149 ** Close a file. 1895 ** Close a file.
2150 */ 1896 */
2151 static int flockClose(sqlite3_file *id) { 1897 static int flockClose(sqlite3_file *id) {
2152 if( id ){ 1898 if( id ){
2153 flockUnlock(id, NO_LOCK); 1899 flockUnlock(id, NO_LOCK);
(...skipping 27 matching lines...) Expand all
2181 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) { 1927 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
2182 int rc = SQLITE_OK; 1928 int rc = SQLITE_OK;
2183 int reserved = 0; 1929 int reserved = 0;
2184 unixFile *pFile = (unixFile*)id; 1930 unixFile *pFile = (unixFile*)id;
2185 1931
2186 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); 1932 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2187 1933
2188 assert( pFile ); 1934 assert( pFile );
2189 1935
2190 /* Check if a thread in this process holds such a lock */ 1936 /* Check if a thread in this process holds such a lock */
2191 if( pFile->locktype>SHARED_LOCK ){ 1937 if( pFile->eFileLock>SHARED_LOCK ){
2192 reserved = 1; 1938 reserved = 1;
2193 } 1939 }
2194 1940
2195 /* Otherwise see if some other process holds it. */ 1941 /* Otherwise see if some other process holds it. */
2196 if( !reserved ){ 1942 if( !reserved ){
2197 sem_t *pSem = pFile->pOpen->pSem; 1943 sem_t *pSem = pFile->pInode->pSem;
2198 struct stat statBuf; 1944 struct stat statBuf;
2199 1945
2200 if( sem_trywait(pSem)==-1 ){ 1946 if( sem_trywait(pSem)==-1 ){
2201 int tErrno = errno; 1947 int tErrno = errno;
2202 if( EAGAIN != tErrno ){ 1948 if( EAGAIN != tErrno ){
2203 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK); 1949 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
2204 pFile->lastErrno = tErrno; 1950 pFile->lastErrno = tErrno;
2205 } else { 1951 } else {
2206 /* someone else has the lock when we are in NO_LOCK */ 1952 /* someone else has the lock when we are in NO_LOCK */
2207 reserved = (pFile->locktype < SHARED_LOCK); 1953 reserved = (pFile->eFileLock < SHARED_LOCK);
2208 } 1954 }
2209 }else{ 1955 }else{
2210 /* we could have it if we want it */ 1956 /* we could have it if we want it */
2211 sem_post(pSem); 1957 sem_post(pSem);
2212 } 1958 }
2213 } 1959 }
2214 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved); 1960 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
2215 1961
2216 *pResOut = reserved; 1962 *pResOut = reserved;
2217 return rc; 1963 return rc;
2218 } 1964 }
2219 1965
2220 /* 1966 /*
2221 ** Lock the file with the lock specified by parameter locktype - one 1967 ** Lock the file with the lock specified by parameter eFileLock - one
2222 ** of the following: 1968 ** of the following:
2223 ** 1969 **
2224 ** (1) SHARED_LOCK 1970 ** (1) SHARED_LOCK
2225 ** (2) RESERVED_LOCK 1971 ** (2) RESERVED_LOCK
2226 ** (3) PENDING_LOCK 1972 ** (3) PENDING_LOCK
2227 ** (4) EXCLUSIVE_LOCK 1973 ** (4) EXCLUSIVE_LOCK
2228 ** 1974 **
2229 ** Sometimes when requesting one lock state, additional lock states 1975 ** Sometimes when requesting one lock state, additional lock states
2230 ** are inserted in between. The locking might fail on one of the later 1976 ** are inserted in between. The locking might fail on one of the later
2231 ** transitions leaving the lock state different from what it started but 1977 ** transitions leaving the lock state different from what it started but
2232 ** still short of its goal. The following chart shows the allowed 1978 ** still short of its goal. The following chart shows the allowed
2233 ** transitions and the inserted intermediate states: 1979 ** transitions and the inserted intermediate states:
2234 ** 1980 **
2235 ** UNLOCKED -> SHARED 1981 ** UNLOCKED -> SHARED
2236 ** SHARED -> RESERVED 1982 ** SHARED -> RESERVED
2237 ** SHARED -> (PENDING) -> EXCLUSIVE 1983 ** SHARED -> (PENDING) -> EXCLUSIVE
2238 ** RESERVED -> (PENDING) -> EXCLUSIVE 1984 ** RESERVED -> (PENDING) -> EXCLUSIVE
2239 ** PENDING -> EXCLUSIVE 1985 ** PENDING -> EXCLUSIVE
2240 ** 1986 **
2241 ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate 1987 ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
2242 ** lock states in the sqlite3_file structure, but all locks SHARED or 1988 ** lock states in the sqlite3_file structure, but all locks SHARED or
2243 ** above are really EXCLUSIVE locks and exclude all other processes from 1989 ** above are really EXCLUSIVE locks and exclude all other processes from
2244 ** access the file. 1990 ** access the file.
2245 ** 1991 **
2246 ** This routine will only increase a lock. Use the sqlite3OsUnlock() 1992 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2247 ** routine to lower a locking level. 1993 ** routine to lower a locking level.
2248 */ 1994 */
2249 static int semLock(sqlite3_file *id, int locktype) { 1995 static int semLock(sqlite3_file *id, int eFileLock) {
2250 unixFile *pFile = (unixFile*)id; 1996 unixFile *pFile = (unixFile*)id;
2251 int fd; 1997 int fd;
2252 sem_t *pSem = pFile->pOpen->pSem; 1998 sem_t *pSem = pFile->pInode->pSem;
2253 int rc = SQLITE_OK; 1999 int rc = SQLITE_OK;
2254 2000
2255 /* if we already have a lock, it is exclusive. 2001 /* if we already have a lock, it is exclusive.
2256 ** Just adjust level and punt on outta here. */ 2002 ** Just adjust level and punt on outta here. */
2257 if (pFile->locktype > NO_LOCK) { 2003 if (pFile->eFileLock > NO_LOCK) {
2258 pFile->locktype = locktype; 2004 pFile->eFileLock = eFileLock;
2259 rc = SQLITE_OK; 2005 rc = SQLITE_OK;
2260 goto sem_end_lock; 2006 goto sem_end_lock;
2261 } 2007 }
2262 2008
2263 /* lock semaphore now but bail out when already locked. */ 2009 /* lock semaphore now but bail out when already locked. */
2264 if( sem_trywait(pSem)==-1 ){ 2010 if( sem_trywait(pSem)==-1 ){
2265 rc = SQLITE_BUSY; 2011 rc = SQLITE_BUSY;
2266 goto sem_end_lock; 2012 goto sem_end_lock;
2267 } 2013 }
2268 2014
2269 /* got it, set the type and return ok */ 2015 /* got it, set the type and return ok */
2270 pFile->locktype = locktype; 2016 pFile->eFileLock = eFileLock;
2271 2017
2272 sem_end_lock: 2018 sem_end_lock:
2273 return rc; 2019 return rc;
2274 } 2020 }
2275 2021
2276 /* 2022 /*
2277 ** Lower the locking level on file descriptor pFile to locktype. locktype 2023 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2278 ** must be either NO_LOCK or SHARED_LOCK. 2024 ** must be either NO_LOCK or SHARED_LOCK.
2279 ** 2025 **
2280 ** If the locking level of the file descriptor is already at or below 2026 ** If the locking level of the file descriptor is already at or below
2281 ** the requested locking level, this routine is a no-op. 2027 ** the requested locking level, this routine is a no-op.
2282 */ 2028 */
2283 static int semUnlock(sqlite3_file *id, int locktype) { 2029 static int semUnlock(sqlite3_file *id, int eFileLock) {
2284 unixFile *pFile = (unixFile*)id; 2030 unixFile *pFile = (unixFile*)id;
2285 sem_t *pSem = pFile->pOpen->pSem; 2031 sem_t *pSem = pFile->pInode->pSem;
2286 2032
2287 assert( pFile ); 2033 assert( pFile );
2288 assert( pSem ); 2034 assert( pSem );
2289 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype, 2035 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
2290 » pFile->locktype, getpid()); 2036 » pFile->eFileLock, getpid()));
2291 assert( locktype<=SHARED_LOCK ); 2037 assert( eFileLock<=SHARED_LOCK );
2292 2038
2293 /* no-op if possible */ 2039 /* no-op if possible */
2294 if( pFile->locktype==locktype ){ 2040 if( pFile->eFileLock==eFileLock ){
2295 return SQLITE_OK; 2041 return SQLITE_OK;
2296 } 2042 }
2297 2043
2298 /* shared can just be set because we always have an exclusive */ 2044 /* shared can just be set because we always have an exclusive */
2299 if (locktype==SHARED_LOCK) { 2045 if (eFileLock==SHARED_LOCK) {
2300 pFile->locktype = locktype; 2046 pFile->eFileLock = eFileLock;
2301 return SQLITE_OK; 2047 return SQLITE_OK;
2302 } 2048 }
2303 2049
2304 /* no, really unlock. */ 2050 /* no, really unlock. */
2305 if ( sem_post(pSem)==-1 ) { 2051 if ( sem_post(pSem)==-1 ) {
2306 int rc, tErrno = errno; 2052 int rc, tErrno = errno;
2307 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 2053 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
2308 if( IS_LOCK_ERROR(rc) ){ 2054 if( IS_LOCK_ERROR(rc) ){
2309 pFile->lastErrno = tErrno; 2055 pFile->lastErrno = tErrno;
2310 } 2056 }
2311 return rc; 2057 return rc;
2312 } 2058 }
2313 pFile->locktype = NO_LOCK; 2059 pFile->eFileLock = NO_LOCK;
2314 return SQLITE_OK; 2060 return SQLITE_OK;
2315 } 2061 }
2316 2062
2317 /* 2063 /*
2318 ** Close a file. 2064 ** Close a file.
2319 */ 2065 */
2320 static int semClose(sqlite3_file *id) { 2066 static int semClose(sqlite3_file *id) {
2321 if( id ){ 2067 if( id ){
2322 unixFile *pFile = (unixFile*)id; 2068 unixFile *pFile = (unixFile*)id;
2323 semUnlock(id, NO_LOCK); 2069 semUnlock(id, NO_LOCK);
2324 assert( pFile ); 2070 assert( pFile );
2325 unixEnterMutex(); 2071 unixEnterMutex();
2326 releaseLockInfo(pFile->pLock); 2072 releaseInodeInfo(pFile);
2327 releaseOpenCnt(pFile->pOpen);
2328 unixLeaveMutex(); 2073 unixLeaveMutex();
2329 closeUnixFile(id); 2074 closeUnixFile(id);
2330 } 2075 }
2331 return SQLITE_OK; 2076 return SQLITE_OK;
2332 } 2077 }
2333 2078
2334 #endif /* OS_VXWORKS */ 2079 #endif /* OS_VXWORKS */
2335 /* 2080 /*
2336 ** Named semaphore locking is only available on VxWorks. 2081 ** Named semaphore locking is only available on VxWorks.
2337 ** 2082 **
(...skipping 10 matching lines...) Expand all
2348 ** Third-party implementations of AFP are available. But this code here 2093 ** Third-party implementations of AFP are available. But this code here
2349 ** only works on OSX. 2094 ** only works on OSX.
2350 */ 2095 */
2351 2096
2352 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE 2097 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2353 /* 2098 /*
2354 ** The afpLockingContext structure contains all afp lock specific state 2099 ** The afpLockingContext structure contains all afp lock specific state
2355 */ 2100 */
2356 typedef struct afpLockingContext afpLockingContext; 2101 typedef struct afpLockingContext afpLockingContext;
2357 struct afpLockingContext { 2102 struct afpLockingContext {
2358 unsigned long long sharedByte; 2103 int reserved;
2359 const char *dbPath; /* Name of the open file */ 2104 const char *dbPath; /* Name of the open file */
2360 }; 2105 };
2361 2106
2362 struct ByteRangeLockPB2 2107 struct ByteRangeLockPB2
2363 { 2108 {
2364 unsigned long long offset; /* offset to first byte to lock */ 2109 unsigned long long offset; /* offset to first byte to lock */
2365 unsigned long long length; /* nbr of bytes to lock */ 2110 unsigned long long length; /* nbr of bytes to lock */
2366 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */ 2111 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
2367 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */ 2112 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
2368 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */ 2113 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
(...skipping 17 matching lines...) Expand all
2386 ){ 2131 ){
2387 struct ByteRangeLockPB2 pb; 2132 struct ByteRangeLockPB2 pb;
2388 int err; 2133 int err;
2389 2134
2390 pb.unLockFlag = setLockFlag ? 0 : 1; 2135 pb.unLockFlag = setLockFlag ? 0 : 1;
2391 pb.startEndFlag = 0; 2136 pb.startEndFlag = 0;
2392 pb.offset = offset; 2137 pb.offset = offset;
2393 pb.length = length; 2138 pb.length = length;
2394 pb.fd = pFile->h; 2139 pb.fd = pFile->h;
2395 2140
2396 OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 2141 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
2397 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""), 2142 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
2398 offset, length); 2143 offset, length));
2399 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0); 2144 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
2400 if ( err==-1 ) { 2145 if ( err==-1 ) {
2401 int rc; 2146 int rc;
2402 int tErrno = errno; 2147 int tErrno = errno;
2403 OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n", 2148 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
2404 path, tErrno, strerror(tErrno)); 2149 path, tErrno, strerror(tErrno)));
2405 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS 2150 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
2406 rc = SQLITE_BUSY; 2151 rc = SQLITE_BUSY;
2407 #else 2152 #else
2408 rc = sqliteErrorFromPosixError(tErrno, 2153 rc = sqliteErrorFromPosixError(tErrno,
2409 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK); 2154 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
2410 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */ 2155 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
2411 if( IS_LOCK_ERROR(rc) ){ 2156 if( IS_LOCK_ERROR(rc) ){
2412 pFile->lastErrno = tErrno; 2157 pFile->lastErrno = tErrno;
2413 } 2158 }
2414 return rc; 2159 return rc;
(...skipping 10 matching lines...) Expand all
2425 */ 2170 */
2426 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){ 2171 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
2427 int rc = SQLITE_OK; 2172 int rc = SQLITE_OK;
2428 int reserved = 0; 2173 int reserved = 0;
2429 unixFile *pFile = (unixFile*)id; 2174 unixFile *pFile = (unixFile*)id;
2430 2175
2431 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); 2176 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
2432 2177
2433 assert( pFile ); 2178 assert( pFile );
2434 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext; 2179 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2180 if( context->reserved ){
2181 *pResOut = 1;
2182 return SQLITE_OK;
2183 }
2184 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
2435 2185
2436 /* Check if a thread in this process holds such a lock */ 2186 /* Check if a thread in this process holds such a lock */
2437 if( pFile->locktype>SHARED_LOCK ){ 2187 if( pFile->pInode->eFileLock>SHARED_LOCK ){
2438 reserved = 1; 2188 reserved = 1;
2439 } 2189 }
2440 2190
2441 /* Otherwise see if some other process holds it. 2191 /* Otherwise see if some other process holds it.
2442 */ 2192 */
2443 if( !reserved ){ 2193 if( !reserved ){
2444 /* lock the RESERVED byte */ 2194 /* lock the RESERVED byte */
2445 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1); 2195 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
2446 if( SQLITE_OK==lrc ){ 2196 if( SQLITE_OK==lrc ){
2447 /* if we succeeded in taking the reserved lock, unlock it to restore 2197 /* if we succeeded in taking the reserved lock, unlock it to restore
2448 ** the original state */ 2198 ** the original state */
2449 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0); 2199 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2450 } else { 2200 } else {
2451 /* if we failed to get the lock then someone else must have it */ 2201 /* if we failed to get the lock then someone else must have it */
2452 reserved = 1; 2202 reserved = 1;
2453 } 2203 }
2454 if( IS_LOCK_ERROR(lrc) ){ 2204 if( IS_LOCK_ERROR(lrc) ){
2455 rc=lrc; 2205 rc=lrc;
2456 } 2206 }
2457 } 2207 }
2458 2208
2459 OSTRACE4("TEST WR-LOCK %d %d %d\n", pFile->h, rc, reserved); 2209 unixLeaveMutex();
2210 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
2460 2211
2461 *pResOut = reserved; 2212 *pResOut = reserved;
2462 return rc; 2213 return rc;
2463 } 2214 }
2464 2215
2465 /* 2216 /*
2466 ** Lock the file with the lock specified by parameter locktype - one 2217 ** Lock the file with the lock specified by parameter eFileLock - one
2467 ** of the following: 2218 ** of the following:
2468 ** 2219 **
2469 ** (1) SHARED_LOCK 2220 ** (1) SHARED_LOCK
2470 ** (2) RESERVED_LOCK 2221 ** (2) RESERVED_LOCK
2471 ** (3) PENDING_LOCK 2222 ** (3) PENDING_LOCK
2472 ** (4) EXCLUSIVE_LOCK 2223 ** (4) EXCLUSIVE_LOCK
2473 ** 2224 **
2474 ** Sometimes when requesting one lock state, additional lock states 2225 ** Sometimes when requesting one lock state, additional lock states
2475 ** are inserted in between. The locking might fail on one of the later 2226 ** are inserted in between. The locking might fail on one of the later
2476 ** transitions leaving the lock state different from what it started but 2227 ** transitions leaving the lock state different from what it started but
2477 ** still short of its goal. The following chart shows the allowed 2228 ** still short of its goal. The following chart shows the allowed
2478 ** transitions and the inserted intermediate states: 2229 ** transitions and the inserted intermediate states:
2479 ** 2230 **
2480 ** UNLOCKED -> SHARED 2231 ** UNLOCKED -> SHARED
2481 ** SHARED -> RESERVED 2232 ** SHARED -> RESERVED
2482 ** SHARED -> (PENDING) -> EXCLUSIVE 2233 ** SHARED -> (PENDING) -> EXCLUSIVE
2483 ** RESERVED -> (PENDING) -> EXCLUSIVE 2234 ** RESERVED -> (PENDING) -> EXCLUSIVE
2484 ** PENDING -> EXCLUSIVE 2235 ** PENDING -> EXCLUSIVE
2485 ** 2236 **
2486 ** This routine will only increase a lock. Use the sqlite3OsUnlock() 2237 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
2487 ** routine to lower a locking level. 2238 ** routine to lower a locking level.
2488 */ 2239 */
2489 static int afpLock(sqlite3_file *id, int locktype){ 2240 static int afpLock(sqlite3_file *id, int eFileLock){
2490 int rc = SQLITE_OK; 2241 int rc = SQLITE_OK;
2491 unixFile *pFile = (unixFile*)id; 2242 unixFile *pFile = (unixFile*)id;
2243 unixInodeInfo *pInode = pFile->pInode;
2492 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext; 2244 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2493 2245
2494 assert( pFile ); 2246 assert( pFile );
2495 OSTRACE5("LOCK %d %s was %s pid=%d\n", pFile->h, 2247 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
2496 locktypeName(locktype), locktypeName(pFile->locktype), getpid()); 2248 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
2249 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
2497 2250
2498 /* If there is already a lock of this type or more restrictive on the 2251 /* If there is already a lock of this type or more restrictive on the
2499 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as 2252 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
2500 ** unixEnterMutex() hasn't been called yet. 2253 ** unixEnterMutex() hasn't been called yet.
2501 */ 2254 */
2502 if( pFile->locktype>=locktype ){ 2255 if( pFile->eFileLock>=eFileLock ){
2503 OSTRACE3("LOCK %d %s ok (already held)\n", pFile->h, 2256 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
2504 locktypeName(locktype)); 2257 azFileLock(eFileLock)));
2505 return SQLITE_OK; 2258 return SQLITE_OK;
2506 } 2259 }
2507 2260
2508 /* Make sure the locking sequence is correct 2261 /* Make sure the locking sequence is correct
2262 ** (1) We never move from unlocked to anything higher than shared lock.
2263 ** (2) SQLite never explicitly requests a pendig lock.
2264 ** (3) A shared lock is always held when a reserve lock is requested.
2509 */ 2265 */
2510 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK ); 2266 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
2511 assert( locktype!=PENDING_LOCK ); 2267 assert( eFileLock!=PENDING_LOCK );
2512 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK ); 2268 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
2513 2269
2514 /* This mutex is needed because pFile->pLock is shared across threads 2270 /* This mutex is needed because pFile->pInode is shared across threads
2515 */ 2271 */
2516 unixEnterMutex(); 2272 unixEnterMutex();
2273 pInode = pFile->pInode;
2517 2274
2518 /* Make sure the current thread owns the pFile. 2275 /* If some thread using this PID has a lock via a different unixFile*
2276 ** handle that precludes the requested lock, return BUSY.
2519 */ 2277 */
2520 rc = transferOwnership(pFile); 2278 if( (pFile->eFileLock!=pInode->eFileLock &&
2521 if( rc!=SQLITE_OK ){ 2279 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
2522 unixLeaveMutex(); 2280 ){
2523 return rc; 2281 rc = SQLITE_BUSY;
2282 goto afp_end_lock;
2283 }
2284
2285 /* If a SHARED lock is requested, and some thread using this PID already
2286 ** has a SHARED or RESERVED lock, then increment reference counts and
2287 ** return SQLITE_OK.
2288 */
2289 if( eFileLock==SHARED_LOCK &&
2290 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
2291 assert( eFileLock==SHARED_LOCK );
2292 assert( pFile->eFileLock==0 );
2293 assert( pInode->nShared>0 );
2294 pFile->eFileLock = SHARED_LOCK;
2295 pInode->nShared++;
2296 pInode->nLock++;
2297 goto afp_end_lock;
2524 } 2298 }
2525 2299
2526 /* A PENDING lock is needed before acquiring a SHARED lock and before 2300 /* A PENDING lock is needed before acquiring a SHARED lock and before
2527 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will 2301 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
2528 ** be released. 2302 ** be released.
2529 */ 2303 */
2530 if( locktype==SHARED_LOCK 2304 if( eFileLock==SHARED_LOCK
2531 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK) 2305 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
2532 ){ 2306 ){
2533 int failed; 2307 int failed;
2534 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1); 2308 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
2535 if (failed) { 2309 if (failed) {
2536 rc = failed; 2310 rc = failed;
2537 goto afp_end_lock; 2311 goto afp_end_lock;
2538 } 2312 }
2539 } 2313 }
2540 2314
2541 /* If control gets to this point, then actually go ahead and make 2315 /* If control gets to this point, then actually go ahead and make
2542 ** operating system calls for the specified lock. 2316 ** operating system calls for the specified lock.
2543 */ 2317 */
2544 if( locktype==SHARED_LOCK ){ 2318 if( eFileLock==SHARED_LOCK ){
2545 int lk, lrc1, lrc2, lrc1Errno; 2319 int lrc1, lrc2, lrc1Errno;
2320 long lk, mask;
2546 2321
2322 assert( pInode->nShared==0 );
2323 assert( pInode->eFileLock==0 );
2324
2325 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
2547 /* Now get the read-lock SHARED_LOCK */ 2326 /* Now get the read-lock SHARED_LOCK */
2548 /* note that the quality of the randomness doesn't matter that much */ 2327 /* note that the quality of the randomness doesn't matter that much */
2549 lk = random(); 2328 lk = random();
2550 context->sharedByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1); 2329 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
2551 lrc1 = afpSetLock(context->dbPath, pFile, 2330 lrc1 = afpSetLock(context->dbPath, pFile,
2552 SHARED_FIRST+context->sharedByte, 1, 1); 2331 SHARED_FIRST+pInode->sharedByte, 1, 1);
2553 if( IS_LOCK_ERROR(lrc1) ){ 2332 if( IS_LOCK_ERROR(lrc1) ){
2554 lrc1Errno = pFile->lastErrno; 2333 lrc1Errno = pFile->lastErrno;
2555 } 2334 }
2556 /* Drop the temporary PENDING lock */ 2335 /* Drop the temporary PENDING lock */
2557 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0); 2336 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
2558 2337
2559 if( IS_LOCK_ERROR(lrc1) ) { 2338 if( IS_LOCK_ERROR(lrc1) ) {
2560 pFile->lastErrno = lrc1Errno; 2339 pFile->lastErrno = lrc1Errno;
2561 rc = lrc1; 2340 rc = lrc1;
2562 goto afp_end_lock; 2341 goto afp_end_lock;
2563 } else if( IS_LOCK_ERROR(lrc2) ){ 2342 } else if( IS_LOCK_ERROR(lrc2) ){
2564 rc = lrc2; 2343 rc = lrc2;
2565 goto afp_end_lock; 2344 goto afp_end_lock;
2566 } else if( lrc1 != SQLITE_OK ) { 2345 } else if( lrc1 != SQLITE_OK ) {
2567 rc = lrc1; 2346 rc = lrc1;
2568 } else { 2347 } else {
2569 pFile->locktype = SHARED_LOCK; 2348 pFile->eFileLock = SHARED_LOCK;
2570 pFile->pOpen->nLock++; 2349 pInode->nLock++;
2350 pInode->nShared = 1;
2571 } 2351 }
2352 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
2353 /* We are trying for an exclusive lock but another thread in this
2354 ** same process is still holding a shared lock. */
2355 rc = SQLITE_BUSY;
2572 }else{ 2356 }else{
2573 /* The request was for a RESERVED or EXCLUSIVE lock. It is 2357 /* The request was for a RESERVED or EXCLUSIVE lock. It is
2574 ** assumed that there is a SHARED or greater lock on the file 2358 ** assumed that there is a SHARED or greater lock on the file
2575 ** already. 2359 ** already.
2576 */ 2360 */
2577 int failed = 0; 2361 int failed = 0;
2578 assert( 0!=pFile->locktype ); 2362 assert( 0!=pFile->eFileLock );
2579 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) { 2363 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
2580 /* Acquire a RESERVED lock */ 2364 /* Acquire a RESERVED lock */
2581 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1); 2365 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
2366 if( !failed ){
2367 context->reserved = 1;
2368 }
2582 } 2369 }
2583 if (!failed && locktype == EXCLUSIVE_LOCK) { 2370 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
2584 /* Acquire an EXCLUSIVE lock */ 2371 /* Acquire an EXCLUSIVE lock */
2585 2372
2586 /* Remove the shared lock before trying the range. we'll need to 2373 /* Remove the shared lock before trying the range. we'll need to
2587 ** reestablish the shared lock if we can't get the afpUnlock 2374 ** reestablish the shared lock if we can't get the afpUnlock
2588 */ 2375 */
2589 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST + 2376 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
2590 context->sharedByte, 1, 0)) ){ 2377 pInode->sharedByte, 1, 0)) ){
2591 int failed2 = SQLITE_OK; 2378 int failed2 = SQLITE_OK;
2592 /* now attemmpt to get the exclusive lock range */ 2379 /* now attemmpt to get the exclusive lock range */
2593 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 2380 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
2594 SHARED_SIZE, 1); 2381 SHARED_SIZE, 1);
2595 if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 2382 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
2596 SHARED_FIRST + context->sharedByte, 1, 1)) ){ 2383 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
2597 /* Can't reestablish the shared lock. Sqlite can't deal, this is 2384 /* Can't reestablish the shared lock. Sqlite can't deal, this is
2598 ** a critical I/O error 2385 ** a critical I/O error
2599 */ 2386 */
2600 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : 2387 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
2601 SQLITE_IOERR_LOCK; 2388 SQLITE_IOERR_LOCK;
2602 goto afp_end_lock; 2389 goto afp_end_lock;
2603 } 2390 }
2604 }else{ 2391 }else{
2605 rc = failed; 2392 rc = failed;
2606 } 2393 }
2607 } 2394 }
2608 if( failed ){ 2395 if( failed ){
2609 rc = failed; 2396 rc = failed;
2610 } 2397 }
2611 } 2398 }
2612 2399
2613 if( rc==SQLITE_OK ){ 2400 if( rc==SQLITE_OK ){
2614 pFile->locktype = locktype; 2401 pFile->eFileLock = eFileLock;
2615 }else if( locktype==EXCLUSIVE_LOCK ){ 2402 pInode->eFileLock = eFileLock;
2616 pFile->locktype = PENDING_LOCK; 2403 }else if( eFileLock==EXCLUSIVE_LOCK ){
2404 pFile->eFileLock = PENDING_LOCK;
2405 pInode->eFileLock = PENDING_LOCK;
2617 } 2406 }
2618 2407
2619 afp_end_lock: 2408 afp_end_lock:
2620 unixLeaveMutex(); 2409 unixLeaveMutex();
2621 OSTRACE4("LOCK %d %s %s\n", pFile->h, locktypeName(locktype), 2410 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
2622 rc==SQLITE_OK ? "ok" : "failed"); 2411 rc==SQLITE_OK ? "ok" : "failed"));
2623 return rc; 2412 return rc;
2624 } 2413 }
2625 2414
2626 /* 2415 /*
2627 ** Lower the locking level on file descriptor pFile to locktype. locktype 2416 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2628 ** must be either NO_LOCK or SHARED_LOCK. 2417 ** must be either NO_LOCK or SHARED_LOCK.
2629 ** 2418 **
2630 ** If the locking level of the file descriptor is already at or below 2419 ** If the locking level of the file descriptor is already at or below
2631 ** the requested locking level, this routine is a no-op. 2420 ** the requested locking level, this routine is a no-op.
2632 */ 2421 */
2633 static int afpUnlock(sqlite3_file *id, int locktype) { 2422 static int afpUnlock(sqlite3_file *id, int eFileLock) {
2634 int rc = SQLITE_OK; 2423 int rc = SQLITE_OK;
2635 unixFile *pFile = (unixFile*)id; 2424 unixFile *pFile = (unixFile*)id;
2636 afpLockingContext *pCtx = (afpLockingContext *) pFile->lockingContext; 2425 unixInodeInfo *pInode;
2426 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
2427 int skipShared = 0;
2428 #ifdef SQLITE_TEST
2429 int h = pFile->h;
2430 #endif
2637 2431
2638 assert( pFile ); 2432 assert( pFile );
2639 OSTRACE5("UNLOCK %d %d was %d pid=%d\n", pFile->h, locktype, 2433 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
2640 pFile->locktype, getpid()); 2434 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
2435 getpid()));
2641 2436
2642 assert( locktype<=SHARED_LOCK ); 2437 assert( eFileLock<=SHARED_LOCK );
2643 if( pFile->locktype<=locktype ){ 2438 if( pFile->eFileLock<=eFileLock ){
2644 return SQLITE_OK; 2439 return SQLITE_OK;
2645 } 2440 }
2646 if( CHECK_THREADID(pFile) ){
2647 return SQLITE_MISUSE;
2648 }
2649 unixEnterMutex(); 2441 unixEnterMutex();
2650 if( pFile->locktype>SHARED_LOCK ){ 2442 pInode = pFile->pInode;
2443 assert( pInode->nShared!=0 );
2444 if( pFile->eFileLock>SHARED_LOCK ){
2445 assert( pInode->eFileLock==pFile->eFileLock );
2446 SimulateIOErrorBenign(1);
2447 SimulateIOError( h=(-1) )
2448 SimulateIOErrorBenign(0);
2651 2449
2652 if( pFile->locktype==EXCLUSIVE_LOCK ){ 2450 #ifndef NDEBUG
2653 rc = afpSetLock(pCtx->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0); 2451 /* When reducing a lock such that other processes can start
2654 if( rc==SQLITE_OK && locktype==SHARED_LOCK ){ 2452 ** reading the database file again, make sure that the
2453 ** transaction counter was updated if any part of the database
2454 ** file changed. If the transaction counter is not updated,
2455 ** other connections to the same file might not realize that
2456 ** the file has changed and hence might not know to flush their
2457 ** cache. The use of a stale cache can lead to database corruption.
2458 */
2459 assert( pFile->inNormalWrite==0
2460 || pFile->dbUpdate==0
2461 || pFile->transCntrChng==1 );
2462 pFile->inNormalWrite = 0;
2463 #endif
2464
2465 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
2466 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
2467 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
2655 /* only re-establish the shared lock if necessary */ 2468 /* only re-establish the shared lock if necessary */
2656 int sharedLockByte = SHARED_FIRST+pCtx->sharedByte; 2469 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2657 rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 1); 2470 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
2471 } else {
2472 skipShared = 1;
2658 } 2473 }
2659 } 2474 }
2660 if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){ 2475 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
2661 rc = afpSetLock(pCtx->dbPath, pFile, PENDING_BYTE, 1, 0); 2476 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
2662 } 2477 }
2663 if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK ){ 2478 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
2664 rc = afpSetLock(pCtx->dbPath, pFile, RESERVED_BYTE, 1, 0); 2479 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
2480 if( !rc ){
2481 context->reserved = 0;
2482 }
2665 } 2483 }
2666 }else if( locktype==NO_LOCK ){ 2484 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
2667 /* clear the shared lock */ 2485 pInode->eFileLock = SHARED_LOCK;
2668 int sharedLockByte = SHARED_FIRST+pCtx->sharedByte; 2486 }
2669 rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 0);
2670 } 2487 }
2488 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
2671 2489
2672 if( rc==SQLITE_OK ){ 2490 /* Decrement the shared lock counter. Release the lock using an
2673 if( locktype==NO_LOCK ){ 2491 ** OS call only when all threads in this same process have released
2674 struct unixOpenCnt *pOpen = pFile->pOpen; 2492 ** the lock.
2675 pOpen->nLock--; 2493 */
2676 assert( pOpen->nLock>=0 ); 2494 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
2677 if( pOpen->nLock==0 ){ 2495 pInode->nShared--;
2496 if( pInode->nShared==0 ){
2497 SimulateIOErrorBenign(1);
2498 SimulateIOError( h=(-1) )
2499 SimulateIOErrorBenign(0);
2500 if( !skipShared ){
2501 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
2502 }
2503 if( !rc ){
2504 pInode->eFileLock = NO_LOCK;
2505 pFile->eFileLock = NO_LOCK;
2506 }
2507 }
2508 if( rc==SQLITE_OK ){
2509 pInode->nLock--;
2510 assert( pInode->nLock>=0 );
2511 if( pInode->nLock==0 ){
2678 rc = closePendingFds(pFile); 2512 rc = closePendingFds(pFile);
2679 } 2513 }
2680 } 2514 }
2681 } 2515 }
2516
2682 unixLeaveMutex(); 2517 unixLeaveMutex();
2683 if( rc==SQLITE_OK ){ 2518 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
2684 pFile->locktype = locktype;
2685 }
2686 return rc; 2519 return rc;
2687 } 2520 }
2688 2521
2689 /* 2522 /*
2690 ** Close a file & cleanup AFP specific locking context 2523 ** Close a file & cleanup AFP specific locking context
2691 */ 2524 */
2692 static int afpClose(sqlite3_file *id) { 2525 static int afpClose(sqlite3_file *id) {
2526 int rc = SQLITE_OK;
2693 if( id ){ 2527 if( id ){
2694 unixFile *pFile = (unixFile*)id; 2528 unixFile *pFile = (unixFile*)id;
2695 afpUnlock(id, NO_LOCK); 2529 afpUnlock(id, NO_LOCK);
2696 unixEnterMutex(); 2530 unixEnterMutex();
2697 if( pFile->pOpen && pFile->pOpen->nLock ){ 2531 if( pFile->pInode && pFile->pInode->nLock ){
2698 /* If there are outstanding locks, do not actually close the file just 2532 /* If there are outstanding locks, do not actually close the file just
2699 ** yet because that would clear those locks. Instead, add the file 2533 ** yet because that would clear those locks. Instead, add the file
2700 ** descriptor to pOpen->aPending. It will be automatically closed when 2534 ** descriptor to pInode->aPending. It will be automatically closed when
2701 ** the last lock is cleared. 2535 ** the last lock is cleared.
2702 */ 2536 */
2703 setPendingFd(pFile); 2537 setPendingFd(pFile);
2704 } 2538 }
2705 releaseOpenCnt(pFile->pOpen); 2539 releaseInodeInfo(pFile);
2706 sqlite3_free(pFile->lockingContext); 2540 sqlite3_free(pFile->lockingContext);
2707 closeUnixFile(id); 2541 rc = closeUnixFile(id);
2708 unixLeaveMutex(); 2542 unixLeaveMutex();
2709 } 2543 }
2710 return SQLITE_OK; 2544 return rc;
2711 } 2545 }
2712 2546
2713 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ 2547 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2714 /* 2548 /*
2715 ** The code above is the AFP lock implementation. The code is specific 2549 ** The code above is the AFP lock implementation. The code is specific
2716 ** to MacOSX and does not work on other unix platforms. No alternative 2550 ** to MacOSX and does not work on other unix platforms. No alternative
2717 ** is available. If you don't compile for a mac, then the "unix-afp" 2551 ** is available. If you don't compile for a mac, then the "unix-afp"
2718 ** VFS is not available. 2552 ** VFS is not available.
2719 ** 2553 **
2720 ********************* End of the AFP lock implementation ********************** 2554 ********************* End of the AFP lock implementation **********************
2721 ******************************************************************************/ 2555 ******************************************************************************/
2722 2556
2557 /******************************************************************************
2558 *************************** Begin NFS Locking ********************************/
2559
2560 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
2561 /*
2562 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
2563 ** must be either NO_LOCK or SHARED_LOCK.
2564 **
2565 ** If the locking level of the file descriptor is already at or below
2566 ** the requested locking level, this routine is a no-op.
2567 */
2568 static int nfsUnlock(sqlite3_file *id, int eFileLock){
2569 return _posixUnlock(id, eFileLock, 1);
2570 }
2571
2572 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
2573 /*
2574 ** The code above is the NFS lock implementation. The code is specific
2575 ** to MacOSX and does not work on other unix platforms. No alternative
2576 ** is available.
2577 **
2578 ********************* End of the NFS lock implementation **********************
2579 ******************************************************************************/
2723 2580
2724 /****************************************************************************** 2581 /******************************************************************************
2725 **************** Non-locking sqlite3_file methods ***************************** 2582 **************** Non-locking sqlite3_file methods *****************************
2726 ** 2583 **
2727 ** The next division contains implementations for all methods of the 2584 ** The next division contains implementations for all methods of the
2728 ** sqlite3_file object other than the locking methods. The locking 2585 ** sqlite3_file object other than the locking methods. The locking
2729 ** methods were defined in divisions above (one locking method per 2586 ** methods were defined in divisions above (one locking method per
2730 ** division). Those methods that are common to all locking modes 2587 ** division). Those methods that are common to all locking modes
2731 ** are gather together into this division. 2588 ** are gather together into this division.
2732 */ 2589 */
2733 2590
2734 /* 2591 /*
2735 ** Seek to the offset passed as the second argument, then read cnt 2592 ** Seek to the offset passed as the second argument, then read cnt
2736 ** bytes into pBuf. Return the number of bytes actually read. 2593 ** bytes into pBuf. Return the number of bytes actually read.
2737 ** 2594 **
2738 ** NB: If you define USE_PREAD or USE_PREAD64, then it might also 2595 ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
2739 ** be necessary to define _XOPEN_SOURCE to be 500. This varies from 2596 ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
2740 ** one system to another. Since SQLite does not define USE_PREAD 2597 ** one system to another. Since SQLite does not define USE_PREAD
2741 ** any any form by default, we will not attempt to define _XOPEN_SOURCE. 2598 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
2742 ** See tickets #2741 and #2681. 2599 ** See tickets #2741 and #2681.
2743 ** 2600 **
2744 ** To avoid stomping the errno value on a failed read the lastErrno value 2601 ** To avoid stomping the errno value on a failed read the lastErrno value
2745 ** is set before returning. 2602 ** is set before returning.
2746 */ 2603 */
2747 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){ 2604 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
2748 int got; 2605 int got;
2606 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
2749 i64 newOffset; 2607 i64 newOffset;
2608 #endif
2750 TIMER_START; 2609 TIMER_START;
2751 #if defined(USE_PREAD) 2610 #if defined(USE_PREAD)
2752 got = pread(id->h, pBuf, cnt, offset); 2611 got = pread(id->h, pBuf, cnt, offset);
2753 SimulateIOError( got = -1 ); 2612 SimulateIOError( got = -1 );
2754 #elif defined(USE_PREAD64) 2613 #elif defined(USE_PREAD64)
2755 got = pread64(id->h, pBuf, cnt, offset); 2614 got = pread64(id->h, pBuf, cnt, offset);
2756 SimulateIOError( got = -1 ); 2615 SimulateIOError( got = -1 );
2757 #else 2616 #else
2758 newOffset = lseek(id->h, offset, SEEK_SET); 2617 newOffset = lseek(id->h, offset, SEEK_SET);
2759 SimulateIOError( newOffset-- ); 2618 SimulateIOError( newOffset-- );
2760 if( newOffset!=offset ){ 2619 if( newOffset!=offset ){
2761 if( newOffset == -1 ){ 2620 if( newOffset == -1 ){
2762 ((unixFile*)id)->lastErrno = errno; 2621 ((unixFile*)id)->lastErrno = errno;
2763 }else{ 2622 }else{
2764 ((unixFile*)id)->lastErrno = 0; 2623 ((unixFile*)id)->lastErrno = 0;
2765 } 2624 }
2766 return -1; 2625 return -1;
2767 } 2626 }
2768 got = read(id->h, pBuf, cnt); 2627 got = read(id->h, pBuf, cnt);
2769 #endif 2628 #endif
2770 TIMER_END; 2629 TIMER_END;
2771 if( got<0 ){ 2630 if( got<0 ){
2772 ((unixFile*)id)->lastErrno = errno; 2631 ((unixFile*)id)->lastErrno = errno;
2773 } 2632 }
2774 OSTRACE5("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED); 2633 OSTRACE(("READ %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
2775 return got; 2634 return got;
2776 } 2635 }
2777 2636
2778 /* 2637 /*
2779 ** Read data from a file into a buffer. Return SQLITE_OK if all 2638 ** Read data from a file into a buffer. Return SQLITE_OK if all
2780 ** bytes were read successfully and SQLITE_IOERR if anything goes 2639 ** bytes were read successfully and SQLITE_IOERR if anything goes
2781 ** wrong. 2640 ** wrong.
2782 */ 2641 */
2783 static int unixRead( 2642 static int unixRead(
2784 sqlite3_file *id, 2643 sqlite3_file *id,
2785 void *pBuf, 2644 void *pBuf,
2786 int amt, 2645 int amt,
2787 sqlite3_int64 offset 2646 sqlite3_int64 offset
2788 ){ 2647 ){
2789 unixFile *pFile = (unixFile *)id; 2648 unixFile *pFile = (unixFile *)id;
2790 int got; 2649 int got;
2791 assert( id ); 2650 assert( id );
2792 2651
2793 /* If this is a database file (not a journal, master-journal or temp 2652 /* If this is a database file (not a journal, master-journal or temp
2794 ** file), the bytes in the locking range should never be read or written. */ 2653 ** file), the bytes in the locking range should never be read or written. */
2654 #if 0
2795 assert( pFile->pUnused==0 2655 assert( pFile->pUnused==0
2796 || offset>=PENDING_BYTE+512 2656 || offset>=PENDING_BYTE+512
2797 || offset+amt<=PENDING_BYTE 2657 || offset+amt<=PENDING_BYTE
2798 ); 2658 );
2659 #endif
2799 2660
2800 got = seekAndRead(pFile, offset, pBuf, amt); 2661 got = seekAndRead(pFile, offset, pBuf, amt);
2801 if( got==amt ){ 2662 if( got==amt ){
2802 return SQLITE_OK; 2663 return SQLITE_OK;
2803 }else if( got<0 ){ 2664 }else if( got<0 ){
2804 /* lastErrno set by seekAndRead */ 2665 /* lastErrno set by seekAndRead */
2805 return SQLITE_IOERR_READ; 2666 return SQLITE_IOERR_READ;
2806 }else{ 2667 }else{
2807 pFile->lastErrno = 0; /* not a system error */ 2668 pFile->lastErrno = 0; /* not a system error */
2808 /* Unread parts of the buffer must be zero-filled */ 2669 /* Unread parts of the buffer must be zero-filled */
2809 memset(&((char*)pBuf)[got], 0, amt-got); 2670 memset(&((char*)pBuf)[got], 0, amt-got);
2810 return SQLITE_IOERR_SHORT_READ; 2671 return SQLITE_IOERR_SHORT_READ;
2811 } 2672 }
2812 } 2673 }
2813 2674
2814 /* 2675 /*
2815 ** Seek to the offset in id->offset then read cnt bytes into pBuf. 2676 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
2816 ** Return the number of bytes actually read. Update the offset. 2677 ** Return the number of bytes actually read. Update the offset.
2817 ** 2678 **
2818 ** To avoid stomping the errno value on a failed write the lastErrno value 2679 ** To avoid stomping the errno value on a failed write the lastErrno value
2819 ** is set before returning. 2680 ** is set before returning.
2820 */ 2681 */
2821 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){ 2682 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
2822 int got; 2683 int got;
2684 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
2823 i64 newOffset; 2685 i64 newOffset;
2686 #endif
2824 TIMER_START; 2687 TIMER_START;
2825 #if defined(USE_PREAD) 2688 #if defined(USE_PREAD)
2826 got = pwrite(id->h, pBuf, cnt, offset); 2689 got = pwrite(id->h, pBuf, cnt, offset);
2827 #elif defined(USE_PREAD64) 2690 #elif defined(USE_PREAD64)
2828 got = pwrite64(id->h, pBuf, cnt, offset); 2691 got = pwrite64(id->h, pBuf, cnt, offset);
2829 #else 2692 #else
2830 newOffset = lseek(id->h, offset, SEEK_SET); 2693 newOffset = lseek(id->h, offset, SEEK_SET);
2831 if( newOffset!=offset ){ 2694 if( newOffset!=offset ){
2832 int capturedErrno = errno; /* Capture errno before fprintf(). */
2833 /* TODO(shess): Tracking a SQLITE_IOERR_WRITE being seen on the
2834 * waterfall. http://crbug.com/56427 */
2835 fprintf(stderr, "SQLite lseek error in seekAndWrite, "
2836 "offset == %d, rc == %d, errno == %d\n",
2837 (int)offset, (int)newOffset, capturedErrno);
2838 fflush(stderr);
2839 if( newOffset == -1 ){ 2695 if( newOffset == -1 ){
2840 ((unixFile*)id)->lastErrno = capturedErrno; 2696 ((unixFile*)id)->lastErrno = errno;
2841 }else{ 2697 }else{
2842 ((unixFile*)id)->lastErrno = 0; 2698 ((unixFile*)id)->lastErrno = 0;
2843 } 2699 }
2844 return -1; 2700 return -1;
2845 } 2701 }
2846 got = write(id->h, pBuf, cnt); 2702 got = write(id->h, pBuf, cnt);
2847 #endif 2703 #endif
2848 TIMER_END; 2704 TIMER_END;
2849 if( got<0 ){ 2705 if( got<0 ){
2850 int capturedErrno = errno; /* Capture errno before fprintf(). */ 2706 ((unixFile*)id)->lastErrno = errno;
2851 /* TODO(shess): Tracking a SQLITE_IOERR_WRITE being seen on the
2852 * waterfall. http://crbug.com/56427 */
2853 fprintf(stderr, "SQLite write error in seekAndWrite, "
2854 "cnt == %d, rc == %d, errno == %d\n",
2855 cnt, got, capturedErrno);
2856 fflush(stderr);
2857 ((unixFile*)id)->lastErrno = capturedErrno;
2858 } 2707 }
2859 2708
2860 OSTRACE5("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED); 2709 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
2861 return got; 2710 return got;
2862 } 2711 }
2863 2712
2864 2713
2865 /* 2714 /*
2866 ** Write data from a buffer into a file. Return SQLITE_OK on success 2715 ** Write data from a buffer into a file. Return SQLITE_OK on success
2867 ** or some other error code on failure. 2716 ** or some other error code on failure.
2868 */ 2717 */
2869 static int unixWrite( 2718 static int unixWrite(
2870 sqlite3_file *id, 2719 sqlite3_file *id,
2871 const void *pBuf, 2720 const void *pBuf,
2872 int amt, 2721 int amt,
2873 sqlite3_int64 offset 2722 sqlite3_int64 offset
2874 ){ 2723 ){
2875 unixFile *pFile = (unixFile*)id; 2724 unixFile *pFile = (unixFile*)id;
2876 int wrote = 0; 2725 int wrote = 0;
2877 assert( id ); 2726 assert( id );
2878 assert( amt>0 ); 2727 assert( amt>0 );
2879 2728
2880 /* If this is a database file (not a journal, master-journal or temp 2729 /* If this is a database file (not a journal, master-journal or temp
2881 ** file), the bytes in the locking range should never be read or written. */ 2730 ** file), the bytes in the locking range should never be read or written. */
2731 #if 0
2882 assert( pFile->pUnused==0 2732 assert( pFile->pUnused==0
2883 || offset>=PENDING_BYTE+512 2733 || offset>=PENDING_BYTE+512
2884 || offset+amt<=PENDING_BYTE 2734 || offset+amt<=PENDING_BYTE
2885 ); 2735 );
2736 #endif
2886 2737
2887 #ifndef NDEBUG 2738 #ifndef NDEBUG
2888 /* If we are doing a normal write to a database file (as opposed to 2739 /* If we are doing a normal write to a database file (as opposed to
2889 ** doing a hot-journal rollback or a write to some file other than a 2740 ** doing a hot-journal rollback or a write to some file other than a
2890 ** normal database file) then record the fact that the database 2741 ** normal database file) then record the fact that the database
2891 ** has changed. If the transaction counter is modified, record that 2742 ** has changed. If the transaction counter is modified, record that
2892 ** fact too. 2743 ** fact too.
2893 */ 2744 */
2894 if( pFile->inNormalWrite ){ 2745 if( pFile->inNormalWrite ){
2895 pFile->dbUpdate = 1; /* The database has been modified */ 2746 pFile->dbUpdate = 1; /* The database has been modified */
(...skipping 10 matching lines...) Expand all
2906 } 2757 }
2907 #endif 2758 #endif
2908 2759
2909 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){ 2760 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
2910 amt -= wrote; 2761 amt -= wrote;
2911 offset += wrote; 2762 offset += wrote;
2912 pBuf = &((char*)pBuf)[wrote]; 2763 pBuf = &((char*)pBuf)[wrote];
2913 } 2764 }
2914 SimulateIOError(( wrote=(-1), amt=1 )); 2765 SimulateIOError(( wrote=(-1), amt=1 ));
2915 SimulateDiskfullError(( wrote=0, amt=1 )); 2766 SimulateDiskfullError(( wrote=0, amt=1 ));
2767
2916 if( amt>0 ){ 2768 if( amt>0 ){
2917 if( wrote<0 ){ 2769 if( wrote<0 ){
2918 /* lastErrno set by seekAndWrite */ 2770 /* lastErrno set by seekAndWrite */
2919 return SQLITE_IOERR_WRITE; 2771 return SQLITE_IOERR_WRITE;
2920 }else{ 2772 }else{
2921 pFile->lastErrno = 0; /* not a system error */ 2773 pFile->lastErrno = 0; /* not a system error */
2922 return SQLITE_FULL; 2774 return SQLITE_FULL;
2923 } 2775 }
2924 } 2776 }
2777
2925 return SQLITE_OK; 2778 return SQLITE_OK;
2926 } 2779 }
2927 2780
2928 #ifdef SQLITE_TEST 2781 #ifdef SQLITE_TEST
2929 /* 2782 /*
2930 ** Count the number of fullsyncs and normal syncs. This is used to test 2783 ** Count the number of fullsyncs and normal syncs. This is used to test
2931 ** that syncs and fullsyncs are occurring at the right times. 2784 ** that syncs and fullsyncs are occurring at the right times.
2932 */ 2785 */
2933 int sqlite3_sync_count = 0; 2786 int sqlite3_sync_count = 0;
2934 int sqlite3_fullsync_count = 0; 2787 int sqlite3_fullsync_count = 0;
(...skipping 86 matching lines...) Expand 10 before | Expand all | Expand 10 after
3021 /* If the FULLFSYNC failed, fall back to attempting an fsync(). 2874 /* If the FULLFSYNC failed, fall back to attempting an fsync().
3022 ** It shouldn't be possible for fullfsync to fail on the local 2875 ** It shouldn't be possible for fullfsync to fail on the local
3023 ** file system (on OSX), so failure indicates that FULLFSYNC 2876 ** file system (on OSX), so failure indicates that FULLFSYNC
3024 ** isn't supported for this file system. So, attempt an fsync 2877 ** isn't supported for this file system. So, attempt an fsync
3025 ** and (for now) ignore the overhead of a superfluous fcntl call. 2878 ** and (for now) ignore the overhead of a superfluous fcntl call.
3026 ** It'd be better to detect fullfsync support once and avoid 2879 ** It'd be better to detect fullfsync support once and avoid
3027 ** the fcntl call every time sync is called. 2880 ** the fcntl call every time sync is called.
3028 */ 2881 */
3029 if( rc ) rc = fsync(fd); 2882 if( rc ) rc = fsync(fd);
3030 2883
2884 #elif defined(__APPLE__)
2885 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
2886 ** so currently we default to the macro that redefines fdatasync to fsync
2887 */
2888 rc = fsync(fd);
3031 #else 2889 #else
3032 rc = fdatasync(fd); 2890 rc = fdatasync(fd);
3033 #if OS_VXWORKS 2891 #if OS_VXWORKS
3034 if( rc==-1 && errno==ENOTSUP ){ 2892 if( rc==-1 && errno==ENOTSUP ){
3035 rc = fsync(fd); 2893 rc = fsync(fd);
3036 } 2894 }
3037 #endif /* OS_VXWORKS */ 2895 #endif /* OS_VXWORKS */
3038 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */ 2896 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
3039 2897
3040 if( OS_VXWORKS && rc!= -1 ){ 2898 if( OS_VXWORKS && rc!= -1 ){
(...skipping 28 matching lines...) Expand all
3069 assert((flags&0x0F)==SQLITE_SYNC_NORMAL 2927 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
3070 || (flags&0x0F)==SQLITE_SYNC_FULL 2928 || (flags&0x0F)==SQLITE_SYNC_FULL
3071 ); 2929 );
3072 2930
3073 /* Unix cannot, but some systems may return SQLITE_FULL from here. This 2931 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
3074 ** line is to test that doing so does not cause any problems. 2932 ** line is to test that doing so does not cause any problems.
3075 */ 2933 */
3076 SimulateDiskfullError( return SQLITE_FULL ); 2934 SimulateDiskfullError( return SQLITE_FULL );
3077 2935
3078 assert( pFile ); 2936 assert( pFile );
3079 OSTRACE2("SYNC %-3d\n", pFile->h); 2937 OSTRACE(("SYNC %-3d\n", pFile->h));
3080 rc = full_fsync(pFile->h, isFullsync, isDataOnly); 2938 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
3081 SimulateIOError( rc=1 ); 2939 SimulateIOError( rc=1 );
3082 if( rc ){ 2940 if( rc ){
3083 pFile->lastErrno = errno; 2941 pFile->lastErrno = errno;
3084 return SQLITE_IOERR_FSYNC; 2942 return SQLITE_IOERR_FSYNC;
3085 } 2943 }
3086 if( pFile->dirfd>=0 ){ 2944 if( pFile->dirfd>=0 ){
3087 int err; 2945 int err;
3088 OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd, 2946 OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
3089 HAVE_FULLFSYNC, isFullsync); 2947 HAVE_FULLFSYNC, isFullsync));
3090 #ifndef SQLITE_DISABLE_DIRSYNC 2948 #ifndef SQLITE_DISABLE_DIRSYNC
3091 /* The directory sync is only attempted if full_fsync is 2949 /* The directory sync is only attempted if full_fsync is
3092 ** turned off or unavailable. If a full_fsync occurred above, 2950 ** turned off or unavailable. If a full_fsync occurred above,
3093 ** then the directory sync is superfluous. 2951 ** then the directory sync is superfluous.
3094 */ 2952 */
3095 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){ 2953 if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
3096 /* 2954 /*
3097 ** We have received multiple reports of fsync() returning 2955 ** We have received multiple reports of fsync() returning
3098 ** errors when applied to directories on certain file systems. 2956 ** errors when applied to directories on certain file systems.
3099 ** A failed directory sync is not a big deal. So it seems 2957 ** A failed directory sync is not a big deal. So it seems
(...skipping 11 matching lines...) Expand all
3111 rc = SQLITE_IOERR_DIR_CLOSE; 2969 rc = SQLITE_IOERR_DIR_CLOSE;
3112 } 2970 }
3113 } 2971 }
3114 return rc; 2972 return rc;
3115 } 2973 }
3116 2974
3117 /* 2975 /*
3118 ** Truncate an open file to a specified size 2976 ** Truncate an open file to a specified size
3119 */ 2977 */
3120 static int unixTruncate(sqlite3_file *id, i64 nByte){ 2978 static int unixTruncate(sqlite3_file *id, i64 nByte){
2979 unixFile *pFile = (unixFile *)id;
3121 int rc; 2980 int rc;
3122 assert( id ); 2981 assert( pFile );
3123 SimulateIOError( return SQLITE_IOERR_TRUNCATE ); 2982 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
3124 rc = ftruncate(((unixFile*)id)->h, (off_t)nByte); 2983
2984 /* If the user has configured a chunk-size for this file, truncate the
2985 ** file so that it consists of an integer number of chunks (i.e. the
2986 ** actual file size after the operation may be larger than the requested
2987 ** size).
2988 */
2989 if( pFile->szChunk ){
2990 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
2991 }
2992
2993 rc = ftruncate(pFile->h, (off_t)nByte);
3125 if( rc ){ 2994 if( rc ){
3126 ((unixFile*)id)->lastErrno = errno; 2995 pFile->lastErrno = errno;
3127 return SQLITE_IOERR_TRUNCATE; 2996 return SQLITE_IOERR_TRUNCATE;
3128 }else{ 2997 }else{
2998 #ifndef NDEBUG
2999 /* If we are doing a normal write to a database file (as opposed to
3000 ** doing a hot-journal rollback or a write to some file other than a
3001 ** normal database file) and we truncate the file to zero length,
3002 ** that effectively updates the change counter. This might happen
3003 ** when restoring a database using the backup API from a zero-length
3004 ** source.
3005 */
3006 if( pFile->inNormalWrite && nByte==0 ){
3007 pFile->transCntrChng = 1;
3008 }
3009 #endif
3010
3129 return SQLITE_OK; 3011 return SQLITE_OK;
3130 } 3012 }
3131 } 3013 }
3132 3014
3133 /* 3015 /*
3134 ** Determine the current size of a file in bytes 3016 ** Determine the current size of a file in bytes
3135 */ 3017 */
3136 static int unixFileSize(sqlite3_file *id, i64 *pSize){ 3018 static int unixFileSize(sqlite3_file *id, i64 *pSize){
3137 int rc; 3019 int rc;
3138 struct stat buf; 3020 struct stat buf;
3139 assert( id ); 3021 assert( id );
3140 rc = fstat(((unixFile*)id)->h, &buf); 3022 rc = fstat(((unixFile*)id)->h, &buf);
3141 SimulateIOError( rc=1 ); 3023 SimulateIOError( rc=1 );
3142 if( rc!=0 ){ 3024 if( rc!=0 ){
3143 ((unixFile*)id)->lastErrno = errno; 3025 ((unixFile*)id)->lastErrno = errno;
3144 return SQLITE_IOERR_FSTAT; 3026 return SQLITE_IOERR_FSTAT;
3145 } 3027 }
3146 *pSize = buf.st_size; 3028 *pSize = buf.st_size;
3147 3029
3148 /* When opening a zero-size database, the findLockInfo() procedure 3030 /* When opening a zero-size database, the findInodeInfo() procedure
3149 ** writes a single byte into that file in order to work around a bug 3031 ** writes a single byte into that file in order to work around a bug
3150 ** in the OS-X msdos filesystem. In order to avoid problems with upper 3032 ** in the OS-X msdos filesystem. In order to avoid problems with upper
3151 ** layers, we need to report this file size as zero even though it is 3033 ** layers, we need to report this file size as zero even though it is
3152 ** really 1. Ticket #3260. 3034 ** really 1. Ticket #3260.
3153 */ 3035 */
3154 if( *pSize==1 ) *pSize = 0; 3036 if( *pSize==1 ) *pSize = 0;
3155 3037
3156 3038
3157 return SQLITE_OK; 3039 return SQLITE_OK;
3158 } 3040 }
3159 3041
3160 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) 3042 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
3161 /* 3043 /*
3162 ** Handler for proxy-locking file-control verbs. Defined below in the 3044 ** Handler for proxy-locking file-control verbs. Defined below in the
3163 ** proxying locking division. 3045 ** proxying locking division.
3164 */ 3046 */
3165 static int proxyFileControl(sqlite3_file*,int,void*); 3047 static int proxyFileControl(sqlite3_file*,int,void*);
3166 #endif 3048 #endif
3167 3049
3050 /*
3051 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
3052 ** file-control operation.
3053 **
3054 ** If the user has configured a chunk-size for this file, it could be
3055 ** that the file needs to be extended at this point. Otherwise, the
3056 ** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
3057 */
3058 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
3059 if( pFile->szChunk ){
3060 i64 nSize; /* Required file size */
3061 struct stat buf; /* Used to hold return values of fstat() */
3062
3063 if( fstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
3064
3065 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
3066 if( nSize>(i64)buf.st_size ){
3067 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
3068 if( posix_fallocate(pFile->h, buf.st_size, nSize-buf.st_size) ){
3069 return SQLITE_IOERR_WRITE;
3070 }
3071 #else
3072 /* If the OS does not have posix_fallocate(), fake it. First use
3073 ** ftruncate() to set the file size, then write a single byte to
3074 ** the last byte in each block within the extended region. This
3075 ** is the same technique used by glibc to implement posix_fallocate()
3076 ** on systems that do not have a real fallocate() system call.
3077 */
3078 int nBlk = buf.st_blksize; /* File-system block size */
3079 i64 iWrite; /* Next offset to write to */
3080 int nWrite; /* Return value from seekAndWrite() */
3081
3082 if( ftruncate(pFile->h, nSize) ){
3083 pFile->lastErrno = errno;
3084 return SQLITE_IOERR_TRUNCATE;
3085 }
3086 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
3087 do {
3088 nWrite = seekAndWrite(pFile, iWrite, "", 1);
3089 iWrite += nBlk;
3090 } while( nWrite==1 && iWrite<nSize );
3091 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
3092 #endif
3093 }
3094 }
3095
3096 return SQLITE_OK;
3097 }
3168 3098
3169 /* 3099 /*
3170 ** Information and control of an open file handle. 3100 ** Information and control of an open file handle.
3171 */ 3101 */
3172 static int unixFileControl(sqlite3_file *id, int op, void *pArg){ 3102 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
3173 switch( op ){ 3103 switch( op ){
3174 case SQLITE_FCNTL_LOCKSTATE: { 3104 case SQLITE_FCNTL_LOCKSTATE: {
3175 *(int*)pArg = ((unixFile*)id)->locktype; 3105 *(int*)pArg = ((unixFile*)id)->eFileLock;
3176 return SQLITE_OK; 3106 return SQLITE_OK;
3177 } 3107 }
3178 case SQLITE_LAST_ERRNO: { 3108 case SQLITE_LAST_ERRNO: {
3179 *(int*)pArg = ((unixFile*)id)->lastErrno; 3109 *(int*)pArg = ((unixFile*)id)->lastErrno;
3180 return SQLITE_OK; 3110 return SQLITE_OK;
3181 } 3111 }
3112 case SQLITE_FCNTL_CHUNK_SIZE: {
3113 ((unixFile*)id)->szChunk = *(int *)pArg;
3114 return SQLITE_OK;
3115 }
3116 case SQLITE_FCNTL_SIZE_HINT: {
3117 return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
3118 }
3182 #ifndef NDEBUG 3119 #ifndef NDEBUG
3183 /* The pager calls this method to signal that it has done 3120 /* The pager calls this method to signal that it has done
3184 ** a rollback and that the database is therefore unchanged and 3121 ** a rollback and that the database is therefore unchanged and
3185 ** it hence it is OK for the transaction change counter to be 3122 ** it hence it is OK for the transaction change counter to be
3186 ** unchanged. 3123 ** unchanged.
3187 */ 3124 */
3188 case SQLITE_FCNTL_DB_UNCHANGED: { 3125 case SQLITE_FCNTL_DB_UNCHANGED: {
3189 ((unixFile*)id)->dbUpdate = 0; 3126 ((unixFile*)id)->dbUpdate = 0;
3190 return SQLITE_OK; 3127 return SQLITE_OK;
3191 } 3128 }
(...skipping 24 matching lines...) Expand all
3216 } 3153 }
3217 3154
3218 /* 3155 /*
3219 ** Return the device characteristics for the file. This is always 0 for unix. 3156 ** Return the device characteristics for the file. This is always 0 for unix.
3220 */ 3157 */
3221 static int unixDeviceCharacteristics(sqlite3_file *NotUsed){ 3158 static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
3222 UNUSED_PARAMETER(NotUsed); 3159 UNUSED_PARAMETER(NotUsed);
3223 return 0; 3160 return 0;
3224 } 3161 }
3225 3162
3163 #ifndef SQLITE_OMIT_WAL
3164
3165
3166 /*
3167 ** Object used to represent an shared memory buffer.
3168 **
3169 ** When multiple threads all reference the same wal-index, each thread
3170 ** has its own unixShm object, but they all point to a single instance
3171 ** of this unixShmNode object. In other words, each wal-index is opened
3172 ** only once per process.
3173 **
3174 ** Each unixShmNode object is connected to a single unixInodeInfo object.
3175 ** We could coalesce this object into unixInodeInfo, but that would mean
3176 ** every open file that does not use shared memory (in other words, most
3177 ** open files) would have to carry around this extra information. So
3178 ** the unixInodeInfo object contains a pointer to this unixShmNode object
3179 ** and the unixShmNode object is created only when needed.
3180 **
3181 ** unixMutexHeld() must be true when creating or destroying
3182 ** this object or while reading or writing the following fields:
3183 **
3184 ** nRef
3185 **
3186 ** The following fields are read-only after the object is created:
3187 **
3188 ** fid
3189 ** zFilename
3190 **
3191 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
3192 ** unixMutexHeld() is true when reading or writing any other field
3193 ** in this structure.
3194 */
3195 struct unixShmNode {
3196 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
3197 sqlite3_mutex *mutex; /* Mutex to access this object */
3198 char *zFilename; /* Name of the mmapped file */
3199 int h; /* Open file descriptor */
3200 int szRegion; /* Size of shared-memory regions */
3201 int nRegion; /* Size of array apRegion */
3202 char **apRegion; /* Array of mapped shared-memory regions */
3203 int nRef; /* Number of unixShm objects pointing to this */
3204 unixShm *pFirst; /* All unixShm objects pointing to this */
3205 #ifdef SQLITE_DEBUG
3206 u8 exclMask; /* Mask of exclusive locks held */
3207 u8 sharedMask; /* Mask of shared locks held */
3208 u8 nextShmId; /* Next available unixShm.id value */
3209 #endif
3210 };
3211
3212 /*
3213 ** Structure used internally by this VFS to record the state of an
3214 ** open shared memory connection.
3215 **
3216 ** The following fields are initialized when this object is created and
3217 ** are read-only thereafter:
3218 **
3219 ** unixShm.pFile
3220 ** unixShm.id
3221 **
3222 ** All other fields are read/write. The unixShm.pFile->mutex must be held
3223 ** while accessing any read/write fields.
3224 */
3225 struct unixShm {
3226 unixShmNode *pShmNode; /* The underlying unixShmNode object */
3227 unixShm *pNext; /* Next unixShm with the same unixShmNode */
3228 u8 hasMutex; /* True if holding the unixShmNode mutex */
3229 u16 sharedMask; /* Mask of shared locks held */
3230 u16 exclMask; /* Mask of exclusive locks held */
3231 #ifdef SQLITE_DEBUG
3232 u8 id; /* Id of this connection within its unixShmNode */
3233 #endif
3234 };
3235
3236 /*
3237 ** Constants used for locking
3238 */
3239 #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
3240 #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
3241
3242 /*
3243 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
3244 **
3245 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
3246 ** otherwise.
3247 */
3248 static int unixShmSystemLock(
3249 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
3250 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
3251 int ofst, /* First byte of the locking range */
3252 int n /* Number of bytes to lock */
3253 ){
3254 struct flock f; /* The posix advisory locking structure */
3255 int rc = SQLITE_OK; /* Result code form fcntl() */
3256
3257 /* Access to the unixShmNode object is serialized by the caller */
3258 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
3259
3260 /* Shared locks never span more than one byte */
3261 assert( n==1 || lockType!=F_RDLCK );
3262
3263 /* Locks are within range */
3264 assert( n>=1 && n<SQLITE_SHM_NLOCK );
3265
3266 /* Initialize the locking parameters */
3267 memset(&f, 0, sizeof(f));
3268 f.l_type = lockType;
3269 f.l_whence = SEEK_SET;
3270 f.l_start = ofst;
3271 f.l_len = n;
3272
3273 rc = fcntl(pShmNode->h, F_SETLK, &f);
3274 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
3275
3276 /* Update the global lock state and do debug tracing */
3277 #ifdef SQLITE_DEBUG
3278 { u16 mask;
3279 OSTRACE(("SHM-LOCK "));
3280 mask = (1<<(ofst+n)) - (1<<ofst);
3281 if( rc==SQLITE_OK ){
3282 if( lockType==F_UNLCK ){
3283 OSTRACE(("unlock %d ok", ofst));
3284 pShmNode->exclMask &= ~mask;
3285 pShmNode->sharedMask &= ~mask;
3286 }else if( lockType==F_RDLCK ){
3287 OSTRACE(("read-lock %d ok", ofst));
3288 pShmNode->exclMask &= ~mask;
3289 pShmNode->sharedMask |= mask;
3290 }else{
3291 assert( lockType==F_WRLCK );
3292 OSTRACE(("write-lock %d ok", ofst));
3293 pShmNode->exclMask |= mask;
3294 pShmNode->sharedMask &= ~mask;
3295 }
3296 }else{
3297 if( lockType==F_UNLCK ){
3298 OSTRACE(("unlock %d failed", ofst));
3299 }else if( lockType==F_RDLCK ){
3300 OSTRACE(("read-lock failed"));
3301 }else{
3302 assert( lockType==F_WRLCK );
3303 OSTRACE(("write-lock %d failed", ofst));
3304 }
3305 }
3306 OSTRACE((" - afterwards %03x,%03x\n",
3307 pShmNode->sharedMask, pShmNode->exclMask));
3308 }
3309 #endif
3310
3311 return rc;
3312 }
3313
3314
3315 /*
3316 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
3317 **
3318 ** This is not a VFS shared-memory method; it is a utility function called
3319 ** by VFS shared-memory methods.
3320 */
3321 static void unixShmPurge(unixFile *pFd){
3322 unixShmNode *p = pFd->pInode->pShmNode;
3323 assert( unixMutexHeld() );
3324 if( p && p->nRef==0 ){
3325 int i;
3326 assert( p->pInode==pFd->pInode );
3327 if( p->mutex ) sqlite3_mutex_free(p->mutex);
3328 for(i=0; i<p->nRegion; i++){
3329 munmap(p->apRegion[i], p->szRegion);
3330 }
3331 sqlite3_free(p->apRegion);
3332 if( p->h>=0 ) close(p->h);
3333 p->pInode->pShmNode = 0;
3334 sqlite3_free(p);
3335 }
3336 }
3337
3338 /*
3339 ** Open a shared-memory area associated with open database file pDbFd.
3340 ** This particular implementation uses mmapped files.
3341 **
3342 ** The file used to implement shared-memory is in the same directory
3343 ** as the open database file and has the same name as the open database
3344 ** file with the "-shm" suffix added. For example, if the database file
3345 ** is "/home/user1/config.db" then the file that is created and mmapped
3346 ** for shared memory will be called "/home/user1/config.db-shm".
3347 **
3348 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
3349 ** some other tmpfs mount. But if a file in a different directory
3350 ** from the database file is used, then differing access permissions
3351 ** or a chroot() might cause two different processes on the same
3352 ** database to end up using different files for shared memory -
3353 ** meaning that their memory would not really be shared - resulting
3354 ** in database corruption. Nevertheless, this tmpfs file usage
3355 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
3356 ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
3357 ** option results in an incompatible build of SQLite; builds of SQLite
3358 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
3359 ** same database file at the same time, database corruption will likely
3360 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
3361 ** "unsupported" and may go away in a future SQLite release.
3362 **
3363 ** When opening a new shared-memory file, if no other instances of that
3364 ** file are currently open, in this process or in other processes, then
3365 ** the file must be truncated to zero length or have its header cleared.
3366 */
3367 static int unixOpenSharedMemory(unixFile *pDbFd){
3368 struct unixShm *p = 0; /* The connection to be opened */
3369 struct unixShmNode *pShmNode; /* The underlying mmapped file */
3370 int rc; /* Result code */
3371 unixInodeInfo *pInode; /* The inode of fd */
3372 char *zShmFilename; /* Name of the file used for SHM */
3373 int nShmFilename; /* Size of the SHM filename in bytes */
3374
3375 /* Allocate space for the new unixShm object. */
3376 p = sqlite3_malloc( sizeof(*p) );
3377 if( p==0 ) return SQLITE_NOMEM;
3378 memset(p, 0, sizeof(*p));
3379 assert( pDbFd->pShm==0 );
3380
3381 /* Check to see if a unixShmNode object already exists. Reuse an existing
3382 ** one if present. Create a new one if necessary.
3383 */
3384 unixEnterMutex();
3385 pInode = pDbFd->pInode;
3386 pShmNode = pInode->pShmNode;
3387 if( pShmNode==0 ){
3388 struct stat sStat; /* fstat() info for database file */
3389
3390 /* Call fstat() to figure out the permissions on the database file. If
3391 ** a new *-shm file is created, an attempt will be made to create it
3392 ** with the same permissions. The actual permissions the file is created
3393 ** with are subject to the current umask setting.
3394 */
3395 if( fstat(pDbFd->h, &sStat) ){
3396 rc = SQLITE_IOERR_FSTAT;
3397 goto shm_open_err;
3398 }
3399
3400 #ifdef SQLITE_SHM_DIRECTORY
3401 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
3402 #else
3403 nShmFilename = 5 + (int)strlen(pDbFd->zPath);
3404 #endif
3405 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
3406 if( pShmNode==0 ){
3407 rc = SQLITE_NOMEM;
3408 goto shm_open_err;
3409 }
3410 memset(pShmNode, 0, sizeof(*pShmNode));
3411 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
3412 #ifdef SQLITE_SHM_DIRECTORY
3413 sqlite3_snprintf(nShmFilename, zShmFilename,
3414 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
3415 (u32)sStat.st_ino, (u32)sStat.st_dev);
3416 #else
3417 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
3418 #endif
3419 pShmNode->h = -1;
3420 pDbFd->pInode->pShmNode = pShmNode;
3421 pShmNode->pInode = pDbFd->pInode;
3422 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
3423 if( pShmNode->mutex==0 ){
3424 rc = SQLITE_NOMEM;
3425 goto shm_open_err;
3426 }
3427
3428 pShmNode->h = open(zShmFilename, O_RDWR|O_CREAT, (sStat.st_mode & 0777));
3429 if( pShmNode->h<0 ){
3430 rc = SQLITE_CANTOPEN_BKPT;
3431 goto shm_open_err;
3432 }
3433
3434 /* Check to see if another process is holding the dead-man switch.
3435 ** If not, truncate the file to zero length.
3436 */
3437 rc = SQLITE_OK;
3438 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
3439 if( ftruncate(pShmNode->h, 0) ){
3440 rc = SQLITE_IOERR_SHMOPEN;
3441 }
3442 }
3443 if( rc==SQLITE_OK ){
3444 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
3445 }
3446 if( rc ) goto shm_open_err;
3447 }
3448
3449 /* Make the new connection a child of the unixShmNode */
3450 p->pShmNode = pShmNode;
3451 #ifdef SQLITE_DEBUG
3452 p->id = pShmNode->nextShmId++;
3453 #endif
3454 pShmNode->nRef++;
3455 pDbFd->pShm = p;
3456 unixLeaveMutex();
3457
3458 /* The reference count on pShmNode has already been incremented under
3459 ** the cover of the unixEnterMutex() mutex and the pointer from the
3460 ** new (struct unixShm) object to the pShmNode has been set. All that is
3461 ** left to do is to link the new object into the linked list starting
3462 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
3463 ** mutex.
3464 */
3465 sqlite3_mutex_enter(pShmNode->mutex);
3466 p->pNext = pShmNode->pFirst;
3467 pShmNode->pFirst = p;
3468 sqlite3_mutex_leave(pShmNode->mutex);
3469 return SQLITE_OK;
3470
3471 /* Jump here on any error */
3472 shm_open_err:
3473 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
3474 sqlite3_free(p);
3475 unixLeaveMutex();
3476 return rc;
3477 }
3478
3479 /*
3480 ** This function is called to obtain a pointer to region iRegion of the
3481 ** shared-memory associated with the database file fd. Shared-memory regions
3482 ** are numbered starting from zero. Each shared-memory region is szRegion
3483 ** bytes in size.
3484 **
3485 ** If an error occurs, an error code is returned and *pp is set to NULL.
3486 **
3487 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
3488 ** region has not been allocated (by any client, including one running in a
3489 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
3490 ** bExtend is non-zero and the requested shared-memory region has not yet
3491 ** been allocated, it is allocated by this function.
3492 **
3493 ** If the shared-memory region has already been allocated or is allocated by
3494 ** this call as described above, then it is mapped into this processes
3495 ** address space (if it is not already), *pp is set to point to the mapped
3496 ** memory and SQLITE_OK returned.
3497 */
3498 static int unixShmMap(
3499 sqlite3_file *fd, /* Handle open on database file */
3500 int iRegion, /* Region to retrieve */
3501 int szRegion, /* Size of regions */
3502 int bExtend, /* True to extend file if necessary */
3503 void volatile **pp /* OUT: Mapped memory */
3504 ){
3505 unixFile *pDbFd = (unixFile*)fd;
3506 unixShm *p;
3507 unixShmNode *pShmNode;
3508 int rc = SQLITE_OK;
3509
3510 /* If the shared-memory file has not yet been opened, open it now. */
3511 if( pDbFd->pShm==0 ){
3512 rc = unixOpenSharedMemory(pDbFd);
3513 if( rc!=SQLITE_OK ) return rc;
3514 }
3515
3516 p = pDbFd->pShm;
3517 pShmNode = p->pShmNode;
3518 sqlite3_mutex_enter(pShmNode->mutex);
3519 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
3520
3521 if( pShmNode->nRegion<=iRegion ){
3522 char **apNew; /* New apRegion[] array */
3523 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
3524 struct stat sStat; /* Used by fstat() */
3525
3526 pShmNode->szRegion = szRegion;
3527
3528 /* The requested region is not mapped into this processes address space.
3529 ** Check to see if it has been allocated (i.e. if the wal-index file is
3530 ** large enough to contain the requested region).
3531 */
3532 if( fstat(pShmNode->h, &sStat) ){
3533 rc = SQLITE_IOERR_SHMSIZE;
3534 goto shmpage_out;
3535 }
3536
3537 if( sStat.st_size<nByte ){
3538 /* The requested memory region does not exist. If bExtend is set to
3539 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
3540 **
3541 ** Alternatively, if bExtend is true, use ftruncate() to allocate
3542 ** the requested memory region.
3543 */
3544 if( !bExtend ) goto shmpage_out;
3545 if( ftruncate(pShmNode->h, nByte) ){
3546 rc = SQLITE_IOERR_SHMSIZE;
3547 goto shmpage_out;
3548 }
3549 }
3550
3551 /* Map the requested memory region into this processes address space. */
3552 apNew = (char **)sqlite3_realloc(
3553 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
3554 );
3555 if( !apNew ){
3556 rc = SQLITE_IOERR_NOMEM;
3557 goto shmpage_out;
3558 }
3559 pShmNode->apRegion = apNew;
3560 while(pShmNode->nRegion<=iRegion){
3561 void *pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE,
3562 MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
3563 );
3564 if( pMem==MAP_FAILED ){
3565 rc = SQLITE_IOERR;
3566 goto shmpage_out;
3567 }
3568 pShmNode->apRegion[pShmNode->nRegion] = pMem;
3569 pShmNode->nRegion++;
3570 }
3571 }
3572
3573 shmpage_out:
3574 if( pShmNode->nRegion>iRegion ){
3575 *pp = pShmNode->apRegion[iRegion];
3576 }else{
3577 *pp = 0;
3578 }
3579 sqlite3_mutex_leave(pShmNode->mutex);
3580 return rc;
3581 }
3582
3583 /*
3584 ** Change the lock state for a shared-memory segment.
3585 **
3586 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
3587 ** different here than in posix. In xShmLock(), one can go from unlocked
3588 ** to shared and back or from unlocked to exclusive and back. But one may
3589 ** not go from shared to exclusive or from exclusive to shared.
3590 */
3591 static int unixShmLock(
3592 sqlite3_file *fd, /* Database file holding the shared memory */
3593 int ofst, /* First lock to acquire or release */
3594 int n, /* Number of locks to acquire or release */
3595 int flags /* What to do with the lock */
3596 ){
3597 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
3598 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
3599 unixShm *pX; /* For looping over all siblings */
3600 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
3601 int rc = SQLITE_OK; /* Result code */
3602 u16 mask; /* Mask of locks to take or release */
3603
3604 assert( pShmNode==pDbFd->pInode->pShmNode );
3605 assert( pShmNode->pInode==pDbFd->pInode );
3606 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
3607 assert( n>=1 );
3608 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
3609 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
3610 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
3611 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
3612 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
3613
3614 mask = (1<<(ofst+n)) - (1<<ofst);
3615 assert( n>1 || mask==(1<<ofst) );
3616 sqlite3_mutex_enter(pShmNode->mutex);
3617 if( flags & SQLITE_SHM_UNLOCK ){
3618 u16 allMask = 0; /* Mask of locks held by siblings */
3619
3620 /* See if any siblings hold this same lock */
3621 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
3622 if( pX==p ) continue;
3623 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
3624 allMask |= pX->sharedMask;
3625 }
3626
3627 /* Unlock the system-level locks */
3628 if( (mask & allMask)==0 ){
3629 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
3630 }else{
3631 rc = SQLITE_OK;
3632 }
3633
3634 /* Undo the local locks */
3635 if( rc==SQLITE_OK ){
3636 p->exclMask &= ~mask;
3637 p->sharedMask &= ~mask;
3638 }
3639 }else if( flags & SQLITE_SHM_SHARED ){
3640 u16 allShared = 0; /* Union of locks held by connections other than "p" */
3641
3642 /* Find out which shared locks are already held by sibling connections.
3643 ** If any sibling already holds an exclusive lock, go ahead and return
3644 ** SQLITE_BUSY.
3645 */
3646 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
3647 if( (pX->exclMask & mask)!=0 ){
3648 rc = SQLITE_BUSY;
3649 break;
3650 }
3651 allShared |= pX->sharedMask;
3652 }
3653
3654 /* Get shared locks at the system level, if necessary */
3655 if( rc==SQLITE_OK ){
3656 if( (allShared & mask)==0 ){
3657 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
3658 }else{
3659 rc = SQLITE_OK;
3660 }
3661 }
3662
3663 /* Get the local shared locks */
3664 if( rc==SQLITE_OK ){
3665 p->sharedMask |= mask;
3666 }
3667 }else{
3668 /* Make sure no sibling connections hold locks that will block this
3669 ** lock. If any do, return SQLITE_BUSY right away.
3670 */
3671 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
3672 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
3673 rc = SQLITE_BUSY;
3674 break;
3675 }
3676 }
3677
3678 /* Get the exclusive locks at the system level. Then if successful
3679 ** also mark the local connection as being locked.
3680 */
3681 if( rc==SQLITE_OK ){
3682 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
3683 if( rc==SQLITE_OK ){
3684 assert( (p->sharedMask & mask)==0 );
3685 p->exclMask |= mask;
3686 }
3687 }
3688 }
3689 sqlite3_mutex_leave(pShmNode->mutex);
3690 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
3691 p->id, getpid(), p->sharedMask, p->exclMask));
3692 return rc;
3693 }
3694
3695 /*
3696 ** Implement a memory barrier or memory fence on shared memory.
3697 **
3698 ** All loads and stores begun before the barrier must complete before
3699 ** any load or store begun after the barrier.
3700 */
3701 static void unixShmBarrier(
3702 sqlite3_file *fd /* Database file holding the shared memory */
3703 ){
3704 UNUSED_PARAMETER(fd);
3705 unixEnterMutex();
3706 unixLeaveMutex();
3707 }
3708
3709 /*
3710 ** Close a connection to shared-memory. Delete the underlying
3711 ** storage if deleteFlag is true.
3712 **
3713 ** If there is no shared memory associated with the connection then this
3714 ** routine is a harmless no-op.
3715 */
3716 static int unixShmUnmap(
3717 sqlite3_file *fd, /* The underlying database file */
3718 int deleteFlag /* Delete shared-memory if true */
3719 ){
3720 unixShm *p; /* The connection to be closed */
3721 unixShmNode *pShmNode; /* The underlying shared-memory file */
3722 unixShm **pp; /* For looping over sibling connections */
3723 unixFile *pDbFd; /* The underlying database file */
3724
3725 pDbFd = (unixFile*)fd;
3726 p = pDbFd->pShm;
3727 if( p==0 ) return SQLITE_OK;
3728 pShmNode = p->pShmNode;
3729
3730 assert( pShmNode==pDbFd->pInode->pShmNode );
3731 assert( pShmNode->pInode==pDbFd->pInode );
3732
3733 /* Remove connection p from the set of connections associated
3734 ** with pShmNode */
3735 sqlite3_mutex_enter(pShmNode->mutex);
3736 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
3737 *pp = p->pNext;
3738
3739 /* Free the connection p */
3740 sqlite3_free(p);
3741 pDbFd->pShm = 0;
3742 sqlite3_mutex_leave(pShmNode->mutex);
3743
3744 /* If pShmNode->nRef has reached 0, then close the underlying
3745 ** shared-memory file, too */
3746 unixEnterMutex();
3747 assert( pShmNode->nRef>0 );
3748 pShmNode->nRef--;
3749 if( pShmNode->nRef==0 ){
3750 if( deleteFlag ) unlink(pShmNode->zFilename);
3751 unixShmPurge(pDbFd);
3752 }
3753 unixLeaveMutex();
3754
3755 return SQLITE_OK;
3756 }
3757
3758
3759 #else
3760 # define unixShmMap 0
3761 # define unixShmLock 0
3762 # define unixShmBarrier 0
3763 # define unixShmUnmap 0
3764 #endif /* #ifndef SQLITE_OMIT_WAL */
3765
3226 /* 3766 /*
3227 ** Here ends the implementation of all sqlite3_file methods. 3767 ** Here ends the implementation of all sqlite3_file methods.
3228 ** 3768 **
3229 ********************** End sqlite3_file Methods ******************************* 3769 ********************** End sqlite3_file Methods *******************************
3230 ******************************************************************************/ 3770 ******************************************************************************/
3231 3771
3772
3232 /* 3773 /*
3233 ** This division contains definitions of sqlite3_io_methods objects that 3774 ** This division contains definitions of sqlite3_io_methods objects that
3234 ** implement various file locking strategies. It also contains definitions 3775 ** implement various file locking strategies. It also contains definitions
3235 ** of "finder" functions. A finder-function is used to locate the appropriate 3776 ** of "finder" functions. A finder-function is used to locate the appropriate
3236 ** sqlite3_io_methods object for a particular database file. The pAppData 3777 ** sqlite3_io_methods object for a particular database file. The pAppData
3237 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to 3778 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
3238 ** the correct finder-function for that VFS. 3779 ** the correct finder-function for that VFS.
3239 ** 3780 **
3240 ** Most finder functions return a pointer to a fixed sqlite3_io_methods 3781 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
3241 ** object. The only interesting finder-function is autolockIoFinder, which 3782 ** object. The only interesting finder-function is autolockIoFinder, which
(...skipping 14 matching lines...) Expand all
3256 ** 3797 **
3257 ** 3798 **
3258 ** Each instance of this macro generates two objects: 3799 ** Each instance of this macro generates two objects:
3259 ** 3800 **
3260 ** * A constant sqlite3_io_methods object call METHOD that has locking 3801 ** * A constant sqlite3_io_methods object call METHOD that has locking
3261 ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK. 3802 ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
3262 ** 3803 **
3263 ** * An I/O method finder function called FINDER that returns a pointer 3804 ** * An I/O method finder function called FINDER that returns a pointer
3264 ** to the METHOD object in the previous bullet. 3805 ** to the METHOD object in the previous bullet.
3265 */ 3806 */
3266 #define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK) \ 3807 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
3267 static const sqlite3_io_methods METHOD = { \ 3808 static const sqlite3_io_methods METHOD = { \
3268 1, /* iVersion */ \ 3809 VERSION, /* iVersion */ \
3269 CLOSE, /* xClose */ \ 3810 CLOSE, /* xClose */ \
3270 unixRead, /* xRead */ \ 3811 unixRead, /* xRead */ \
3271 unixWrite, /* xWrite */ \ 3812 unixWrite, /* xWrite */ \
3272 unixTruncate, /* xTruncate */ \ 3813 unixTruncate, /* xTruncate */ \
3273 unixSync, /* xSync */ \ 3814 unixSync, /* xSync */ \
3274 unixFileSize, /* xFileSize */ \ 3815 unixFileSize, /* xFileSize */ \
3275 LOCK, /* xLock */ \ 3816 LOCK, /* xLock */ \
3276 UNLOCK, /* xUnlock */ \ 3817 UNLOCK, /* xUnlock */ \
3277 CKLOCK, /* xCheckReservedLock */ \ 3818 CKLOCK, /* xCheckReservedLock */ \
3278 unixFileControl, /* xFileControl */ \ 3819 unixFileControl, /* xFileControl */ \
3279 unixSectorSize, /* xSectorSize */ \ 3820 unixSectorSize, /* xSectorSize */ \
3280 unixDeviceCharacteristics /* xDeviceCapabilities */ \ 3821 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
3822 unixShmMap, /* xShmMap */ \
3823 unixShmLock, /* xShmLock */ \
3824 unixShmBarrier, /* xShmBarrier */ \
3825 unixShmUnmap /* xShmUnmap */ \
3281 }; \ 3826 }; \
3282 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \ 3827 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
3283 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \ 3828 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
3284 return &METHOD; \ 3829 return &METHOD; \
3285 } \ 3830 } \
3286 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \ 3831 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
3287 = FINDER##Impl; 3832 = FINDER##Impl;
3288 3833
3289 /* 3834 /*
3290 ** Here are all of the sqlite3_io_methods objects for each of the 3835 ** Here are all of the sqlite3_io_methods objects for each of the
3291 ** locking strategies. Functions that return pointers to these methods 3836 ** locking strategies. Functions that return pointers to these methods
3292 ** are also created. 3837 ** are also created.
3293 */ 3838 */
3294 IOMETHODS( 3839 IOMETHODS(
3295 posixIoFinder, /* Finder function name */ 3840 posixIoFinder, /* Finder function name */
3296 posixIoMethods, /* sqlite3_io_methods object name */ 3841 posixIoMethods, /* sqlite3_io_methods object name */
3842 2, /* shared memory is enabled */
3297 unixClose, /* xClose method */ 3843 unixClose, /* xClose method */
3298 unixLock, /* xLock method */ 3844 unixLock, /* xLock method */
3299 unixUnlock, /* xUnlock method */ 3845 unixUnlock, /* xUnlock method */
3300 unixCheckReservedLock /* xCheckReservedLock method */ 3846 unixCheckReservedLock /* xCheckReservedLock method */
3301 ) 3847 )
3302 IOMETHODS( 3848 IOMETHODS(
3303 nolockIoFinder, /* Finder function name */ 3849 nolockIoFinder, /* Finder function name */
3304 nolockIoMethods, /* sqlite3_io_methods object name */ 3850 nolockIoMethods, /* sqlite3_io_methods object name */
3851 1, /* shared memory is disabled */
3305 nolockClose, /* xClose method */ 3852 nolockClose, /* xClose method */
3306 nolockLock, /* xLock method */ 3853 nolockLock, /* xLock method */
3307 nolockUnlock, /* xUnlock method */ 3854 nolockUnlock, /* xUnlock method */
3308 nolockCheckReservedLock /* xCheckReservedLock method */ 3855 nolockCheckReservedLock /* xCheckReservedLock method */
3309 ) 3856 )
3310 IOMETHODS( 3857 IOMETHODS(
3311 dotlockIoFinder, /* Finder function name */ 3858 dotlockIoFinder, /* Finder function name */
3312 dotlockIoMethods, /* sqlite3_io_methods object name */ 3859 dotlockIoMethods, /* sqlite3_io_methods object name */
3860 1, /* shared memory is disabled */
3313 dotlockClose, /* xClose method */ 3861 dotlockClose, /* xClose method */
3314 dotlockLock, /* xLock method */ 3862 dotlockLock, /* xLock method */
3315 dotlockUnlock, /* xUnlock method */ 3863 dotlockUnlock, /* xUnlock method */
3316 dotlockCheckReservedLock /* xCheckReservedLock method */ 3864 dotlockCheckReservedLock /* xCheckReservedLock method */
3317 ) 3865 )
3318 3866
3319 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS 3867 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
3320 IOMETHODS( 3868 IOMETHODS(
3321 flockIoFinder, /* Finder function name */ 3869 flockIoFinder, /* Finder function name */
3322 flockIoMethods, /* sqlite3_io_methods object name */ 3870 flockIoMethods, /* sqlite3_io_methods object name */
3871 1, /* shared memory is disabled */
3323 flockClose, /* xClose method */ 3872 flockClose, /* xClose method */
3324 flockLock, /* xLock method */ 3873 flockLock, /* xLock method */
3325 flockUnlock, /* xUnlock method */ 3874 flockUnlock, /* xUnlock method */
3326 flockCheckReservedLock /* xCheckReservedLock method */ 3875 flockCheckReservedLock /* xCheckReservedLock method */
3327 ) 3876 )
3328 #endif 3877 #endif
3329 3878
3330 #if OS_VXWORKS 3879 #if OS_VXWORKS
3331 IOMETHODS( 3880 IOMETHODS(
3332 semIoFinder, /* Finder function name */ 3881 semIoFinder, /* Finder function name */
3333 semIoMethods, /* sqlite3_io_methods object name */ 3882 semIoMethods, /* sqlite3_io_methods object name */
3883 1, /* shared memory is disabled */
3334 semClose, /* xClose method */ 3884 semClose, /* xClose method */
3335 semLock, /* xLock method */ 3885 semLock, /* xLock method */
3336 semUnlock, /* xUnlock method */ 3886 semUnlock, /* xUnlock method */
3337 semCheckReservedLock /* xCheckReservedLock method */ 3887 semCheckReservedLock /* xCheckReservedLock method */
3338 ) 3888 )
3339 #endif 3889 #endif
3340 3890
3341 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE 3891 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3342 IOMETHODS( 3892 IOMETHODS(
3343 afpIoFinder, /* Finder function name */ 3893 afpIoFinder, /* Finder function name */
3344 afpIoMethods, /* sqlite3_io_methods object name */ 3894 afpIoMethods, /* sqlite3_io_methods object name */
3895 1, /* shared memory is disabled */
3345 afpClose, /* xClose method */ 3896 afpClose, /* xClose method */
3346 afpLock, /* xLock method */ 3897 afpLock, /* xLock method */
3347 afpUnlock, /* xUnlock method */ 3898 afpUnlock, /* xUnlock method */
3348 afpCheckReservedLock /* xCheckReservedLock method */ 3899 afpCheckReservedLock /* xCheckReservedLock method */
3349 ) 3900 )
3350 #endif 3901 #endif
3351 3902
3352 /* 3903 /*
3353 ** The "Whole File Locking" finder returns the same set of methods as
3354 ** the posix locking finder. But it also sets the SQLITE_WHOLE_FILE_LOCKING
3355 ** flag to force the posix advisory locks to cover the whole file instead
3356 ** of just a small span of bytes near the 1GiB boundary. Whole File Locking
3357 ** is useful on NFS-mounted files since it helps NFS to maintain cache
3358 ** coherency. But it is a detriment to other filesystems since it runs
3359 ** slower.
3360 */
3361 static const sqlite3_io_methods *posixWflIoFinderImpl(const char*z, unixFile*p){
3362 UNUSED_PARAMETER(z);
3363 p->fileFlags = SQLITE_WHOLE_FILE_LOCKING;
3364 return &posixIoMethods;
3365 }
3366 static const sqlite3_io_methods
3367 *(*const posixWflIoFinder)(const char*,unixFile *p) = posixWflIoFinderImpl;
3368
3369 /*
3370 ** The proxy locking method is a "super-method" in the sense that it 3904 ** The proxy locking method is a "super-method" in the sense that it
3371 ** opens secondary file descriptors for the conch and lock files and 3905 ** opens secondary file descriptors for the conch and lock files and
3372 ** it uses proxy, dot-file, AFP, and flock() locking methods on those 3906 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
3373 ** secondary files. For this reason, the division that implements 3907 ** secondary files. For this reason, the division that implements
3374 ** proxy locking is located much further down in the file. But we need 3908 ** proxy locking is located much further down in the file. But we need
3375 ** to go ahead and define the sqlite3_io_methods and finder function 3909 ** to go ahead and define the sqlite3_io_methods and finder function
3376 ** for proxy locking here. So we forward declare the I/O methods. 3910 ** for proxy locking here. So we forward declare the I/O methods.
3377 */ 3911 */
3378 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE 3912 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3379 static int proxyClose(sqlite3_file*); 3913 static int proxyClose(sqlite3_file*);
3380 static int proxyLock(sqlite3_file*, int); 3914 static int proxyLock(sqlite3_file*, int);
3381 static int proxyUnlock(sqlite3_file*, int); 3915 static int proxyUnlock(sqlite3_file*, int);
3382 static int proxyCheckReservedLock(sqlite3_file*, int*); 3916 static int proxyCheckReservedLock(sqlite3_file*, int*);
3383 IOMETHODS( 3917 IOMETHODS(
3384 proxyIoFinder, /* Finder function name */ 3918 proxyIoFinder, /* Finder function name */
3385 proxyIoMethods, /* sqlite3_io_methods object name */ 3919 proxyIoMethods, /* sqlite3_io_methods object name */
3920 1, /* shared memory is disabled */
3386 proxyClose, /* xClose method */ 3921 proxyClose, /* xClose method */
3387 proxyLock, /* xLock method */ 3922 proxyLock, /* xLock method */
3388 proxyUnlock, /* xUnlock method */ 3923 proxyUnlock, /* xUnlock method */
3389 proxyCheckReservedLock /* xCheckReservedLock method */ 3924 proxyCheckReservedLock /* xCheckReservedLock method */
3390 ) 3925 )
3391 #endif 3926 #endif
3392 3927
3928 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
3929 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3930 IOMETHODS(
3931 nfsIoFinder, /* Finder function name */
3932 nfsIoMethods, /* sqlite3_io_methods object name */
3933 1, /* shared memory is disabled */
3934 unixClose, /* xClose method */
3935 unixLock, /* xLock method */
3936 nfsUnlock, /* xUnlock method */
3937 unixCheckReservedLock /* xCheckReservedLock method */
3938 )
3939 #endif
3393 3940
3394 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE 3941 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
3395 /* 3942 /*
3396 ** This "finder" function attempts to determine the best locking strategy 3943 ** This "finder" function attempts to determine the best locking strategy
3397 ** for the database file "filePath". It then returns the sqlite3_io_methods 3944 ** for the database file "filePath". It then returns the sqlite3_io_methods
3398 ** object that implements that strategy. 3945 ** object that implements that strategy.
3399 ** 3946 **
3400 ** This is for MacOSX only. 3947 ** This is for MacOSX only.
3401 */ 3948 */
3402 static const sqlite3_io_methods *autolockIoFinderImpl( 3949 static const sqlite3_io_methods *autolockIoFinderImpl(
3403 const char *filePath, /* name of the database file */ 3950 const char *filePath, /* name of the database file */
3404 unixFile *pNew /* open file object for the database file */ 3951 unixFile *pNew /* open file object for the database file */
3405 ){ 3952 ){
3406 static const struct Mapping { 3953 static const struct Mapping {
3407 const char *zFilesystem; /* Filesystem type name */ 3954 const char *zFilesystem; /* Filesystem type name */
3408 const sqlite3_io_methods *pMethods; /* Appropriate locking method */ 3955 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
3409 } aMap[] = { 3956 } aMap[] = {
3410 { "hfs", &posixIoMethods }, 3957 { "hfs", &posixIoMethods },
3411 { "ufs", &posixIoMethods }, 3958 { "ufs", &posixIoMethods },
3412 { "afpfs", &afpIoMethods }, 3959 { "afpfs", &afpIoMethods },
3413 #ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
3414 { "smbfs", &afpIoMethods }, 3960 { "smbfs", &afpIoMethods },
3415 #else
3416 { "smbfs", &flockIoMethods },
3417 #endif
3418 { "webdav", &nolockIoMethods }, 3961 { "webdav", &nolockIoMethods },
3419 { 0, 0 } 3962 { 0, 0 }
3420 }; 3963 };
3421 int i; 3964 int i;
3422 struct statfs fsInfo; 3965 struct statfs fsInfo;
3423 struct flock lockInfo; 3966 struct flock lockInfo;
3424 3967
3425 if( !filePath ){ 3968 if( !filePath ){
3426 /* If filePath==NULL that means we are dealing with a transient file 3969 /* If filePath==NULL that means we are dealing with a transient file
3427 ** that does not need to be locked. */ 3970 ** that does not need to be locked. */
(...skipping 12 matching lines...) Expand all
3440 3983
3441 /* Default case. Handles, amongst others, "nfs". 3984 /* Default case. Handles, amongst others, "nfs".
3442 ** Test byte-range lock using fcntl(). If the call succeeds, 3985 ** Test byte-range lock using fcntl(). If the call succeeds,
3443 ** assume that the file-system supports POSIX style locks. 3986 ** assume that the file-system supports POSIX style locks.
3444 */ 3987 */
3445 lockInfo.l_len = 1; 3988 lockInfo.l_len = 1;
3446 lockInfo.l_start = 0; 3989 lockInfo.l_start = 0;
3447 lockInfo.l_whence = SEEK_SET; 3990 lockInfo.l_whence = SEEK_SET;
3448 lockInfo.l_type = F_RDLCK; 3991 lockInfo.l_type = F_RDLCK;
3449 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) { 3992 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
3450 pNew->fileFlags = SQLITE_WHOLE_FILE_LOCKING; 3993 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
3451 return &posixIoMethods; 3994 return &nfsIoMethods;
3995 } else {
3996 return &posixIoMethods;
3997 }
3452 }else{ 3998 }else{
3453 return &dotlockIoMethods; 3999 return &dotlockIoMethods;
3454 } 4000 }
3455 } 4001 }
3456 static const sqlite3_io_methods 4002 static const sqlite3_io_methods
3457 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl; 4003 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
3458 4004
3459 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ 4005 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
3460 4006
3461 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE 4007 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
(...skipping 41 matching lines...) Expand 10 before | Expand all | Expand 10 after
3503 4049
3504 4050
3505 /**************************************************************************** 4051 /****************************************************************************
3506 **************************** sqlite3_vfs methods **************************** 4052 **************************** sqlite3_vfs methods ****************************
3507 ** 4053 **
3508 ** This division contains the implementation of methods on the 4054 ** This division contains the implementation of methods on the
3509 ** sqlite3_vfs object. 4055 ** sqlite3_vfs object.
3510 */ 4056 */
3511 4057
3512 /* 4058 /*
4059 ** Initializes a unixFile structure with zeros.
4060 */
4061 void initUnixFile(sqlite3_file* file) {
4062 memset(file, 0, sizeof(unixFile));
4063 }
4064
4065 /*
3513 ** Initialize the contents of the unixFile structure pointed to by pId. 4066 ** Initialize the contents of the unixFile structure pointed to by pId.
3514 */ 4067 */
3515 static int fillInUnixFile( 4068 int fillInUnixFile(
3516 sqlite3_vfs *pVfs, /* Pointer to vfs object */ 4069 sqlite3_vfs *pVfs, /* Pointer to vfs object */
3517 int h, /* Open file descriptor of file being opened */ 4070 int h, /* Open file descriptor of file being opened */
3518 int dirfd, /* Directory file descriptor */ 4071 int dirfd, /* Directory file descriptor */
3519 sqlite3_file *pId, /* Write to the unixFile structure here */ 4072 sqlite3_file *pId, /* Write to the unixFile structure here */
3520 const char *zFilename, /* Name of the file being opened */ 4073 const char *zFilename, /* Name of the file being opened */
3521 int noLock, /* Omit locking if true */ 4074 int noLock, /* Omit locking if true */
3522 int isDelete /* Delete on close if true */ 4075 int isDelete /* Delete on close if true */
3523 ){ 4076 ){
3524 const sqlite3_io_methods *pLockingStyle; 4077 const sqlite3_io_methods *pLockingStyle;
3525 unixFile *pNew = (unixFile *)pId; 4078 unixFile *pNew = (unixFile *)pId;
3526 int rc = SQLITE_OK; 4079 int rc = SQLITE_OK;
3527 4080
3528 assert( pNew->pLock==NULL ); 4081 assert( pNew->pInode==NULL );
3529 assert( pNew->pOpen==NULL );
3530 4082
3531 /* Parameter isDelete is only used on vxworks. Express this explicitly 4083 /* Parameter isDelete is only used on vxworks. Express this explicitly
3532 ** here to prevent compiler warnings about unused parameters. 4084 ** here to prevent compiler warnings about unused parameters.
3533 */ 4085 */
3534 UNUSED_PARAMETER(isDelete); 4086 UNUSED_PARAMETER(isDelete);
3535 4087
3536 OSTRACE3("OPEN %-3d %s\n", h, zFilename); 4088 /* Usually the path zFilename should not be a relative pathname. The
4089 ** exception is when opening the proxy "conch" file in builds that
4090 ** include the special Apple locking styles.
4091 */
4092 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4093 assert( zFilename==0 || zFilename[0]=='/'
4094 || pVfs->pAppData==(void*)&autolockIoFinder );
4095 #else
4096 assert( zFilename==0 || zFilename[0]=='/' );
4097 #endif
4098
4099 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
3537 pNew->h = h; 4100 pNew->h = h;
3538 pNew->dirfd = dirfd; 4101 pNew->dirfd = dirfd;
3539 SET_THREADID(pNew);
3540 pNew->fileFlags = 0; 4102 pNew->fileFlags = 0;
4103 pNew->zPath = zFilename;
3541 4104
3542 #if OS_VXWORKS 4105 #if OS_VXWORKS
3543 pNew->pId = vxworksFindFileId(zFilename); 4106 pNew->pId = vxworksFindFileId(zFilename);
3544 if( pNew->pId==0 ){ 4107 if( pNew->pId==0 ){
3545 noLock = 1; 4108 noLock = 1;
3546 rc = SQLITE_NOMEM; 4109 rc = SQLITE_NOMEM;
3547 } 4110 }
3548 #endif 4111 #endif
3549 4112
3550 if( noLock ){ 4113 if( noLock ){
3551 pLockingStyle = &nolockIoMethods; 4114 pLockingStyle = &nolockIoMethods;
3552 }else{ 4115 }else{
3553 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew); 4116 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
3554 #if SQLITE_ENABLE_LOCKING_STYLE 4117 #if SQLITE_ENABLE_LOCKING_STYLE
3555 /* Cache zFilename in the locking context (AFP and dotlock override) for 4118 /* Cache zFilename in the locking context (AFP and dotlock override) for
3556 ** proxyLock activation is possible (remote proxy is based on db name) 4119 ** proxyLock activation is possible (remote proxy is based on db name)
3557 ** zFilename remains valid until file is closed, to support */ 4120 ** zFilename remains valid until file is closed, to support */
3558 pNew->lockingContext = (void*)zFilename; 4121 pNew->lockingContext = (void*)zFilename;
3559 #endif 4122 #endif
3560 } 4123 }
3561 4124
3562 if( pLockingStyle == &posixIoMethods ){ 4125 if( pLockingStyle == &posixIoMethods
4126 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4127 || pLockingStyle == &nfsIoMethods
4128 #endif
4129 ){
3563 unixEnterMutex(); 4130 unixEnterMutex();
3564 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen); 4131 rc = findInodeInfo(pNew, &pNew->pInode);
3565 if( rc!=SQLITE_OK ){ 4132 if( rc!=SQLITE_OK ){
3566 /* If an error occured in findLockInfo(), close the file descriptor 4133 /* If an error occured in findInodeInfo(), close the file descriptor
3567 ** immediately, before releasing the mutex. findLockInfo() may fail 4134 ** immediately, before releasing the mutex. findInodeInfo() may fail
3568 ** in two scenarios: 4135 ** in two scenarios:
3569 ** 4136 **
3570 ** (a) A call to fstat() failed. 4137 ** (a) A call to fstat() failed.
3571 ** (b) A malloc failed. 4138 ** (b) A malloc failed.
3572 ** 4139 **
3573 ** Scenario (b) may only occur if the process is holding no other 4140 ** Scenario (b) may only occur if the process is holding no other
3574 ** file descriptors open on the same file. If there were other file 4141 ** file descriptors open on the same file. If there were other file
3575 ** descriptors on this file, then no malloc would be required by 4142 ** descriptors on this file, then no malloc would be required by
3576 ** findLockInfo(). If this is the case, it is quite safe to close 4143 ** findInodeInfo(). If this is the case, it is quite safe to close
3577 ** handle h - as it is guaranteed that no posix locks will be released 4144 ** handle h - as it is guaranteed that no posix locks will be released
3578 ** by doing so. 4145 ** by doing so.
3579 ** 4146 **
3580 ** If scenario (a) caused the error then things are not so safe. The 4147 ** If scenario (a) caused the error then things are not so safe. The
3581 ** implicit assumption here is that if fstat() fails, things are in 4148 ** implicit assumption here is that if fstat() fails, things are in
3582 ** such bad shape that dropping a lock or two doesn't matter much. 4149 ** such bad shape that dropping a lock or two doesn't matter much.
3583 */ 4150 */
3584 close(h); 4151 close(h);
3585 h = -1; 4152 h = -1;
3586 } 4153 }
3587 unixLeaveMutex(); 4154 unixLeaveMutex();
3588 } 4155 }
3589 4156
3590 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) 4157 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
3591 else if( pLockingStyle == &afpIoMethods ){ 4158 else if( pLockingStyle == &afpIoMethods ){
3592 /* AFP locking uses the file path so it needs to be included in 4159 /* AFP locking uses the file path so it needs to be included in
3593 ** the afpLockingContext. 4160 ** the afpLockingContext.
3594 */ 4161 */
3595 afpLockingContext *pCtx; 4162 afpLockingContext *pCtx;
3596 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) ); 4163 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
3597 if( pCtx==0 ){ 4164 if( pCtx==0 ){
3598 rc = SQLITE_NOMEM; 4165 rc = SQLITE_NOMEM;
3599 }else{ 4166 }else{
3600 /* NB: zFilename exists and remains valid until the file is closed 4167 /* NB: zFilename exists and remains valid until the file is closed
3601 ** according to requirement F11141. So we do not need to make a 4168 ** according to requirement F11141. So we do not need to make a
3602 ** copy of the filename. */ 4169 ** copy of the filename. */
3603 pCtx->dbPath = zFilename; 4170 pCtx->dbPath = zFilename;
4171 pCtx->reserved = 0;
3604 srandomdev(); 4172 srandomdev();
3605 unixEnterMutex(); 4173 unixEnterMutex();
3606 rc = findLockInfo(pNew, NULL, &pNew->pOpen); 4174 rc = findInodeInfo(pNew, &pNew->pInode);
4175 if( rc!=SQLITE_OK ){
4176 sqlite3_free(pNew->lockingContext);
4177 close(h);
4178 h = -1;
4179 }
3607 unixLeaveMutex(); 4180 unixLeaveMutex();
3608 } 4181 }
3609 } 4182 }
3610 #endif 4183 #endif
3611 4184
3612 else if( pLockingStyle == &dotlockIoMethods ){ 4185 else if( pLockingStyle == &dotlockIoMethods ){
3613 /* Dotfile locking uses the file path so it needs to be included in 4186 /* Dotfile locking uses the file path so it needs to be included in
3614 ** the dotlockLockingContext 4187 ** the dotlockLockingContext
3615 */ 4188 */
3616 char *zLockFile; 4189 char *zLockFile;
3617 int nFilename; 4190 int nFilename;
3618 nFilename = (int)strlen(zFilename) + 6; 4191 nFilename = (int)strlen(zFilename) + 6;
3619 zLockFile = (char *)sqlite3_malloc(nFilename); 4192 zLockFile = (char *)sqlite3_malloc(nFilename);
3620 if( zLockFile==0 ){ 4193 if( zLockFile==0 ){
3621 rc = SQLITE_NOMEM; 4194 rc = SQLITE_NOMEM;
3622 }else{ 4195 }else{
3623 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename); 4196 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
3624 } 4197 }
3625 pNew->lockingContext = zLockFile; 4198 pNew->lockingContext = zLockFile;
3626 } 4199 }
3627 4200
3628 #if OS_VXWORKS 4201 #if OS_VXWORKS
3629 else if( pLockingStyle == &semIoMethods ){ 4202 else if( pLockingStyle == &semIoMethods ){
3630 /* Named semaphore locking uses the file path so it needs to be 4203 /* Named semaphore locking uses the file path so it needs to be
3631 ** included in the semLockingContext 4204 ** included in the semLockingContext
3632 */ 4205 */
3633 unixEnterMutex(); 4206 unixEnterMutex();
3634 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen); 4207 rc = findInodeInfo(pNew, &pNew->pInode);
3635 if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){ 4208 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
3636 char *zSemName = pNew->pOpen->aSemName; 4209 char *zSemName = pNew->pInode->aSemName;
3637 int n; 4210 int n;
3638 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem", 4211 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
3639 pNew->pId->zCanonicalName); 4212 pNew->pId->zCanonicalName);
3640 for( n=1; zSemName[n]; n++ ) 4213 for( n=1; zSemName[n]; n++ )
3641 if( zSemName[n]=='/' ) zSemName[n] = '_'; 4214 if( zSemName[n]=='/' ) zSemName[n] = '_';
3642 pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1); 4215 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
3643 if( pNew->pOpen->pSem == SEM_FAILED ){ 4216 if( pNew->pInode->pSem == SEM_FAILED ){
3644 rc = SQLITE_NOMEM; 4217 rc = SQLITE_NOMEM;
3645 pNew->pOpen->aSemName[0] = '\0'; 4218 pNew->pInode->aSemName[0] = '\0';
3646 } 4219 }
3647 } 4220 }
3648 unixLeaveMutex(); 4221 unixLeaveMutex();
3649 } 4222 }
3650 #endif 4223 #endif
3651 4224
3652 pNew->lastErrno = 0; 4225 pNew->lastErrno = 0;
3653 #if OS_VXWORKS 4226 #if OS_VXWORKS
3654 if( rc!=SQLITE_OK ){ 4227 if( rc!=SQLITE_OK ){
4228 if( h>=0 ) close(h);
4229 h = -1;
3655 unlink(zFilename); 4230 unlink(zFilename);
3656 isDelete = 0; 4231 isDelete = 0;
3657 } 4232 }
3658 pNew->isDelete = isDelete; 4233 pNew->isDelete = isDelete;
3659 #endif 4234 #endif
3660 if( rc!=SQLITE_OK ){ 4235 if( rc!=SQLITE_OK ){
3661 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */ 4236 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
3662 if( h>=0 ) close(h); 4237 if( h>=0 ) close(h);
3663 }else{ 4238 }else{
3664 pNew->pMethod = pLockingStyle; 4239 pNew->pMethod = pLockingStyle;
(...skipping 19 matching lines...) Expand all
3684 4259
3685 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename); 4260 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
3686 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--); 4261 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
3687 if( ii>0 ){ 4262 if( ii>0 ){
3688 zDirname[ii] = '\0'; 4263 zDirname[ii] = '\0';
3689 fd = open(zDirname, O_RDONLY|O_BINARY, 0); 4264 fd = open(zDirname, O_RDONLY|O_BINARY, 0);
3690 if( fd>=0 ){ 4265 if( fd>=0 ){
3691 #ifdef FD_CLOEXEC 4266 #ifdef FD_CLOEXEC
3692 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC); 4267 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3693 #endif 4268 #endif
3694 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname); 4269 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
3695 } 4270 }
3696 } 4271 }
3697 *pFd = fd; 4272 *pFd = fd;
3698 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN); 4273 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN_BKPT);
4274 }
4275
4276 /*
4277 ** Return the name of a directory in which to put temporary files.
4278 ** If no suitable temporary file directory can be found, return NULL.
4279 */
4280 static const char *unixTempFileDir(void){
4281 static const char *azDirs[] = {
4282 0,
4283 0,
4284 "/var/tmp",
4285 "/usr/tmp",
4286 "/tmp",
4287 0 /* List terminator */
4288 };
4289 unsigned int i;
4290 struct stat buf;
4291 const char *zDir = 0;
4292
4293 azDirs[0] = sqlite3_temp_directory;
4294 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
4295 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
4296 if( zDir==0 ) continue;
4297 if( stat(zDir, &buf) ) continue;
4298 if( !S_ISDIR(buf.st_mode) ) continue;
4299 if( access(zDir, 07) ) continue;
4300 break;
4301 }
4302 return zDir;
3699 } 4303 }
3700 4304
3701 /* 4305 /*
3702 ** Create a temporary file name in zBuf. zBuf must be allocated 4306 ** Create a temporary file name in zBuf. zBuf must be allocated
3703 ** by the calling process and must be big enough to hold at least 4307 ** by the calling process and must be big enough to hold at least
3704 ** pVfs->mxPathname bytes. 4308 ** pVfs->mxPathname bytes.
3705 */ 4309 */
3706 static int getTempname(int nBuf, char *zBuf){ 4310 static int unixGetTempname(int nBuf, char *zBuf){
3707 static const char *azDirs[] = {
3708 0,
3709 0,
3710 "/var/tmp",
3711 "/usr/tmp",
3712 "/tmp",
3713 ".",
3714 };
3715 static const unsigned char zChars[] = 4311 static const unsigned char zChars[] =
3716 "abcdefghijklmnopqrstuvwxyz" 4312 "abcdefghijklmnopqrstuvwxyz"
3717 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 4313 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
3718 "0123456789"; 4314 "0123456789";
3719 unsigned int i, j; 4315 unsigned int i, j;
3720 struct stat buf; 4316 const char *zDir;
3721 const char *zDir = ".";
3722 4317
3723 /* It's odd to simulate an io-error here, but really this is just 4318 /* It's odd to simulate an io-error here, but really this is just
3724 ** using the io-error infrastructure to test that SQLite handles this 4319 ** using the io-error infrastructure to test that SQLite handles this
3725 ** function failing. 4320 ** function failing.
3726 */ 4321 */
3727 SimulateIOError( return SQLITE_IOERR ); 4322 SimulateIOError( return SQLITE_IOERR );
3728 4323
3729 azDirs[0] = sqlite3_temp_directory; 4324 zDir = unixTempFileDir();
3730 if (NULL == azDirs[1]) { 4325 if( zDir==0 ) zDir = ".";
3731 azDirs[1] = getenv("TMPDIR");
3732 }
3733
3734 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
3735 if( azDirs[i]==0 ) continue;
3736 if( stat(azDirs[i], &buf) ) continue;
3737 if( !S_ISDIR(buf.st_mode) ) continue;
3738 if( access(azDirs[i], 07) ) continue;
3739 zDir = azDirs[i];
3740 break;
3741 }
3742 4326
3743 /* Check that the output buffer is large enough for the temporary file 4327 /* Check that the output buffer is large enough for the temporary file
3744 ** name. If it is not, return SQLITE_ERROR. 4328 ** name. If it is not, return SQLITE_ERROR.
3745 */ 4329 */
3746 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){ 4330 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
3747 return SQLITE_ERROR; 4331 return SQLITE_ERROR;
3748 } 4332 }
3749 4333
3750 do{ 4334 do{
3751 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir); 4335 sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
(...skipping 45 matching lines...) Expand 10 before | Expand all | Expand 10 after
3797 4381
3798 /* A stat() call may fail for various reasons. If this happens, it is 4382 /* A stat() call may fail for various reasons. If this happens, it is
3799 ** almost certain that an open() call on the same path will also fail. 4383 ** almost certain that an open() call on the same path will also fail.
3800 ** For this reason, if an error occurs in the stat() call here, it is 4384 ** For this reason, if an error occurs in the stat() call here, it is
3801 ** ignored and -1 is returned. The caller will try to open a new file 4385 ** ignored and -1 is returned. The caller will try to open a new file
3802 ** descriptor on the same path, fail, and return an error to SQLite. 4386 ** descriptor on the same path, fail, and return an error to SQLite.
3803 ** 4387 **
3804 ** Even if a subsequent open() call does succeed, the consequences of 4388 ** Even if a subsequent open() call does succeed, the consequences of
3805 ** not searching for a resusable file descriptor are not dire. */ 4389 ** not searching for a resusable file descriptor are not dire. */
3806 if( 0==stat(zPath, &sStat) ){ 4390 if( 0==stat(zPath, &sStat) ){
3807 struct unixOpenCnt *pO; 4391 unixInodeInfo *pInode;
3808 struct unixFileId id;
3809 id.dev = sStat.st_dev;
3810 id.ino = sStat.st_ino;
3811 4392
3812 unixEnterMutex(); 4393 unixEnterMutex();
3813 for(pO=openList; pO && memcmp(&id, &pO->fileId, sizeof(id)); pO=pO->pNext); 4394 pInode = inodeList;
3814 if( pO ){ 4395 while( pInode && (pInode->fileId.dev!=sStat.st_dev
4396 || pInode->fileId.ino!=sStat.st_ino) ){
4397 pInode = pInode->pNext;
4398 }
4399 if( pInode ){
3815 UnixUnusedFd **pp; 4400 UnixUnusedFd **pp;
3816 for(pp=&pO->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext)); 4401 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
3817 pUnused = *pp; 4402 pUnused = *pp;
3818 if( pUnused ){ 4403 if( pUnused ){
3819 *pp = pUnused->pNext; 4404 *pp = pUnused->pNext;
3820 } 4405 }
3821 } 4406 }
3822 unixLeaveMutex(); 4407 unixLeaveMutex();
3823 } 4408 }
3824 #endif /* if !OS_VXWORKS */ 4409 #endif /* if !OS_VXWORKS */
3825 return pUnused; 4410 return pUnused;
3826 } 4411 }
3827 4412
3828 /* 4413 /*
4414 ** This function is called by unixOpen() to determine the unix permissions
4415 ** to create new files with. If no error occurs, then SQLITE_OK is returned
4416 ** and a value suitable for passing as the third argument to open(2) is
4417 ** written to *pMode. If an IO error occurs, an SQLite error code is
4418 ** returned and the value of *pMode is not modified.
4419 **
4420 ** If the file being opened is a temporary file, it is always created with
4421 ** the octal permissions 0600 (read/writable by owner only). If the file
4422 ** is a database or master journal file, it is created with the permissions
4423 ** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
4424 **
4425 ** Finally, if the file being opened is a WAL or regular journal file, then
4426 ** this function queries the file-system for the permissions on the
4427 ** corresponding database file and sets *pMode to this value. Whenever
4428 ** possible, WAL and journal files are created using the same permissions
4429 ** as the associated database file.
4430 */
4431 static int findCreateFileMode(
4432 const char *zPath, /* Path of file (possibly) being created */
4433 int flags, /* Flags passed as 4th argument to xOpen() */
4434 mode_t *pMode /* OUT: Permissions to open file with */
4435 ){
4436 int rc = SQLITE_OK; /* Return Code */
4437 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
4438 char zDb[MAX_PATHNAME+1]; /* Database file path */
4439 int nDb; /* Number of valid bytes in zDb */
4440 struct stat sStat; /* Output of stat() on database file */
4441
4442 nDb = sqlite3Strlen30(zPath) - ((flags & SQLITE_OPEN_WAL) ? 4 : 8);
4443 memcpy(zDb, zPath, nDb);
4444 zDb[nDb] = '\0';
4445 if( 0==stat(zDb, &sStat) ){
4446 *pMode = sStat.st_mode & 0777;
4447 }else{
4448 rc = SQLITE_IOERR_FSTAT;
4449 }
4450 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
4451 *pMode = 0600;
4452 }else{
4453 *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
4454 }
4455 return rc;
4456 }
4457
4458 /*
3829 ** Open the file zPath. 4459 ** Open the file zPath.
3830 ** 4460 **
3831 ** Previously, the SQLite OS layer used three functions in place of this 4461 ** Previously, the SQLite OS layer used three functions in place of this
3832 ** one: 4462 ** one:
3833 ** 4463 **
3834 ** sqlite3OsOpenReadWrite(); 4464 ** sqlite3OsOpenReadWrite();
3835 ** sqlite3OsOpenReadOnly(); 4465 ** sqlite3OsOpenReadOnly();
3836 ** sqlite3OsOpenExclusive(); 4466 ** sqlite3OsOpenExclusive();
3837 ** 4467 **
3838 ** These calls correspond to the following combinations of flags: 4468 ** These calls correspond to the following combinations of flags:
(...skipping 21 matching lines...) Expand all
3860 int openFlags = 0; /* Flags to pass to open() */ 4490 int openFlags = 0; /* Flags to pass to open() */
3861 int eType = flags&0xFFFFFF00; /* Type of file to open */ 4491 int eType = flags&0xFFFFFF00; /* Type of file to open */
3862 int noLock; /* True to omit locking primitives */ 4492 int noLock; /* True to omit locking primitives */
3863 int rc = SQLITE_OK; /* Function Return Code */ 4493 int rc = SQLITE_OK; /* Function Return Code */
3864 4494
3865 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE); 4495 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
3866 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE); 4496 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
3867 int isCreate = (flags & SQLITE_OPEN_CREATE); 4497 int isCreate = (flags & SQLITE_OPEN_CREATE);
3868 int isReadonly = (flags & SQLITE_OPEN_READONLY); 4498 int isReadonly = (flags & SQLITE_OPEN_READONLY);
3869 int isReadWrite = (flags & SQLITE_OPEN_READWRITE); 4499 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
4500 #if SQLITE_ENABLE_LOCKING_STYLE
4501 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
4502 #endif
3870 4503
3871 /* If creating a master or main-file journal, this function will open 4504 /* If creating a master or main-file journal, this function will open
3872 ** a file-descriptor on the directory too. The first time unixSync() 4505 ** a file-descriptor on the directory too. The first time unixSync()
3873 ** is called the directory file descriptor will be fsync()ed and close()d. 4506 ** is called the directory file descriptor will be fsync()ed and close()d.
3874 */ 4507 */
3875 int isOpenDirectory = (isCreate && 4508 int isOpenDirectory = (isCreate && (
3876 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL) 4509 eType==SQLITE_OPEN_MASTER_JOURNAL
3877 ); 4510 || eType==SQLITE_OPEN_MAIN_JOURNAL
4511 || eType==SQLITE_OPEN_WAL
4512 ));
3878 4513
3879 /* If argument zPath is a NULL pointer, this function is required to open 4514 /* If argument zPath is a NULL pointer, this function is required to open
3880 ** a temporary file. Use this buffer to store the file name in. 4515 ** a temporary file. Use this buffer to store the file name in.
3881 */ 4516 */
3882 char zTmpname[MAX_PATHNAME+1]; 4517 char zTmpname[MAX_PATHNAME+1];
3883 const char *zName = zPath; 4518 const char *zName = zPath;
3884 4519
3885 /* Check the following statements are true: 4520 /* Check the following statements are true:
3886 ** 4521 **
3887 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and 4522 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
3888 ** (b) if CREATE is set, then READWRITE must also be set, and 4523 ** (b) if CREATE is set, then READWRITE must also be set, and
3889 ** (c) if EXCLUSIVE is set, then CREATE must also be set. 4524 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
3890 ** (d) if DELETEONCLOSE is set, then CREATE must also be set. 4525 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
3891 */ 4526 */
3892 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly)); 4527 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
3893 assert(isCreate==0 || isReadWrite); 4528 assert(isCreate==0 || isReadWrite);
3894 assert(isExclusive==0 || isCreate); 4529 assert(isExclusive==0 || isCreate);
3895 assert(isDelete==0 || isCreate); 4530 assert(isDelete==0 || isCreate);
3896 4531
3897 /* The main DB, main journal, and master journal are never automatically 4532 /* The main DB, main journal, WAL file and master journal are never
3898 ** deleted. Nor are they ever temporary files. */ 4533 ** automatically deleted. Nor are they ever temporary files. */
3899 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB ); 4534 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
3900 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL ); 4535 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
3901 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL ); 4536 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
4537 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
3902 4538
3903 /* Assert that the upper layer has set one of the "file-type" flags. */ 4539 /* Assert that the upper layer has set one of the "file-type" flags. */
3904 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB 4540 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
3905 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 4541 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
3906 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL 4542 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
3907 || eType==SQLITE_OPEN_TRANSIENT_DB 4543 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
3908 ); 4544 );
3909 4545
3910 memset(p, 0, sizeof(unixFile)); 4546 memset(p, 0, sizeof(unixFile));
3911 4547
3912 if( eType==SQLITE_OPEN_MAIN_DB ){ 4548 if( eType==SQLITE_OPEN_MAIN_DB ){
3913 UnixUnusedFd *pUnused; 4549 UnixUnusedFd *pUnused;
3914 pUnused = findReusableFd(zName, flags); 4550 pUnused = findReusableFd(zName, flags);
3915 if( pUnused ){ 4551 if( pUnused ){
3916 fd = pUnused->fd; 4552 fd = pUnused->fd;
3917 }else{ 4553 }else{
3918 pUnused = sqlite3_malloc(sizeof(*pUnused)); 4554 pUnused = sqlite3_malloc(sizeof(*pUnused));
3919 if( !pUnused ){ 4555 if( !pUnused ){
3920 return SQLITE_NOMEM; 4556 return SQLITE_NOMEM;
3921 } 4557 }
3922 } 4558 }
3923 p->pUnused = pUnused; 4559 p->pUnused = pUnused;
3924 }else if( !zName ){ 4560 }else if( !zName ){
3925 /* If zName is NULL, the upper layer is requesting a temp file. */ 4561 /* If zName is NULL, the upper layer is requesting a temp file. */
3926 assert(isDelete && !isOpenDirectory); 4562 assert(isDelete && !isOpenDirectory);
3927 rc = getTempname(MAX_PATHNAME+1, zTmpname); 4563 rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
3928 if( rc!=SQLITE_OK ){ 4564 if( rc!=SQLITE_OK ){
3929 return rc; 4565 return rc;
3930 } 4566 }
3931 zName = zTmpname; 4567 zName = zTmpname;
3932 } 4568 }
3933 4569
3934 /* Determine the value of the flags parameter passed to POSIX function 4570 /* Determine the value of the flags parameter passed to POSIX function
3935 ** open(). These must be calculated even if open() is not called, as 4571 ** open(). These must be calculated even if open() is not called, as
3936 ** they may be stored as part of the file handle and used by the 4572 ** they may be stored as part of the file handle and used by the
3937 ** 'conch file' locking functions later on. */ 4573 ** 'conch file' locking functions later on. */
3938 if( isReadonly ) openFlags |= O_RDONLY; 4574 if( isReadonly ) openFlags |= O_RDONLY;
3939 if( isReadWrite ) openFlags |= O_RDWR; 4575 if( isReadWrite ) openFlags |= O_RDWR;
3940 if( isCreate ) openFlags |= O_CREAT; 4576 if( isCreate ) openFlags |= O_CREAT;
3941 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW); 4577 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
3942 openFlags |= (O_LARGEFILE|O_BINARY); 4578 openFlags |= (O_LARGEFILE|O_BINARY);
3943 4579
3944 if( fd<0 ){ 4580 if( fd<0 ){
3945 mode_t openMode = (isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS); 4581 mode_t openMode; /* Permissions to create file with */
4582 rc = findCreateFileMode(zName, flags, &openMode);
4583 if( rc!=SQLITE_OK ){
4584 assert( !p->pUnused );
4585 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
4586 return rc;
4587 }
3946 fd = open(zName, openFlags, openMode); 4588 fd = open(zName, openFlags, openMode);
3947 OSTRACE4("OPENX %-3d %s 0%o\n", fd, zName, openFlags); 4589 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
3948 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){ 4590 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
3949 /* Failed to open the file for read/write access. Try read-only. */ 4591 /* Failed to open the file for read/write access. Try read-only. */
3950 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE); 4592 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
3951 openFlags &= ~(O_RDWR|O_CREAT); 4593 openFlags &= ~(O_RDWR|O_CREAT);
3952 flags |= SQLITE_OPEN_READONLY; 4594 flags |= SQLITE_OPEN_READONLY;
3953 openFlags |= O_RDONLY; 4595 openFlags |= O_RDONLY;
3954 fd = open(zName, openFlags, openMode); 4596 fd = open(zName, openFlags, openMode);
3955 } 4597 }
3956 if( fd<0 ){ 4598 if( fd<0 ){
3957 rc = SQLITE_CANTOPEN; 4599 rc = SQLITE_CANTOPEN_BKPT;
3958 goto open_finished; 4600 goto open_finished;
3959 } 4601 }
3960 } 4602 }
3961 assert( fd>=0 ); 4603 assert( fd>=0 );
3962 if( pOutFlags ){ 4604 if( pOutFlags ){
3963 *pOutFlags = flags; 4605 *pOutFlags = flags;
3964 } 4606 }
3965 4607
3966 if( p->pUnused ){ 4608 if( p->pUnused ){
3967 p->pUnused->fd = fd; 4609 p->pUnused->fd = fd;
(...skipping 25 matching lines...) Expand all
3993 goto open_finished; 4635 goto open_finished;
3994 } 4636 }
3995 } 4637 }
3996 4638
3997 #ifdef FD_CLOEXEC 4639 #ifdef FD_CLOEXEC
3998 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC); 4640 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
3999 #endif 4641 #endif
4000 4642
4001 noLock = eType!=SQLITE_OPEN_MAIN_DB; 4643 noLock = eType!=SQLITE_OPEN_MAIN_DB;
4002 4644
4645
4646 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
4647 struct statfs fsInfo;
4648 if( fstatfs(fd, &fsInfo) == -1 ){
4649 ((unixFile*)pFile)->lastErrno = errno;
4650 if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
4651 close(fd); /* silently leak if fail, in error */
4652 return SQLITE_IOERR_ACCESS;
4653 }
4654 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
4655 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
4656 }
4657 #endif
4658
4659 #if SQLITE_ENABLE_LOCKING_STYLE
4003 #if SQLITE_PREFER_PROXY_LOCKING 4660 #if SQLITE_PREFER_PROXY_LOCKING
4004 if( zPath!=NULL && !noLock && pVfs->xOpen ){ 4661 isAutoProxy = 1;
4662 #endif
4663 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
4005 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING"); 4664 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
4006 int useProxy = 0; 4665 int useProxy = 0;
4007 4666
4008 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 4667 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
4009 ** never use proxy, NULL means use proxy for non-local files only. */ 4668 ** never use proxy, NULL means use proxy for non-local files only. */
4010 if( envforce!=NULL ){ 4669 if( envforce!=NULL ){
4011 useProxy = atoi(envforce)>0; 4670 useProxy = atoi(envforce)>0;
4012 }else{ 4671 }else{
4013 struct statfs fsInfo; 4672 struct statfs fsInfo;
4014 if( statfs(zPath, &fsInfo) == -1 ){ 4673 if( statfs(zPath, &fsInfo) == -1 ){
(...skipping 11 matching lines...) Expand all
4026 close(fd); /* silently leak if fail, in error */ 4685 close(fd); /* silently leak if fail, in error */
4027 rc = SQLITE_IOERR_ACCESS; 4686 rc = SQLITE_IOERR_ACCESS;
4028 goto open_finished; 4687 goto open_finished;
4029 } 4688 }
4030 useProxy = !(fsInfo.f_flags&MNT_LOCAL); 4689 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
4031 } 4690 }
4032 if( useProxy ){ 4691 if( useProxy ){
4033 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete); 4692 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4034 if( rc==SQLITE_OK ){ 4693 if( rc==SQLITE_OK ){
4035 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:"); 4694 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
4695 if( rc!=SQLITE_OK ){
4696 /* Use unixClose to clean up the resources added in fillInUnixFile
4697 ** and clear all the structure's references. Specifically,
4698 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
4699 */
4700 unixClose(pFile);
4701 return rc;
4702 }
4036 } 4703 }
4037 goto open_finished; 4704 goto open_finished;
4038 } 4705 }
4039 } 4706 }
4040 #endif 4707 #endif
4041 4708
4042 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete); 4709 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
4043 open_finished: 4710 open_finished:
4044 if( rc!=SQLITE_OK ){ 4711 if( rc!=SQLITE_OK ){
4045 sqlite3_free(p->pUnused); 4712 sqlite3_free(p->pUnused);
4046 } 4713 }
4047 return rc; 4714 return rc;
4048 } 4715 }
4049 4716
4050 4717
4051 /* 4718 /*
4052 ** Delete the file at zPath. If the dirSync argument is true, fsync() 4719 ** Delete the file at zPath. If the dirSync argument is true, fsync()
4053 ** the directory after deleting the file. 4720 ** the directory after deleting the file.
4054 */ 4721 */
4055 static int unixDelete( 4722 static int unixDelete(
4056 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */ 4723 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
4057 const char *zPath, /* Name of file to be deleted */ 4724 const char *zPath, /* Name of file to be deleted */
4058 int dirSync /* If true, fsync() directory after deleting file */ 4725 int dirSync /* If true, fsync() directory after deleting file */
4059 ){ 4726 ){
4060 int rc = SQLITE_OK; 4727 int rc = SQLITE_OK;
4061 UNUSED_PARAMETER(NotUsed); 4728 UNUSED_PARAMETER(NotUsed);
4062 SimulateIOError(return SQLITE_IOERR_DELETE); 4729 SimulateIOError(return SQLITE_IOERR_DELETE);
4063 unlink(zPath); 4730 if( unlink(zPath)==(-1) && errno!=ENOENT ){
4731 return SQLITE_IOERR_DELETE;
4732 }
4064 #ifndef SQLITE_DISABLE_DIRSYNC 4733 #ifndef SQLITE_DISABLE_DIRSYNC
4065 if( dirSync ){ 4734 if( dirSync ){
4066 int fd; 4735 int fd;
4067 rc = openDirectory(zPath, &fd); 4736 rc = openDirectory(zPath, &fd);
4068 if( rc==SQLITE_OK ){ 4737 if( rc==SQLITE_OK ){
4069 #if OS_VXWORKS 4738 #if OS_VXWORKS
4070 if( fsync(fd)==-1 ) 4739 if( fsync(fd)==-1 )
4071 #else 4740 #else
4072 if( fsync(fd) ) 4741 if( fsync(fd) )
4073 #endif 4742 #endif
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after
4110 amode = W_OK|R_OK; 4779 amode = W_OK|R_OK;
4111 break; 4780 break;
4112 case SQLITE_ACCESS_READ: 4781 case SQLITE_ACCESS_READ:
4113 amode = R_OK; 4782 amode = R_OK;
4114 break; 4783 break;
4115 4784
4116 default: 4785 default:
4117 assert(!"Invalid flags argument"); 4786 assert(!"Invalid flags argument");
4118 } 4787 }
4119 *pResOut = (access(zPath, amode)==0); 4788 *pResOut = (access(zPath, amode)==0);
4789 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
4790 struct stat buf;
4791 if( 0==stat(zPath, &buf) && buf.st_size==0 ){
4792 *pResOut = 0;
4793 }
4794 }
4120 return SQLITE_OK; 4795 return SQLITE_OK;
4121 } 4796 }
4122 4797
4123 4798
4124 /* 4799 /*
4125 ** Turn a relative pathname into a full pathname. The relative path 4800 ** Turn a relative pathname into a full pathname. The relative path
4126 ** is stored as a nul-terminated string in the buffer pointed to by 4801 ** is stored as a nul-terminated string in the buffer pointed to by
4127 ** zPath. 4802 ** zPath.
4128 ** 4803 **
4129 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 4804 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
(...skipping 16 matching lines...) Expand all
4146 4821
4147 assert( pVfs->mxPathname==MAX_PATHNAME ); 4822 assert( pVfs->mxPathname==MAX_PATHNAME );
4148 UNUSED_PARAMETER(pVfs); 4823 UNUSED_PARAMETER(pVfs);
4149 4824
4150 zOut[nOut-1] = '\0'; 4825 zOut[nOut-1] = '\0';
4151 if( zPath[0]=='/' ){ 4826 if( zPath[0]=='/' ){
4152 sqlite3_snprintf(nOut, zOut, "%s", zPath); 4827 sqlite3_snprintf(nOut, zOut, "%s", zPath);
4153 }else{ 4828 }else{
4154 int nCwd; 4829 int nCwd;
4155 if( getcwd(zOut, nOut-1)==0 ){ 4830 if( getcwd(zOut, nOut-1)==0 ){
4156 return SQLITE_CANTOPEN; 4831 return SQLITE_CANTOPEN_BKPT;
4157 } 4832 }
4158 nCwd = (int)strlen(zOut); 4833 nCwd = (int)strlen(zOut);
4159 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath); 4834 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
4160 } 4835 }
4161 return SQLITE_OK; 4836 return SQLITE_OK;
4162 } 4837 }
4163 4838
4164 4839
4165 #ifndef SQLITE_OMIT_LOAD_EXTENSION 4840 #ifndef SQLITE_OMIT_LOAD_EXTENSION
4166 /* 4841 /*
(...skipping 131 matching lines...) Expand 10 before | Expand all | Expand 10 after
4298 /* 4973 /*
4299 ** The following variable, if set to a non-zero value, is interpreted as 4974 ** The following variable, if set to a non-zero value, is interpreted as
4300 ** the number of seconds since 1970 and is used to set the result of 4975 ** the number of seconds since 1970 and is used to set the result of
4301 ** sqlite3OsCurrentTime() during testing. 4976 ** sqlite3OsCurrentTime() during testing.
4302 */ 4977 */
4303 #ifdef SQLITE_TEST 4978 #ifdef SQLITE_TEST
4304 int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */ 4979 int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
4305 #endif 4980 #endif
4306 4981
4307 /* 4982 /*
4308 ** Find the current time (in Universal Coordinated Time). Write the 4983 ** Find the current time (in Universal Coordinated Time). Write into *piNow
4309 ** current time and date as a Julian Day number into *prNow and 4984 ** the current time and date as a Julian Day number times 86_400_000. In
4310 ** return 0. Return 1 if the time and date cannot be found. 4985 ** other words, write into *piNow the number of milliseconds since the Julian
4986 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
4987 ** proleptic Gregorian calendar.
4988 **
4989 ** On success, return 0. Return 1 if the time and date cannot be found.
4311 */ 4990 */
4312 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){ 4991 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
4313 #if defined(SQLITE_OMIT_FLOATING_POINT) 4992 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
4993 #if defined(NO_GETTOD)
4314 time_t t; 4994 time_t t;
4315 time(&t); 4995 time(&t);
4316 *prNow = (((sqlite3_int64)t)/8640 + 24405875)/10; 4996 *piNow = ((sqlite3_int64)i)*1000 + unixEpoch;
4317 #elif defined(NO_GETTOD)
4318 time_t t;
4319 time(&t);
4320 *prNow = t/86400.0 + 2440587.5;
4321 #elif OS_VXWORKS 4997 #elif OS_VXWORKS
4322 struct timespec sNow; 4998 struct timespec sNow;
4323 clock_gettime(CLOCK_REALTIME, &sNow); 4999 clock_gettime(CLOCK_REALTIME, &sNow);
4324 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0; 5000 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
4325 #else 5001 #else
4326 struct timeval sNow; 5002 struct timeval sNow;
4327 gettimeofday(&sNow, 0); 5003 gettimeofday(&sNow, 0);
4328 *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0; 5004 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
4329 #endif 5005 #endif
4330 5006
4331 #ifdef SQLITE_TEST 5007 #ifdef SQLITE_TEST
4332 if( sqlite3_current_time ){ 5008 if( sqlite3_current_time ){
4333 *prNow = sqlite3_current_time/86400.0 + 2440587.5; 5009 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
4334 } 5010 }
4335 #endif 5011 #endif
4336 UNUSED_PARAMETER(NotUsed); 5012 UNUSED_PARAMETER(NotUsed);
4337 return 0; 5013 return 0;
4338 } 5014 }
4339 5015
4340 /* 5016 /*
5017 ** Find the current time (in Universal Coordinated Time). Write the
5018 ** current time and date as a Julian Day number into *prNow and
5019 ** return 0. Return 1 if the time and date cannot be found.
5020 */
5021 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
5022 sqlite3_int64 i;
5023 UNUSED_PARAMETER(NotUsed);
5024 unixCurrentTimeInt64(0, &i);
5025 *prNow = i/86400000.0;
5026 return 0;
5027 }
5028
5029 /*
4341 ** We added the xGetLastError() method with the intention of providing 5030 ** We added the xGetLastError() method with the intention of providing
4342 ** better low-level error messages when operating-system problems come up 5031 ** better low-level error messages when operating-system problems come up
4343 ** during SQLite operation. But so far, none of that has been implemented 5032 ** during SQLite operation. But so far, none of that has been implemented
4344 ** in the core. So this routine is never called. For now, it is merely 5033 ** in the core. So this routine is never called. For now, it is merely
4345 ** a place-holder. 5034 ** a place-holder.
4346 */ 5035 */
4347 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){ 5036 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
4348 UNUSED_PARAMETER(NotUsed); 5037 UNUSED_PARAMETER(NotUsed);
4349 UNUSED_PARAMETER(NotUsed2); 5038 UNUSED_PARAMETER(NotUsed2);
4350 UNUSED_PARAMETER(NotUsed3); 5039 UNUSED_PARAMETER(NotUsed3);
4351 return 0; 5040 return 0;
4352 } 5041 }
4353 5042
5043
4354 /* 5044 /*
4355 ************************ End of sqlite3_vfs methods *************************** 5045 ************************ End of sqlite3_vfs methods ***************************
4356 ******************************************************************************/ 5046 ******************************************************************************/
4357 5047
4358 /****************************************************************************** 5048 /******************************************************************************
4359 ************************** Begin Proxy Locking ******************************** 5049 ************************** Begin Proxy Locking ********************************
4360 ** 5050 **
4361 ** Proxy locking is a "uber-locking-method" in this sense: It uses the 5051 ** Proxy locking is a "uber-locking-method" in this sense: It uses the
4362 ** other locking methods on secondary lock files. Proxy locking is a 5052 ** other locking methods on secondary lock files. Proxy locking is a
4363 ** meta-layer over top of the primitive locking implemented above. For 5053 ** meta-layer over top of the primitive locking implemented above. For
(...skipping 89 matching lines...) Expand 10 before | Expand all | Expand 10 after
4453 ** lock and the conch file contents is updated with the host ID and proxy 5143 ** lock and the conch file contents is updated with the host ID and proxy
4454 ** path and the lock is downgraded to a shared lock again. If the conch 5144 ** path and the lock is downgraded to a shared lock again. If the conch
4455 ** is held by another process (with a shared lock), the exclusive lock 5145 ** is held by another process (with a shared lock), the exclusive lock
4456 ** will fail and SQLITE_BUSY is returned. 5146 ** will fail and SQLITE_BUSY is returned.
4457 ** 5147 **
4458 ** The proxy file - a single-byte file used for all advisory file locks 5148 ** The proxy file - a single-byte file used for all advisory file locks
4459 ** normally taken on the database file. This allows for safe sharing 5149 ** normally taken on the database file. This allows for safe sharing
4460 ** of the database file for multiple readers and writers on the same 5150 ** of the database file for multiple readers and writers on the same
4461 ** host (the conch ensures that they all use the same local lock file). 5151 ** host (the conch ensures that they all use the same local lock file).
4462 ** 5152 **
4463 ** There is a third file - the host ID file - used as a persistent record
4464 ** of a unique identifier for the host, a 128-byte unique host id file
4465 ** in the path defined by the HOSTIDPATH macro (default value is
4466 ** /Library/Caches/.com.apple.sqliteConchHostId).
4467 **
4468 ** Requesting the lock proxy does not immediately take the conch, it is 5153 ** Requesting the lock proxy does not immediately take the conch, it is
4469 ** only taken when the first request to lock database file is made. 5154 ** only taken when the first request to lock database file is made.
4470 ** This matches the semantics of the traditional locking behavior, where 5155 ** This matches the semantics of the traditional locking behavior, where
4471 ** opening a connection to a database file does not take a lock on it. 5156 ** opening a connection to a database file does not take a lock on it.
4472 ** The shared lock and an open file descriptor are maintained until 5157 ** The shared lock and an open file descriptor are maintained until
4473 ** the connection to the database is closed. 5158 ** the connection to the database is closed.
4474 ** 5159 **
4475 ** The proxy file and the lock file are never deleted so they only need 5160 ** The proxy file and the lock file are never deleted so they only need
4476 ** to be created the first time they are used. 5161 ** to be created the first time they are used.
4477 ** 5162 **
4478 ** Configuration options 5163 ** Configuration options
4479 ** --------------------- 5164 ** ---------------------
4480 ** 5165 **
4481 ** SQLITE_PREFER_PROXY_LOCKING 5166 ** SQLITE_PREFER_PROXY_LOCKING
4482 ** 5167 **
4483 ** Database files accessed on non-local file systems are 5168 ** Database files accessed on non-local file systems are
4484 ** automatically configured for proxy locking, lock files are 5169 ** automatically configured for proxy locking, lock files are
4485 ** named automatically using the same logic as 5170 ** named automatically using the same logic as
4486 ** PRAGMA lock_proxy_file=":auto:" 5171 ** PRAGMA lock_proxy_file=":auto:"
4487 ** 5172 **
4488 ** SQLITE_PROXY_DEBUG 5173 ** SQLITE_PROXY_DEBUG
4489 ** 5174 **
4490 ** Enables the logging of error messages during host id file 5175 ** Enables the logging of error messages during host id file
4491 ** retrieval and creation 5176 ** retrieval and creation
4492 ** 5177 **
4493 ** HOSTIDPATH
4494 **
4495 ** Overrides the default host ID file path location
4496 **
4497 ** LOCKPROXYDIR 5178 ** LOCKPROXYDIR
4498 ** 5179 **
4499 ** Overrides the default directory used for lock proxy files that 5180 ** Overrides the default directory used for lock proxy files that
4500 ** are named automatically via the ":auto:" setting 5181 ** are named automatically via the ":auto:" setting
4501 ** 5182 **
4502 ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 5183 ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
4503 ** 5184 **
4504 ** Permissions to use when creating a directory for storing the 5185 ** Permissions to use when creating a directory for storing the
4505 ** lock proxy files, only used when LOCKPROXYDIR is not set. 5186 ** lock proxy files, only used when LOCKPROXYDIR is not set.
4506 ** 5187 **
4507 ** 5188 **
4508 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING, 5189 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
4509 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will 5190 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
4510 ** force proxy locking to be used for every database file opened, and 0 5191 ** force proxy locking to be used for every database file opened, and 0
4511 ** will force automatic proxy locking to be disabled for all database 5192 ** will force automatic proxy locking to be disabled for all database
4512 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or 5193 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
4513 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING). 5194 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
4514 */ 5195 */
4515 5196
4516 /* 5197 /*
4517 ** Proxy locking is only available on MacOSX 5198 ** Proxy locking is only available on MacOSX
4518 */ 5199 */
4519 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE 5200 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
4520 5201
4521 #ifdef SQLITE_TEST
4522 /* simulate multiple hosts by creating unique hostid file paths */
4523 int sqlite3_hostid_num = 0;
4524 #endif
4525
4526 /* 5202 /*
4527 ** The proxyLockingContext has the path and file structures for the remote 5203 ** The proxyLockingContext has the path and file structures for the remote
4528 ** and local proxy files in it 5204 ** and local proxy files in it
4529 */ 5205 */
4530 typedef struct proxyLockingContext proxyLockingContext; 5206 typedef struct proxyLockingContext proxyLockingContext;
4531 struct proxyLockingContext { 5207 struct proxyLockingContext {
4532 unixFile *conchFile; /* Open conch file */ 5208 unixFile *conchFile; /* Open conch file */
4533 char *conchFilePath; /* Name of the conch file */ 5209 char *conchFilePath; /* Name of the conch file */
4534 unixFile *lockProxy; /* Open proxy lock file */ 5210 unixFile *lockProxy; /* Open proxy lock file */
4535 char *lockProxyPath; /* Name of the proxy lock file */ 5211 char *lockProxyPath; /* Name of the proxy lock file */
4536 char *dbPath; /* Name of the open file */ 5212 char *dbPath; /* Name of the open file */
4537 int conchHeld; /* True if the conch is currently held */ 5213 int conchHeld; /* 1 if the conch is held, -1 if lockless */
4538 void *oldLockingContext; /* Original lockingcontext to restore on close */ 5214 void *oldLockingContext; /* Original lockingcontext to restore on close */
4539 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */ 5215 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
4540 }; 5216 };
4541 5217
4542 /* HOSTIDLEN and CONCHLEN both include space for the string 5218 /*
4543 ** terminating nul 5219 ** The proxy lock file path for the database at dbPath is written into lPath,
5220 ** which must point to valid, writable memory large enough for a maxLen length
5221 ** file path.
4544 */ 5222 */
4545 #define HOSTIDLEN 128
4546 #define CONCHLEN (MAXPATHLEN+HOSTIDLEN+1)
4547 #ifndef HOSTIDPATH
4548 # define HOSTIDPATH "/Library/Caches/.com.apple.sqliteConchHostId"
4549 #endif
4550
4551 /* basically a copy of unixRandomness with different
4552 ** test behavior built in */
4553 static int proxyGenerateHostID(char *pHostID){
4554 int pid, fd, len;
4555 unsigned char *key = (unsigned char *)pHostID;
4556
4557 memset(key, 0, HOSTIDLEN);
4558 len = 0;
4559 fd = open("/dev/urandom", O_RDONLY);
4560 if( fd>=0 ){
4561 len = read(fd, key, HOSTIDLEN);
4562 close(fd); /* silently leak the fd if it fails */
4563 }
4564 if( len < HOSTIDLEN ){
4565 time_t t;
4566 time(&t);
4567 memcpy(key, &t, sizeof(t));
4568 pid = getpid();
4569 memcpy(&key[sizeof(t)], &pid, sizeof(pid));
4570 }
4571
4572 #ifdef MAKE_PRETTY_HOSTID
4573 {
4574 int i;
4575 /* filter the bytes into printable ascii characters and NUL terminate */
4576 key[(HOSTIDLEN-1)] = 0x00;
4577 for( i=0; i<(HOSTIDLEN-1); i++ ){
4578 unsigned char pa = key[i]&0x7F;
4579 if( pa<0x20 ){
4580 key[i] = (key[i]&0x80 == 0x80) ? pa+0x40 : pa+0x20;
4581 }else if( pa==0x7F ){
4582 key[i] = (key[i]&0x80 == 0x80) ? pa=0x20 : pa+0x7E;
4583 }
4584 }
4585 }
4586 #endif
4587 return SQLITE_OK;
4588 }
4589
4590 /* writes the host id path to path, path should be an pre-allocated buffer
4591 ** with enough space for a path
4592 */
4593 static void proxyGetHostIDPath(char *path, size_t len){
4594 strlcpy(path, HOSTIDPATH, len);
4595 #ifdef SQLITE_TEST
4596 if( sqlite3_hostid_num>0 ){
4597 char suffix[2] = "1";
4598 suffix[0] = suffix[0] + sqlite3_hostid_num;
4599 strlcat(path, suffix, len);
4600 }
4601 #endif
4602 OSTRACE3("GETHOSTIDPATH %s pid=%d\n", path, getpid());
4603 }
4604
4605 /* get the host ID from a sqlite hostid file stored in the
4606 ** user-specific tmp directory, create the ID if it's not there already
4607 */
4608 static int proxyGetHostID(char *pHostID, int *pError){
4609 int fd;
4610 char path[MAXPATHLEN];
4611 size_t len;
4612 int rc=SQLITE_OK;
4613
4614 proxyGetHostIDPath(path, MAXPATHLEN);
4615 /* try to create the host ID file, if it already exists read the contents */
4616 fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644);
4617 if( fd<0 ){
4618 int err=errno;
4619
4620 if( err!=EEXIST ){
4621 #ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
4622 fprintf(stderr, "sqlite error creating host ID file %s: %s\n",
4623 path, strerror(err));
4624 #endif
4625 return SQLITE_PERM;
4626 }
4627 /* couldn't create the file, read it instead */
4628 fd = open(path, O_RDONLY|O_EXCL);
4629 if( fd<0 ){
4630 #ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
4631 int err = errno;
4632 fprintf(stderr, "sqlite error opening host ID file %s: %s\n",
4633 path, strerror(err));
4634 #endif
4635 return SQLITE_PERM;
4636 }
4637 len = pread(fd, pHostID, HOSTIDLEN, 0);
4638 if( len<0 ){
4639 *pError = errno;
4640 rc = SQLITE_IOERR_READ;
4641 }else if( len<HOSTIDLEN ){
4642 *pError = 0;
4643 rc = SQLITE_IOERR_SHORT_READ;
4644 }
4645 close(fd); /* silently leak the fd if it fails */
4646 OSTRACE3("GETHOSTID read %s pid=%d\n", pHostID, getpid());
4647 return rc;
4648 }else{
4649 /* we're creating the host ID file (use a random string of bytes) */
4650 proxyGenerateHostID(pHostID);
4651 len = pwrite(fd, pHostID, HOSTIDLEN, 0);
4652 if( len<0 ){
4653 *pError = errno;
4654 rc = SQLITE_IOERR_WRITE;
4655 }else if( len<HOSTIDLEN ){
4656 *pError = 0;
4657 rc = SQLITE_IOERR_WRITE;
4658 }
4659 close(fd); /* silently leak the fd if it fails */
4660 OSTRACE3("GETHOSTID wrote %s pid=%d\n", pHostID, getpid());
4661 return rc;
4662 }
4663 }
4664
4665 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){ 5223 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
4666 int len; 5224 int len;
4667 int dbLen; 5225 int dbLen;
4668 int i; 5226 int i;
4669 5227
4670 #ifdef LOCKPROXYDIR 5228 #ifdef LOCKPROXYDIR
4671 len = strlcpy(lPath, LOCKPROXYDIR, maxLen); 5229 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
4672 #else 5230 #else
4673 # ifdef _CS_DARWIN_USER_TEMP_DIR 5231 # ifdef _CS_DARWIN_USER_TEMP_DIR
4674 { 5232 {
4675 confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen); 5233 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
4676 len = strlcat(lPath, "sqliteplocks", maxLen); 5234 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
4677 if( mkdir(lPath, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){ 5235 lPath, errno, getpid()));
4678 /* if mkdir fails, handle as lock file creation failure */ 5236 return SQLITE_IOERR_LOCK;
4679 # ifdef SQLITE_DEBUG
4680 int err = errno;
4681 if( err!=EEXIST ){
4682 fprintf(stderr, "proxyGetLockPath: mkdir(%s,0%o) error %d %s\n", lPath,
4683 SQLITE_DEFAULT_PROXYDIR_PERMISSIONS, err, strerror(err));
4684 }
4685 # endif
4686 }else{
4687 OSTRACE3("GETLOCKPATH mkdir %s pid=%d\n", lPath, getpid());
4688 } 5237 }
4689 5238 len = strlcat(lPath, "sqliteplocks", maxLen);
4690 } 5239 }
4691 # else 5240 # else
4692 len = strlcpy(lPath, "/tmp/", maxLen); 5241 len = strlcpy(lPath, "/tmp/", maxLen);
4693 # endif 5242 # endif
4694 #endif 5243 #endif
4695 5244
4696 if( lPath[len-1]!='/' ){ 5245 if( lPath[len-1]!='/' ){
4697 len = strlcat(lPath, "/", maxLen); 5246 len = strlcat(lPath, "/", maxLen);
4698 } 5247 }
4699 5248
4700 /* transform the db path to a unique cache name */ 5249 /* transform the db path to a unique cache name */
4701 dbLen = (int)strlen(dbPath); 5250 dbLen = (int)strlen(dbPath);
4702 for( i=0; i<dbLen && (i+len+7)<maxLen; i++){ 5251 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
4703 char c = dbPath[i]; 5252 char c = dbPath[i];
4704 lPath[i+len] = (c=='/')?'_':c; 5253 lPath[i+len] = (c=='/')?'_':c;
4705 } 5254 }
4706 lPath[i+len]='\0'; 5255 lPath[i+len]='\0';
4707 strlcat(lPath, ":auto:", maxLen); 5256 strlcat(lPath, ":auto:", maxLen);
5257 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
4708 return SQLITE_OK; 5258 return SQLITE_OK;
4709 } 5259 }
4710 5260
5261 /*
5262 ** Creates the lock file and any missing directories in lockPath
5263 */
5264 static int proxyCreateLockPath(const char *lockPath){
5265 int i, len;
5266 char buf[MAXPATHLEN];
5267 int start = 0;
5268
5269 assert(lockPath!=NULL);
5270 /* try to create all the intermediate directories */
5271 len = (int)strlen(lockPath);
5272 buf[0] = lockPath[0];
5273 for( i=1; i<len; i++ ){
5274 if( lockPath[i] == '/' && (i - start > 0) ){
5275 /* only mkdir if leaf dir != "." or "/" or ".." */
5276 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
5277 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
5278 buf[i]='\0';
5279 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
5280 int err=errno;
5281 if( err!=EEXIST ) {
5282 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
5283 "'%s' proxy lock path=%s pid=%d\n",
5284 buf, strerror(err), lockPath, getpid()));
5285 return err;
5286 }
5287 }
5288 }
5289 start=i+1;
5290 }
5291 buf[i] = lockPath[i];
5292 }
5293 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
5294 return 0;
5295 }
5296
4711 /* 5297 /*
4712 ** Create a new VFS file descriptor (stored in memory obtained from 5298 ** Create a new VFS file descriptor (stored in memory obtained from
4713 ** sqlite3_malloc) and open the file named "path" in the file descriptor. 5299 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
4714 ** 5300 **
4715 ** The caller is responsible not only for closing the file descriptor 5301 ** The caller is responsible not only for closing the file descriptor
4716 ** but also for freeing the memory associated with the file descriptor. 5302 ** but also for freeing the memory associated with the file descriptor.
4717 */ 5303 */
4718 static int proxyCreateUnixFile(const char *path, unixFile **ppFile) { 5304 static int proxyCreateUnixFile(
5305 const char *path, /* path for the new unixFile */
5306 unixFile **ppFile, /* unixFile created and returned by ref */
5307 int islockfile /* if non zero missing dirs will be created */
5308 ) {
5309 int fd = -1;
5310 int dirfd = -1;
4719 unixFile *pNew; 5311 unixFile *pNew;
4720 int flags = SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
4721 int rc = SQLITE_OK; 5312 int rc = SQLITE_OK;
5313 int openFlags = O_RDWR | O_CREAT;
4722 sqlite3_vfs dummyVfs; 5314 sqlite3_vfs dummyVfs;
4723 5315 int terrno = 0;
4724 pNew = (unixFile *)sqlite3_malloc(sizeof(unixFile)); 5316 UnixUnusedFd *pUnused = NULL;
4725 if( !pNew ){ 5317
4726 return SQLITE_NOMEM; 5318 /* 1. first try to open/create the file
5319 ** 2. if that fails, and this is a lock file (not-conch), try creating
5320 ** the parent directories and then try again.
5321 ** 3. if that fails, try to open the file read-only
5322 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
5323 */
5324 pUnused = findReusableFd(path, openFlags);
5325 if( pUnused ){
5326 fd = pUnused->fd;
5327 }else{
5328 pUnused = sqlite3_malloc(sizeof(*pUnused));
5329 if( !pUnused ){
5330 return SQLITE_NOMEM;
5331 }
5332 }
5333 if( fd<0 ){
5334 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5335 terrno = errno;
5336 if( fd<0 && errno==ENOENT && islockfile ){
5337 if( proxyCreateLockPath(path) == SQLITE_OK ){
5338 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5339 }
5340 }
5341 }
5342 if( fd<0 ){
5343 openFlags = O_RDONLY;
5344 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
5345 terrno = errno;
5346 }
5347 if( fd<0 ){
5348 if( islockfile ){
5349 return SQLITE_BUSY;
5350 }
5351 switch (terrno) {
5352 case EACCES:
5353 return SQLITE_PERM;
5354 case EIO:
5355 return SQLITE_IOERR_LOCK; /* even though it is the conch */
5356 default:
5357 return SQLITE_CANTOPEN_BKPT;
5358 }
5359 }
5360
5361 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
5362 if( pNew==NULL ){
5363 rc = SQLITE_NOMEM;
5364 goto end_create_proxy;
4727 } 5365 }
4728 memset(pNew, 0, sizeof(unixFile)); 5366 memset(pNew, 0, sizeof(unixFile));
4729 5367 pNew->openFlags = openFlags;
4730 /* Call unixOpen() to open the proxy file. The flags passed to unixOpen()
4731 ** suggest that the file being opened is a "main database". This is
4732 ** necessary as other file types do not necessarily support locking. It
4733 ** is better to use unixOpen() instead of opening the file directly with
4734 ** open(), as unixOpen() sets up the various mechanisms required to
4735 ** make sure a call to close() does not cause the system to discard
4736 ** POSIX locks prematurely.
4737 **
4738 ** It is important that the xOpen member of the VFS object passed to
4739 ** unixOpen() is NULL. This tells unixOpen() may try to open a proxy-file
4740 ** for the proxy-file (creating a potential infinite loop).
4741 */
4742 dummyVfs.pAppData = (void*)&autolockIoFinder; 5368 dummyVfs.pAppData = (void*)&autolockIoFinder;
4743 dummyVfs.xOpen = 0; 5369 pUnused->fd = fd;
4744 rc = unixOpen(&dummyVfs, path, (sqlite3_file *)pNew, flags, &flags); 5370 pUnused->flags = openFlags;
4745 if( rc==SQLITE_OK && (flags&SQLITE_OPEN_READONLY) ){ 5371 pNew->pUnused = pUnused;
4746 pNew->pMethod->xClose((sqlite3_file *)pNew); 5372
4747 rc = SQLITE_CANTOPEN; 5373 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
4748 } 5374 if( rc==SQLITE_OK ){
4749 5375 *ppFile = pNew;
4750 if( rc!=SQLITE_OK ){ 5376 return SQLITE_OK;
4751 sqlite3_free(pNew); 5377 }
4752 pNew = 0; 5378 end_create_proxy:
4753 } 5379 close(fd); /* silently leak fd if error, we're already in error */
4754 5380 sqlite3_free(pNew);
4755 *ppFile = pNew; 5381 sqlite3_free(pUnused);
4756 return rc; 5382 return rc;
4757 } 5383 }
4758 5384
4759 /* takes the conch by taking a shared lock and read the contents conch, if 5385 #ifdef SQLITE_TEST
5386 /* simulate multiple hosts by creating unique hostid file paths */
5387 int sqlite3_hostid_num = 0;
5388 #endif
5389
5390 #define PROXY_HOSTIDLEN 16 /* conch file host id length */
5391
5392 /* Not always defined in the headers as it ought to be */
5393 extern int gethostuuid(uuid_t id, const struct timespec *wait);
5394
5395 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
5396 ** bytes of writable memory.
5397 */
5398 static int proxyGetHostID(unsigned char *pHostID, int *pError){
5399 struct timespec timeout = {1, 0}; /* 1 sec timeout */
5400
5401 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
5402 memset(pHostID, 0, PROXY_HOSTIDLEN);
5403 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
5404 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
5405 if( gethostuuid(pHostID, &timeout) ){
5406 int err = errno;
5407 if( pError ){
5408 *pError = err;
5409 }
5410 return SQLITE_IOERR;
5411 }
5412 #endif
5413 #ifdef SQLITE_TEST
5414 /* simulate multiple hosts by creating unique hostid file paths */
5415 if( sqlite3_hostid_num != 0){
5416 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
5417 }
5418 #endif
5419
5420 return SQLITE_OK;
5421 }
5422
5423 /* The conch file contains the header, host id and lock file path
5424 */
5425 #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
5426 #define PROXY_HEADERLEN 1 /* conch file header length */
5427 #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
5428 #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
5429
5430 /*
5431 ** Takes an open conch file, copies the contents to a new path and then moves
5432 ** it back. The newly created file's file descriptor is assigned to the
5433 ** conch file structure and finally the original conch file descriptor is
5434 ** closed. Returns zero if successful.
5435 */
5436 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
5437 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5438 unixFile *conchFile = pCtx->conchFile;
5439 char tPath[MAXPATHLEN];
5440 char buf[PROXY_MAXCONCHLEN];
5441 char *cPath = pCtx->conchFilePath;
5442 size_t readLen = 0;
5443 size_t pathLen = 0;
5444 char errmsg[64] = "";
5445 int fd = -1;
5446 int rc = -1;
5447 UNUSED_PARAMETER(myHostID);
5448
5449 /* create a new path by replace the trailing '-conch' with '-break' */
5450 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
5451 if( pathLen>MAXPATHLEN || pathLen<6 ||
5452 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
5453 sprintf(errmsg, "path error (len %d)", (int)pathLen);
5454 goto end_breaklock;
5455 }
5456 /* read the conch content */
5457 readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
5458 if( readLen<PROXY_PATHINDEX ){
5459 sprintf(errmsg, "read error (len %d)", (int)readLen);
5460 goto end_breaklock;
5461 }
5462 /* write it out to the temporary break file */
5463 fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
5464 if( fd<0 ){
5465 sprintf(errmsg, "create failed (%d)", errno);
5466 goto end_breaklock;
5467 }
5468 if( pwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
5469 sprintf(errmsg, "write failed (%d)", errno);
5470 goto end_breaklock;
5471 }
5472 if( rename(tPath, cPath) ){
5473 sprintf(errmsg, "rename failed (%d)", errno);
5474 goto end_breaklock;
5475 }
5476 rc = 0;
5477 fprintf(stderr, "broke stale lock on %s\n", cPath);
5478 close(conchFile->h);
5479 conchFile->h = fd;
5480 conchFile->openFlags = O_RDWR | O_CREAT;
5481
5482 end_breaklock:
5483 if( rc ){
5484 if( fd>=0 ){
5485 unlink(tPath);
5486 close(fd);
5487 }
5488 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
5489 }
5490 return rc;
5491 }
5492
5493 /* Take the requested lock on the conch file and break a stale lock if the
5494 ** host id matches.
5495 */
5496 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
5497 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5498 unixFile *conchFile = pCtx->conchFile;
5499 int rc = SQLITE_OK;
5500 int nTries = 0;
5501 struct timespec conchModTime;
5502
5503 do {
5504 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5505 nTries ++;
5506 if( rc==SQLITE_BUSY ){
5507 /* If the lock failed (busy):
5508 * 1st try: get the mod time of the conch, wait 0.5s and try again.
5509 * 2nd try: fail if the mod time changed or host id is different, wait
5510 * 10 sec and try again
5511 * 3rd try: break the lock unless the mod time has changed.
5512 */
5513 struct stat buf;
5514 if( fstat(conchFile->h, &buf) ){
5515 pFile->lastErrno = errno;
5516 return SQLITE_IOERR_LOCK;
5517 }
5518
5519 if( nTries==1 ){
5520 conchModTime = buf.st_mtimespec;
5521 usleep(500000); /* wait 0.5 sec and try the lock again*/
5522 continue;
5523 }
5524
5525 assert( nTries>1 );
5526 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
5527 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
5528 return SQLITE_BUSY;
5529 }
5530
5531 if( nTries==2 ){
5532 char tBuf[PROXY_MAXCONCHLEN];
5533 int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
5534 if( len<0 ){
5535 pFile->lastErrno = errno;
5536 return SQLITE_IOERR_LOCK;
5537 }
5538 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
5539 /* don't break the lock if the host id doesn't match */
5540 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
5541 return SQLITE_BUSY;
5542 }
5543 }else{
5544 /* don't break the lock on short read or a version mismatch */
5545 return SQLITE_BUSY;
5546 }
5547 usleep(10000000); /* wait 10 sec and try the lock again */
5548 continue;
5549 }
5550
5551 assert( nTries==3 );
5552 if( 0==proxyBreakConchLock(pFile, myHostID) ){
5553 rc = SQLITE_OK;
5554 if( lockType==EXCLUSIVE_LOCK ){
5555 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
5556 }
5557 if( !rc ){
5558 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
5559 }
5560 }
5561 }
5562 } while( rc==SQLITE_BUSY && nTries<3 );
5563
5564 return rc;
5565 }
5566
5567 /* Takes the conch by taking a shared lock and read the contents conch, if
4760 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL 5568 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
4761 ** lockPath means that the lockPath in the conch file will be used if the 5569 ** lockPath means that the lockPath in the conch file will be used if the
4762 ** host IDs match, or a new lock path will be generated automatically 5570 ** host IDs match, or a new lock path will be generated automatically
4763 ** and written to the conch file. 5571 ** and written to the conch file.
4764 */ 5572 */
4765 static int proxyTakeConch(unixFile *pFile){ 5573 static int proxyTakeConch(unixFile *pFile){
4766 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 5574 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
4767 5575
4768 if( pCtx->conchHeld>0 ){ 5576 if( pCtx->conchHeld!=0 ){
4769 return SQLITE_OK; 5577 return SQLITE_OK;
4770 }else{ 5578 }else{
4771 unixFile *conchFile = pCtx->conchFile; 5579 unixFile *conchFile = pCtx->conchFile;
4772 char testValue[CONCHLEN]; 5580 uuid_t myHostID;
4773 char conchValue[CONCHLEN]; 5581 int pError = 0;
5582 char readBuf[PROXY_MAXCONCHLEN];
4774 char lockPath[MAXPATHLEN]; 5583 char lockPath[MAXPATHLEN];
4775 char *tLockPath = NULL; 5584 char *tempLockPath = NULL;
4776 int rc = SQLITE_OK; 5585 int rc = SQLITE_OK;
4777 int readRc = SQLITE_OK; 5586 int createConch = 0;
4778 int syncPerms = 0; 5587 int hostIdMatch = 0;
5588 int readLen = 0;
5589 int tryOldLockPath = 0;
5590 int forceNewLockPath = 0;
5591
5592 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
5593 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
4779 5594
4780 OSTRACE4("TAKECONCH %d for %s pid=%d\n", conchFile->h, 5595 rc = proxyGetHostID(myHostID, &pError);
4781 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()); 5596 if( (rc&0xff)==SQLITE_IOERR ){
4782 5597 pFile->lastErrno = pError;
4783 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK); 5598 goto end_takeconch;
4784 if( rc==SQLITE_OK ){
4785 int pError = 0;
4786 memset(testValue, 0, CONCHLEN); /* conch is fixed size */
4787 rc = proxyGetHostID(testValue, &pError);
4788 if( (rc&0xff)==SQLITE_IOERR ){
4789 pFile->lastErrno = pError;
4790 }
4791 if( pCtx->lockProxyPath ){
4792 strlcpy(&testValue[HOSTIDLEN], pCtx->lockProxyPath, MAXPATHLEN);
4793 }
4794 } 5599 }
5600 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
4795 if( rc!=SQLITE_OK ){ 5601 if( rc!=SQLITE_OK ){
4796 goto end_takeconch; 5602 goto end_takeconch;
4797 } 5603 }
4798 5604 /* read the existing conch file */
4799 readRc = unixRead((sqlite3_file *)conchFile, conchValue, CONCHLEN, 0); 5605 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
4800 if( readRc!=SQLITE_IOERR_SHORT_READ ){ 5606 if( readLen<0 ){
4801 if( readRc!=SQLITE_OK ){ 5607 /* I/O error: lastErrno set by seekAndRead */
4802 if( (rc&0xff)==SQLITE_IOERR ){ 5608 pFile->lastErrno = conchFile->lastErrno;
4803 pFile->lastErrno = conchFile->lastErrno; 5609 rc = SQLITE_IOERR_READ;
4804 } 5610 goto end_takeconch;
4805 rc = readRc; 5611 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
5612 readBuf[0]!=(char)PROXY_CONCHVERSION ){
5613 /* a short read or version format mismatch means we need to create a new
5614 ** conch file.
5615 */
5616 createConch = 1;
5617 }
5618 /* if the host id matches and the lock path already exists in the conch
5619 ** we'll try to use the path there, if we can't open that path, we'll
5620 ** retry with a new auto-generated path
5621 */
5622 do { /* in case we need to try again for an :auto: named lock file */
5623
5624 if( !createConch && !forceNewLockPath ){
5625 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
5626 PROXY_HOSTIDLEN);
5627 /* if the conch has data compare the contents */
5628 if( !pCtx->lockProxyPath ){
5629 /* for auto-named local lock file, just check the host ID and we'll
5630 ** use the local lock file path that's already in there
5631 */
5632 if( hostIdMatch ){
5633 size_t pathLen = (readLen - PROXY_PATHINDEX);
5634
5635 if( pathLen>=MAXPATHLEN ){
5636 pathLen=MAXPATHLEN-1;
5637 }
5638 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
5639 lockPath[pathLen] = 0;
5640 tempLockPath = lockPath;
5641 tryOldLockPath = 1;
5642 /* create a copy of the lock path if the conch is taken */
5643 goto end_takeconch;
5644 }
5645 }else if( hostIdMatch
5646 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
5647 readLen-PROXY_PATHINDEX)
5648 ){
5649 /* conch host and lock path match */
5650 goto end_takeconch;
5651 }
5652 }
5653
5654 /* if the conch isn't writable and doesn't match, we can't take it */
5655 if( (conchFile->openFlags&O_RDWR) == 0 ){
5656 rc = SQLITE_BUSY;
4806 goto end_takeconch; 5657 goto end_takeconch;
4807 } 5658 }
4808 /* if the conch has data compare the contents */ 5659
5660 /* either the conch didn't match or we need to create a new one */
4809 if( !pCtx->lockProxyPath ){ 5661 if( !pCtx->lockProxyPath ){
4810 /* for auto-named local lock file, just check the host ID and we'll 5662 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
4811 ** use the local lock file path that's already in there */ 5663 tempLockPath = lockPath;
4812 if( !memcmp(testValue, conchValue, HOSTIDLEN) ){ 5664 /* create a copy of the lock path _only_ if the conch is taken */
4813 tLockPath = (char *)&conchValue[HOSTIDLEN]; 5665 }
4814 goto end_takeconch; 5666
5667 /* update conch with host and path (this will fail if other process
5668 ** has a shared lock already), if the host id matches, use the big
5669 ** stick.
5670 */
5671 futimes(conchFile->h, NULL);
5672 if( hostIdMatch && !createConch ){
5673 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
5674 /* We are trying for an exclusive lock but another thread in this
5675 ** same process is still holding a shared lock. */
5676 rc = SQLITE_BUSY;
5677 } else {
5678 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
4815 } 5679 }
4816 }else{ 5680 }else{
4817 /* we've got the conch if conchValue matches our path and host ID */ 5681 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK) ;
4818 if( !memcmp(testValue, conchValue, CONCHLEN) ){ 5682 }
4819 goto end_takeconch; 5683 if( rc==SQLITE_OK ){
4820 } 5684 char writeBuffer[PROXY_MAXCONCHLEN];
4821 } 5685 int writeSize = 0;
4822 }else{ 5686
4823 /* a short read means we're "creating" the conch (even though it could 5687 writeBuffer[0] = (char)PROXY_CONCHVERSION;
4824 ** have been user-intervention), if we acquire the exclusive lock, 5688 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
4825 ** we'll try to match the current on-disk permissions of the database 5689 if( pCtx->lockProxyPath!=NULL ){
4826 */ 5690 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN );
4827 syncPerms = 1; 5691 }else{
4828 } 5692 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
4829 5693 }
4830 /* either conch was emtpy or didn't match */ 5694 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
4831 if( !pCtx->lockProxyPath ){ 5695 ftruncate(conchFile->h, writeSize);
4832 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN); 5696 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
4833 tLockPath = lockPath; 5697 fsync(conchFile->h);
4834 strlcpy(&testValue[HOSTIDLEN], lockPath, MAXPATHLEN); 5698 /* If we created a new conch file (not just updated the contents of a
4835 } 5699 ** valid conch file), try to match the permissions of the database
4836 5700 */
4837 /* update conch with host and path (this will fail if other process 5701 if( rc==SQLITE_OK && createConch ){
4838 ** has a shared lock already) */ 5702 struct stat buf;
4839 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK); 5703 int err = fstat(pFile->h, &buf);
4840 if( rc==SQLITE_OK ){ 5704 if( err==0 ){
4841 rc = unixWrite((sqlite3_file *)conchFile, testValue, CONCHLEN, 0); 5705 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
4842 if( rc==SQLITE_OK && syncPerms ){ 5706 S_IROTH|S_IWOTH);
4843 struct stat buf; 5707 /* try to match the database file R/W permissions, ignore failure */
4844 int err = fstat(pFile->h, &buf);
4845 if( err==0 ){
4846 /* try to match the database file permissions, ignore failure */
4847 #ifndef SQLITE_PROXY_DEBUG 5708 #ifndef SQLITE_PROXY_DEBUG
4848 fchmod(conchFile->h, buf.st_mode); 5709 fchmod(conchFile->h, cmode);
4849 #else 5710 #else
4850 if( fchmod(conchFile->h, buf.st_mode)!=0 ){ 5711 if( fchmod(conchFile->h, cmode)!=0 ){
5712 int code = errno;
5713 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
5714 cmode, code, strerror(code));
5715 } else {
5716 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
5717 }
5718 }else{
4851 int code = errno; 5719 int code = errno;
4852 fprintf(stderr, "fchmod %o FAILED with %d %s\n", 5720 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
4853 buf.st_mode, code, strerror(code)); 5721 err, code, strerror(code));
4854 } else { 5722 #endif
4855 fprintf(stderr, "fchmod %o SUCCEDED\n",buf.st_mode); 5723 }
4856 } 5724 }
5725 }
5726 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
5727
5728 end_takeconch:
5729 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
5730 if( rc==SQLITE_OK && pFile->openFlags ){
5731 if( pFile->h>=0 ){
5732 #ifdef STRICT_CLOSE_ERROR
5733 if( close(pFile->h) ){
5734 pFile->lastErrno = errno;
5735 return SQLITE_IOERR_CLOSE;
5736 }
5737 #else
5738 close(pFile->h); /* silently leak fd if fail */
5739 #endif
5740 }
5741 pFile->h = -1;
5742 int fd = open(pCtx->dbPath, pFile->openFlags,
5743 SQLITE_DEFAULT_FILE_PERMISSIONS);
5744 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
5745 if( fd>=0 ){
5746 pFile->h = fd;
4857 }else{ 5747 }else{
4858 int code = errno; 5748 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
4859 fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 5749 during locking */
4860 err, code, strerror(code)); 5750 }
4861 #endif 5751 }
4862 } 5752 if( rc==SQLITE_OK && !pCtx->lockProxy ){
4863 } 5753 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
4864 } 5754 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
4865 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK); 5755 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
4866 5756 /* we couldn't create the proxy lock file with the old lock file path
4867 end_takeconch: 5757 ** so try again via auto-naming
4868 OSTRACE2("TRANSPROXY: CLOSE %d\n", pFile->h); 5758 */
4869 if( rc==SQLITE_OK && pFile->openFlags ){ 5759 forceNewLockPath = 1;
4870 if( pFile->h>=0 ){ 5760 tryOldLockPath = 0;
4871 #ifdef STRICT_CLOSE_ERROR 5761 continue; /* go back to the do {} while start point, try again */
4872 if( close(pFile->h) ){ 5762 }
4873 pFile->lastErrno = errno; 5763 }
4874 return SQLITE_IOERR_CLOSE; 5764 if( rc==SQLITE_OK ){
4875 } 5765 /* Need to make a copy of path if we extracted the value
4876 #else 5766 ** from the conch file or the path was allocated on the stack
4877 close(pFile->h); /* silently leak fd if fail */ 5767 */
4878 #endif 5768 if( tempLockPath ){
4879 } 5769 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
4880 pFile->h = -1; 5770 if( !pCtx->lockProxyPath ){
4881 int fd = open(pCtx->dbPath, pFile->openFlags, 5771 rc = SQLITE_NOMEM;
4882 SQLITE_DEFAULT_FILE_PERMISSIONS); 5772 }
4883 OSTRACE2("TRANSPROXY: OPEN %d\n", fd); 5773 }
4884 if( fd>=0 ){ 5774 }
4885 pFile->h = fd; 5775 if( rc==SQLITE_OK ){
4886 }else{ 5776 pCtx->conchHeld = 1;
4887 rc=SQLITE_CANTOPEN; /* SQLITE_BUSY? proxyTakeConch called 5777
4888 during locking */
4889 }
4890 }
4891 if( rc==SQLITE_OK && !pCtx->lockProxy ){
4892 char *path = tLockPath ? tLockPath : pCtx->lockProxyPath;
4893 /* ACS: Need to make a copy of path sometimes */
4894 rc = proxyCreateUnixFile(path, &pCtx->lockProxy);
4895 }
4896 if( rc==SQLITE_OK ){
4897 pCtx->conchHeld = 1;
4898
4899 if( tLockPath ){
4900 pCtx->lockProxyPath = sqlite3DbStrDup(0, tLockPath);
4901 if( pCtx->lockProxy->pMethod == &afpIoMethods ){ 5778 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
4902 ((afpLockingContext *)pCtx->lockProxy->lockingContext)->dbPath = 5779 afpLockingContext *afpCtx;
4903 pCtx->lockProxyPath; 5780 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
4904 } 5781 afpCtx->dbPath = pCtx->lockProxyPath;
4905 } 5782 }
4906 } else { 5783 } else {
4907 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK); 5784 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
4908 } 5785 }
4909 OSTRACE3("TAKECONCH %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed"); 5786 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
4910 return rc; 5787 rc==SQLITE_OK?"ok":"failed"));
5788 return rc;
5789 } while (1); /* in case we need to retry the :auto: lock file -
5790 ** we should never get here except via the 'continue' call. */
4911 } 5791 }
4912 } 5792 }
4913 5793
4914 /* 5794 /*
4915 ** If pFile holds a lock on a conch file, then release that lock. 5795 ** If pFile holds a lock on a conch file, then release that lock.
4916 */ 5796 */
4917 static int proxyReleaseConch(unixFile *pFile){ 5797 static int proxyReleaseConch(unixFile *pFile){
4918 int rc; /* Subroutine return code */ 5798 int rc = SQLITE_OK; /* Subroutine return code */
4919 proxyLockingContext *pCtx; /* The locking context for the proxy lock */ 5799 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
4920 unixFile *conchFile; /* Name of the conch file */ 5800 unixFile *conchFile; /* Name of the conch file */
4921 5801
4922 pCtx = (proxyLockingContext *)pFile->lockingContext; 5802 pCtx = (proxyLockingContext *)pFile->lockingContext;
4923 conchFile = pCtx->conchFile; 5803 conchFile = pCtx->conchFile;
4924 OSTRACE4("RELEASECONCH %d for %s pid=%d\n", conchFile->h, 5804 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
4925 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 5805 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
4926 getpid()); 5806 getpid()));
5807 if( pCtx->conchHeld>0 ){
5808 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
5809 }
4927 pCtx->conchHeld = 0; 5810 pCtx->conchHeld = 0;
4928 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK); 5811 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
4929 OSTRACE3("RELEASECONCH %d %s\n", conchFile->h, 5812 (rc==SQLITE_OK ? "ok" : "failed")));
4930 (rc==SQLITE_OK ? "ok" : "failed"));
4931 return rc; 5813 return rc;
4932 } 5814 }
4933 5815
4934 /* 5816 /*
4935 ** Given the name of a database file, compute the name of its conch file. 5817 ** Given the name of a database file, compute the name of its conch file.
4936 ** Store the conch filename in memory obtained from sqlite3_malloc(). 5818 ** Store the conch filename in memory obtained from sqlite3_malloc().
4937 ** Make *pConchPath point to the new name. Return SQLITE_OK on success 5819 ** Make *pConchPath point to the new name. Return SQLITE_OK on success
4938 ** or SQLITE_NOMEM if unable to obtain memory. 5820 ** or SQLITE_NOMEM if unable to obtain memory.
4939 ** 5821 **
4940 ** The caller is responsible for ensuring that the allocated memory 5822 ** The caller is responsible for ensuring that the allocated memory
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after
4977 5859
4978 5860
4979 /* Takes a fully configured proxy locking-style unix file and switches 5861 /* Takes a fully configured proxy locking-style unix file and switches
4980 ** the local lock file path 5862 ** the local lock file path
4981 */ 5863 */
4982 static int switchLockProxyPath(unixFile *pFile, const char *path) { 5864 static int switchLockProxyPath(unixFile *pFile, const char *path) {
4983 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext; 5865 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
4984 char *oldPath = pCtx->lockProxyPath; 5866 char *oldPath = pCtx->lockProxyPath;
4985 int rc = SQLITE_OK; 5867 int rc = SQLITE_OK;
4986 5868
4987 if( pFile->locktype!=NO_LOCK ){ 5869 if( pFile->eFileLock!=NO_LOCK ){
4988 return SQLITE_BUSY; 5870 return SQLITE_BUSY;
4989 } 5871 }
4990 5872
4991 /* nothing to do if the path is NULL, :auto: or matches the existing path */ 5873 /* nothing to do if the path is NULL, :auto: or matches the existing path */
4992 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") || 5874 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
4993 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){ 5875 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
4994 return SQLITE_OK; 5876 return SQLITE_OK;
4995 }else{ 5877 }else{
4996 unixFile *lockProxy = pCtx->lockProxy; 5878 unixFile *lockProxy = pCtx->lockProxy;
4997 pCtx->lockProxy=NULL; 5879 pCtx->lockProxy=NULL;
(...skipping 16 matching lines...) Expand all
5014 ** 5896 **
5015 ** This routine find the filename associated with pFile and writes it 5897 ** This routine find the filename associated with pFile and writes it
5016 ** int dbPath. 5898 ** int dbPath.
5017 */ 5899 */
5018 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){ 5900 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
5019 #if defined(__APPLE__) 5901 #if defined(__APPLE__)
5020 if( pFile->pMethod == &afpIoMethods ){ 5902 if( pFile->pMethod == &afpIoMethods ){
5021 /* afp style keeps a reference to the db path in the filePath field 5903 /* afp style keeps a reference to the db path in the filePath field
5022 ** of the struct */ 5904 ** of the struct */
5023 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN ); 5905 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
5024 strcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath); 5906 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPAT HLEN);
5025 }else 5907 } else
5026 #endif 5908 #endif
5027 if( pFile->pMethod == &dotlockIoMethods ){ 5909 if( pFile->pMethod == &dotlockIoMethods ){
5028 /* dot lock style uses the locking context to store the dot lock 5910 /* dot lock style uses the locking context to store the dot lock
5029 ** file path */ 5911 ** file path */
5030 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX); 5912 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
5031 memcpy(dbPath, (char *)pFile->lockingContext, len + 1); 5913 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
5032 }else{ 5914 }else{
5033 /* all other styles use the locking context to store the db file path */ 5915 /* all other styles use the locking context to store the db file path */
5034 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN ); 5916 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
5035 strcpy(dbPath, (char *)pFile->lockingContext); 5917 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
5036 } 5918 }
5037 return SQLITE_OK; 5919 return SQLITE_OK;
5038 } 5920 }
5039 5921
5040 /* 5922 /*
5041 ** Takes an already filled in unix file and alters it so all file locking 5923 ** Takes an already filled in unix file and alters it so all file locking
5042 ** will be performed on the local proxy lock file. The following fields 5924 ** will be performed on the local proxy lock file. The following fields
5043 ** are preserved in the locking context so that they can be restored and 5925 ** are preserved in the locking context so that they can be restored and
5044 ** the unix structure properly cleaned up at close time: 5926 ** the unix structure properly cleaned up at close time:
5045 ** ->lockingContext 5927 ** ->lockingContext
5046 ** ->pMethod 5928 ** ->pMethod
5047 */ 5929 */
5048 static int proxyTransformUnixFile(unixFile *pFile, const char *path) { 5930 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
5049 proxyLockingContext *pCtx; 5931 proxyLockingContext *pCtx;
5050 char dbPath[MAXPATHLEN+1]; /* Name of the database file */ 5932 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
5051 char *lockPath=NULL; 5933 char *lockPath=NULL;
5052 int rc = SQLITE_OK; 5934 int rc = SQLITE_OK;
5053 5935
5054 if( pFile->locktype!=NO_LOCK ){ 5936 if( pFile->eFileLock!=NO_LOCK ){
5055 return SQLITE_BUSY; 5937 return SQLITE_BUSY;
5056 } 5938 }
5057 proxyGetDbPathForUnixFile(pFile, dbPath); 5939 proxyGetDbPathForUnixFile(pFile, dbPath);
5058 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){ 5940 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
5059 lockPath=NULL; 5941 lockPath=NULL;
5060 }else{ 5942 }else{
5061 lockPath=(char *)path; 5943 lockPath=(char *)path;
5062 } 5944 }
5063 5945
5064 OSTRACE4("TRANSPROXY %d for %s pid=%d\n", pFile->h, 5946 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
5065 (lockPath ? lockPath : ":auto:"), getpid()); 5947 (lockPath ? lockPath : ":auto:"), getpid()));
5066 5948
5067 pCtx = sqlite3_malloc( sizeof(*pCtx) ); 5949 pCtx = sqlite3_malloc( sizeof(*pCtx) );
5068 if( pCtx==0 ){ 5950 if( pCtx==0 ){
5069 return SQLITE_NOMEM; 5951 return SQLITE_NOMEM;
5070 } 5952 }
5071 memset(pCtx, 0, sizeof(*pCtx)); 5953 memset(pCtx, 0, sizeof(*pCtx));
5072 5954
5073 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath); 5955 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
5074 if( rc==SQLITE_OK ){ 5956 if( rc==SQLITE_OK ){
5075 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile); 5957 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
5958 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
5959 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
5960 ** (c) the file system is read-only, then enable no-locking access.
5961 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
5962 ** that openFlags will have only one of O_RDONLY or O_RDWR.
5963 */
5964 struct statfs fsInfo;
5965 struct stat conchInfo;
5966 int goLockless = 0;
5967
5968 if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
5969 int err = errno;
5970 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
5971 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
5972 }
5973 }
5974 if( goLockless ){
5975 pCtx->conchHeld = -1; /* read only FS/ lockless */
5976 rc = SQLITE_OK;
5977 }
5978 }
5076 } 5979 }
5077 if( rc==SQLITE_OK && lockPath ){ 5980 if( rc==SQLITE_OK && lockPath ){
5078 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath); 5981 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
5079 } 5982 }
5080 5983
5081 if( rc==SQLITE_OK ){ 5984 if( rc==SQLITE_OK ){
5985 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
5986 if( pCtx->dbPath==NULL ){
5987 rc = SQLITE_NOMEM;
5988 }
5989 }
5990 if( rc==SQLITE_OK ){
5082 /* all memory is allocated, proxys are created and assigned, 5991 /* all memory is allocated, proxys are created and assigned,
5083 ** switch the locking context and pMethod then return. 5992 ** switch the locking context and pMethod then return.
5084 */ 5993 */
5085 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
5086 pCtx->oldLockingContext = pFile->lockingContext; 5994 pCtx->oldLockingContext = pFile->lockingContext;
5087 pFile->lockingContext = pCtx; 5995 pFile->lockingContext = pCtx;
5088 pCtx->pOldMethod = pFile->pMethod; 5996 pCtx->pOldMethod = pFile->pMethod;
5089 pFile->pMethod = &proxyIoMethods; 5997 pFile->pMethod = &proxyIoMethods;
5090 }else{ 5998 }else{
5091 if( pCtx->conchFile ){ 5999 if( pCtx->conchFile ){
5092 rc = pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile); 6000 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
5093 if( rc ) return rc;
5094 sqlite3_free(pCtx->conchFile); 6001 sqlite3_free(pCtx->conchFile);
5095 } 6002 }
6003 sqlite3DbFree(0, pCtx->lockProxyPath);
5096 sqlite3_free(pCtx->conchFilePath); 6004 sqlite3_free(pCtx->conchFilePath);
5097 sqlite3_free(pCtx); 6005 sqlite3_free(pCtx);
5098 } 6006 }
5099 OSTRACE3("TRANSPROXY %d %s\n", pFile->h, 6007 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
5100 (rc==SQLITE_OK ? "ok" : "failed")); 6008 (rc==SQLITE_OK ? "ok" : "failed")));
5101 return rc; 6009 return rc;
5102 } 6010 }
5103 6011
5104 6012
5105 /* 6013 /*
5106 ** This routine handles sqlite3_file_control() calls that are specific 6014 ** This routine handles sqlite3_file_control() calls that are specific
5107 ** to proxy locking. 6015 ** to proxy locking.
5108 */ 6016 */
5109 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){ 6017 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
5110 switch( op ){ 6018 switch( op ){
(...skipping 63 matching lines...) Expand 10 before | Expand all | Expand 10 after
5174 ** This routine checks if there is a RESERVED lock held on the specified 6082 ** This routine checks if there is a RESERVED lock held on the specified
5175 ** file by this or any other process. If such a lock is held, set *pResOut 6083 ** file by this or any other process. If such a lock is held, set *pResOut
5176 ** to a non-zero value otherwise *pResOut is set to zero. The return value 6084 ** to a non-zero value otherwise *pResOut is set to zero. The return value
5177 ** is set to SQLITE_OK unless an I/O error occurs during lock checking. 6085 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
5178 */ 6086 */
5179 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) { 6087 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
5180 unixFile *pFile = (unixFile*)id; 6088 unixFile *pFile = (unixFile*)id;
5181 int rc = proxyTakeConch(pFile); 6089 int rc = proxyTakeConch(pFile);
5182 if( rc==SQLITE_OK ){ 6090 if( rc==SQLITE_OK ){
5183 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 6091 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5184 unixFile *proxy = pCtx->lockProxy; 6092 if( pCtx->conchHeld>0 ){
5185 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut); 6093 unixFile *proxy = pCtx->lockProxy;
6094 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
6095 }else{ /* conchHeld < 0 is lockless */
6096 pResOut=0;
6097 }
5186 } 6098 }
5187 return rc; 6099 return rc;
5188 } 6100 }
5189 6101
5190 /* 6102 /*
5191 ** Lock the file with the lock specified by parameter locktype - one 6103 ** Lock the file with the lock specified by parameter eFileLock - one
5192 ** of the following: 6104 ** of the following:
5193 ** 6105 **
5194 ** (1) SHARED_LOCK 6106 ** (1) SHARED_LOCK
5195 ** (2) RESERVED_LOCK 6107 ** (2) RESERVED_LOCK
5196 ** (3) PENDING_LOCK 6108 ** (3) PENDING_LOCK
5197 ** (4) EXCLUSIVE_LOCK 6109 ** (4) EXCLUSIVE_LOCK
5198 ** 6110 **
5199 ** Sometimes when requesting one lock state, additional lock states 6111 ** Sometimes when requesting one lock state, additional lock states
5200 ** are inserted in between. The locking might fail on one of the later 6112 ** are inserted in between. The locking might fail on one of the later
5201 ** transitions leaving the lock state different from what it started but 6113 ** transitions leaving the lock state different from what it started but
5202 ** still short of its goal. The following chart shows the allowed 6114 ** still short of its goal. The following chart shows the allowed
5203 ** transitions and the inserted intermediate states: 6115 ** transitions and the inserted intermediate states:
5204 ** 6116 **
5205 ** UNLOCKED -> SHARED 6117 ** UNLOCKED -> SHARED
5206 ** SHARED -> RESERVED 6118 ** SHARED -> RESERVED
5207 ** SHARED -> (PENDING) -> EXCLUSIVE 6119 ** SHARED -> (PENDING) -> EXCLUSIVE
5208 ** RESERVED -> (PENDING) -> EXCLUSIVE 6120 ** RESERVED -> (PENDING) -> EXCLUSIVE
5209 ** PENDING -> EXCLUSIVE 6121 ** PENDING -> EXCLUSIVE
5210 ** 6122 **
5211 ** This routine will only increase a lock. Use the sqlite3OsUnlock() 6123 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
5212 ** routine to lower a locking level. 6124 ** routine to lower a locking level.
5213 */ 6125 */
5214 static int proxyLock(sqlite3_file *id, int locktype) { 6126 static int proxyLock(sqlite3_file *id, int eFileLock) {
5215 unixFile *pFile = (unixFile*)id; 6127 unixFile *pFile = (unixFile*)id;
5216 int rc = proxyTakeConch(pFile); 6128 int rc = proxyTakeConch(pFile);
5217 if( rc==SQLITE_OK ){ 6129 if( rc==SQLITE_OK ){
5218 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 6130 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5219 unixFile *proxy = pCtx->lockProxy; 6131 if( pCtx->conchHeld>0 ){
5220 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype); 6132 unixFile *proxy = pCtx->lockProxy;
5221 pFile->locktype = proxy->locktype; 6133 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
6134 pFile->eFileLock = proxy->eFileLock;
6135 }else{
6136 /* conchHeld < 0 is lockless */
6137 }
5222 } 6138 }
5223 return rc; 6139 return rc;
5224 } 6140 }
5225 6141
5226 6142
5227 /* 6143 /*
5228 ** Lower the locking level on file descriptor pFile to locktype. locktype 6144 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
5229 ** must be either NO_LOCK or SHARED_LOCK. 6145 ** must be either NO_LOCK or SHARED_LOCK.
5230 ** 6146 **
5231 ** If the locking level of the file descriptor is already at or below 6147 ** If the locking level of the file descriptor is already at or below
5232 ** the requested locking level, this routine is a no-op. 6148 ** the requested locking level, this routine is a no-op.
5233 */ 6149 */
5234 static int proxyUnlock(sqlite3_file *id, int locktype) { 6150 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
5235 unixFile *pFile = (unixFile*)id; 6151 unixFile *pFile = (unixFile*)id;
5236 int rc = proxyTakeConch(pFile); 6152 int rc = proxyTakeConch(pFile);
5237 if( rc==SQLITE_OK ){ 6153 if( rc==SQLITE_OK ){
5238 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 6154 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
5239 unixFile *proxy = pCtx->lockProxy; 6155 if( pCtx->conchHeld>0 ){
5240 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype); 6156 unixFile *proxy = pCtx->lockProxy;
5241 pFile->locktype = proxy->locktype; 6157 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
6158 pFile->eFileLock = proxy->eFileLock;
6159 }else{
6160 /* conchHeld < 0 is lockless */
6161 }
5242 } 6162 }
5243 return rc; 6163 return rc;
5244 } 6164 }
5245 6165
5246 /* 6166 /*
5247 ** Close a file that uses proxy locks. 6167 ** Close a file that uses proxy locks.
5248 */ 6168 */
5249 static int proxyClose(sqlite3_file *id) { 6169 static int proxyClose(sqlite3_file *id) {
5250 if( id ){ 6170 if( id ){
5251 unixFile *pFile = (unixFile*)id; 6171 unixFile *pFile = (unixFile*)id;
(...skipping 12 matching lines...) Expand all
5264 } 6184 }
5265 if( conchFile ){ 6185 if( conchFile ){
5266 if( pCtx->conchHeld ){ 6186 if( pCtx->conchHeld ){
5267 rc = proxyReleaseConch(pFile); 6187 rc = proxyReleaseConch(pFile);
5268 if( rc ) return rc; 6188 if( rc ) return rc;
5269 } 6189 }
5270 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile); 6190 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
5271 if( rc ) return rc; 6191 if( rc ) return rc;
5272 sqlite3_free(conchFile); 6192 sqlite3_free(conchFile);
5273 } 6193 }
5274 sqlite3_free(pCtx->lockProxyPath); 6194 sqlite3DbFree(0, pCtx->lockProxyPath);
5275 sqlite3_free(pCtx->conchFilePath); 6195 sqlite3_free(pCtx->conchFilePath);
5276 sqlite3_free(pCtx->dbPath); 6196 sqlite3DbFree(0, pCtx->dbPath);
5277 /* restore the original locking context and pMethod then close it */ 6197 /* restore the original locking context and pMethod then close it */
5278 pFile->lockingContext = pCtx->oldLockingContext; 6198 pFile->lockingContext = pCtx->oldLockingContext;
5279 pFile->pMethod = pCtx->pOldMethod; 6199 pFile->pMethod = pCtx->pOldMethod;
5280 sqlite3_free(pCtx); 6200 sqlite3_free(pCtx);
5281 return pFile->pMethod->xClose(id); 6201 return pFile->pMethod->xClose(id);
5282 } 6202 }
5283 return SQLITE_OK; 6203 return SQLITE_OK;
5284 } 6204 }
5285 6205
5286 6206
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after
5323 ** behaviors. See the division above that contains the IOMETHODS 6243 ** behaviors. See the division above that contains the IOMETHODS
5324 ** macro for addition information on finder-functions. 6244 ** macro for addition information on finder-functions.
5325 ** 6245 **
5326 ** Most finders simply return a pointer to a fixed sqlite3_io_methods 6246 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
5327 ** object. But the "autolockIoFinder" available on MacOSX does a little 6247 ** object. But the "autolockIoFinder" available on MacOSX does a little
5328 ** more than that; it looks at the filesystem type that hosts the 6248 ** more than that; it looks at the filesystem type that hosts the
5329 ** database file and tries to choose an locking method appropriate for 6249 ** database file and tries to choose an locking method appropriate for
5330 ** that filesystem time. 6250 ** that filesystem time.
5331 */ 6251 */
5332 #define UNIXVFS(VFSNAME, FINDER) { \ 6252 #define UNIXVFS(VFSNAME, FINDER) { \
5333 1, /* iVersion */ \ 6253 2, /* iVersion */ \
5334 sizeof(unixFile), /* szOsFile */ \ 6254 sizeof(unixFile), /* szOsFile */ \
5335 MAX_PATHNAME, /* mxPathname */ \ 6255 MAX_PATHNAME, /* mxPathname */ \
5336 0, /* pNext */ \ 6256 0, /* pNext */ \
5337 VFSNAME, /* zName */ \ 6257 VFSNAME, /* zName */ \
5338 (void*)&FINDER, /* pAppData */ \ 6258 (void*)&FINDER, /* pAppData */ \
5339 unixOpen, /* xOpen */ \ 6259 unixOpen, /* xOpen */ \
5340 unixDelete, /* xDelete */ \ 6260 unixDelete, /* xDelete */ \
5341 unixAccess, /* xAccess */ \ 6261 unixAccess, /* xAccess */ \
5342 unixFullPathname, /* xFullPathname */ \ 6262 unixFullPathname, /* xFullPathname */ \
5343 unixDlOpen, /* xDlOpen */ \ 6263 unixDlOpen, /* xDlOpen */ \
5344 unixDlError, /* xDlError */ \ 6264 unixDlError, /* xDlError */ \
5345 unixDlSym, /* xDlSym */ \ 6265 unixDlSym, /* xDlSym */ \
5346 unixDlClose, /* xDlClose */ \ 6266 unixDlClose, /* xDlClose */ \
5347 unixRandomness, /* xRandomness */ \ 6267 unixRandomness, /* xRandomness */ \
5348 unixSleep, /* xSleep */ \ 6268 unixSleep, /* xSleep */ \
5349 unixCurrentTime, /* xCurrentTime */ \ 6269 unixCurrentTime, /* xCurrentTime */ \
5350 unixGetLastError /* xGetLastError */ \ 6270 unixGetLastError, /* xGetLastError */ \
6271 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
5351 } 6272 }
5352 6273
5353 /* 6274 /*
5354 ** All default VFSes for unix are contained in the following array. 6275 ** All default VFSes for unix are contained in the following array.
5355 ** 6276 **
5356 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified 6277 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
5357 ** by the SQLite core when the VFS is registered. So the following 6278 ** by the SQLite core when the VFS is registered. So the following
5358 ** array cannot be const. 6279 ** array cannot be const.
5359 */ 6280 */
5360 static sqlite3_vfs aVfs[] = { 6281 static sqlite3_vfs aVfs[] = {
5361 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__)) 6282 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
5362 UNIXVFS("unix", autolockIoFinder ), 6283 UNIXVFS("unix", autolockIoFinder ),
5363 #else 6284 #else
5364 UNIXVFS("unix", posixIoFinder ), 6285 UNIXVFS("unix", posixIoFinder ),
5365 #endif 6286 #endif
5366 UNIXVFS("unix-none", nolockIoFinder ), 6287 UNIXVFS("unix-none", nolockIoFinder ),
5367 UNIXVFS("unix-dotfile", dotlockIoFinder ), 6288 UNIXVFS("unix-dotfile", dotlockIoFinder ),
5368 UNIXVFS("unix-wfl", posixWflIoFinder ),
5369 #if OS_VXWORKS 6289 #if OS_VXWORKS
5370 UNIXVFS("unix-namedsem", semIoFinder ), 6290 UNIXVFS("unix-namedsem", semIoFinder ),
5371 #endif 6291 #endif
5372 #if SQLITE_ENABLE_LOCKING_STYLE 6292 #if SQLITE_ENABLE_LOCKING_STYLE
5373 UNIXVFS("unix-posix", posixIoFinder ), 6293 UNIXVFS("unix-posix", posixIoFinder ),
5374 #if !OS_VXWORKS 6294 #if !OS_VXWORKS
5375 UNIXVFS("unix-flock", flockIoFinder ), 6295 UNIXVFS("unix-flock", flockIoFinder ),
5376 #endif 6296 #endif
5377 #endif 6297 #endif
5378 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) 6298 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
5379 UNIXVFS("unix-afp", afpIoFinder ), 6299 UNIXVFS("unix-afp", afpIoFinder ),
6300 UNIXVFS("unix-nfs", nfsIoFinder ),
5380 UNIXVFS("unix-proxy", proxyIoFinder ), 6301 UNIXVFS("unix-proxy", proxyIoFinder ),
5381 #endif 6302 #endif
5382 }; 6303 };
5383 unsigned int i; /* Loop counter */ 6304 unsigned int i; /* Loop counter */
5384 6305
5385 /* Register all VFSes defined in the aVfs[] array */ 6306 /* Register all VFSes defined in the aVfs[] array */
5386 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){ 6307 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
5387 sqlite3_vfs_register(&aVfs[i], i==0); 6308 sqlite3_vfs_register(&aVfs[i], i==0);
5388 } 6309 }
5389 return SQLITE_OK; 6310 return SQLITE_OK;
5390 } 6311 }
5391 6312
5392 /* 6313 /*
5393 ** Shutdown the operating system interface. 6314 ** Shutdown the operating system interface.
5394 ** 6315 **
5395 ** Some operating systems might need to do some cleanup in this routine, 6316 ** Some operating systems might need to do some cleanup in this routine,
5396 ** to release dynamically allocated objects. But not on unix. 6317 ** to release dynamically allocated objects. But not on unix.
5397 ** This routine is a no-op for unix. 6318 ** This routine is a no-op for unix.
5398 */ 6319 */
5399 int sqlite3_os_end(void){ 6320 int sqlite3_os_end(void){
5400 return SQLITE_OK; 6321 return SQLITE_OK;
5401 } 6322 }
5402 6323
5403 #endif /* SQLITE_OS_UNIX */ 6324 #endif /* SQLITE_OS_UNIX */
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698