extensions/sqlite/sqlite-source/os_unix.c
author Asher Baker <asherkin@gmail.com>
Thu Apr 26 16:58:18 2012 +0100 (2012-04-26)
changeset 3488 bee90c8ef6c3
parent 1952 b7aa2b626807
permissions -rw-r--r--
Fixed client serials not being unique on Windows (bug 5285, r=psychonic).
ds@1952
     1
/*
ds@1952
     2
** 2004 May 22
ds@1952
     3
**
ds@1952
     4
** The author disclaims copyright to this source code.  In place of
ds@1952
     5
** a legal notice, here is a blessing:
ds@1952
     6
**
ds@1952
     7
**    May you do good and not evil.
ds@1952
     8
**    May you find forgiveness for yourself and forgive others.
ds@1952
     9
**    May you share freely, never taking more than you give.
ds@1952
    10
**
ds@1952
    11
******************************************************************************
ds@1952
    12
**
ds@1952
    13
** This file contains code that is specific to Unix systems.
ds@1952
    14
*/
ds@1952
    15
#include "sqliteInt.h"
ds@1952
    16
#if OS_UNIX              /* This file is used on unix only */
ds@1952
    17
ds@1952
    18
/* #define SQLITE_ENABLE_LOCKING_STYLE 0 */
ds@1952
    19
ds@1952
    20
/*
ds@1952
    21
** These #defines should enable >2GB file support on Posix if the
ds@1952
    22
** underlying operating system supports it.  If the OS lacks
ds@1952
    23
** large file support, these should be no-ops.
ds@1952
    24
**
ds@1952
    25
** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
ds@1952
    26
** on the compiler command line.  This is necessary if you are compiling
ds@1952
    27
** on a recent machine (ex: RedHat 7.2) but you want your code to work
ds@1952
    28
** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
ds@1952
    29
** without this option, LFS is enable.  But LFS does not exist in the kernel
ds@1952
    30
** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
ds@1952
    31
** portability you should omit LFS.
ds@1952
    32
*/
ds@1952
    33
#ifndef SQLITE_DISABLE_LFS
ds@1952
    34
# define _LARGE_FILE       1
ds@1952
    35
# ifndef _FILE_OFFSET_BITS
ds@1952
    36
#   define _FILE_OFFSET_BITS 64
ds@1952
    37
# endif
ds@1952
    38
# define _LARGEFILE_SOURCE 1
ds@1952
    39
#endif
ds@1952
    40
ds@1952
    41
/*
ds@1952
    42
** standard include files.
ds@1952
    43
*/
ds@1952
    44
#include <sys/types.h>
ds@1952
    45
#include <sys/stat.h>
ds@1952
    46
#include <fcntl.h>
ds@1952
    47
#include <unistd.h>
ds@1952
    48
#include <time.h>
ds@1952
    49
#include <sys/time.h>
ds@1952
    50
#include <errno.h>
ds@1952
    51
#ifdef SQLITE_ENABLE_LOCKING_STYLE
ds@1952
    52
#include <sys/ioctl.h>
ds@1952
    53
#include <sys/param.h>
ds@1952
    54
#include <sys/mount.h>
ds@1952
    55
#endif /* SQLITE_ENABLE_LOCKING_STYLE */
ds@1952
    56
ds@1952
    57
/*
ds@1952
    58
** If we are to be thread-safe, include the pthreads header and define
ds@1952
    59
** the SQLITE_UNIX_THREADS macro.
ds@1952
    60
*/
ds@1952
    61
#if SQLITE_THREADSAFE
ds@1952
    62
# include <pthread.h>
ds@1952
    63
# define SQLITE_UNIX_THREADS 1
ds@1952
    64
#endif
ds@1952
    65
ds@1952
    66
/*
ds@1952
    67
** Default permissions when creating a new file
ds@1952
    68
*/
ds@1952
    69
#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
ds@1952
    70
# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
ds@1952
    71
#endif
ds@1952
    72
ds@1952
    73
/*
ds@1952
    74
** Maximum supported path-length.
ds@1952
    75
*/
ds@1952
    76
#define MAX_PATHNAME 512
ds@1952
    77
ds@1952
    78
ds@1952
    79
/*
ds@1952
    80
** The unixFile structure is subclass of sqlite3_file specific for the unix
ds@1952
    81
** protability layer.
ds@1952
    82
*/
ds@1952
    83
typedef struct unixFile unixFile;
ds@1952
    84
struct unixFile {
ds@1952
    85
  sqlite3_io_methods const *pMethod;  /* Always the first entry */
ds@1952
    86
#ifdef SQLITE_TEST
ds@1952
    87
  /* In test mode, increase the size of this structure a bit so that 
ds@1952
    88
  ** it is larger than the struct CrashFile defined in test6.c.
ds@1952
    89
  */
ds@1952
    90
  char aPadding[32];
ds@1952
    91
#endif
ds@1952
    92
  struct openCnt *pOpen;    /* Info about all open fd's on this inode */
ds@1952
    93
  struct lockInfo *pLock;   /* Info about locks on this inode */
ds@1952
    94
#ifdef SQLITE_ENABLE_LOCKING_STYLE
ds@1952
    95
  void *lockingContext;     /* Locking style specific state */
ds@1952
    96
#endif /* SQLITE_ENABLE_LOCKING_STYLE */
ds@1952
    97
  int h;                    /* The file descriptor */
ds@1952
    98
  unsigned char locktype;   /* The type of lock held on this fd */
ds@1952
    99
  int dirfd;                /* File descriptor for the directory */
ds@1952
   100
#if SQLITE_THREADSAFE
ds@1952
   101
  pthread_t tid;            /* The thread that "owns" this unixFile */
ds@1952
   102
#endif
ds@1952
   103
};
ds@1952
   104
ds@1952
   105
/*
ds@1952
   106
** Include code that is common to all os_*.c files
ds@1952
   107
*/
ds@1952
   108
#include "os_common.h"
ds@1952
   109
ds@1952
   110
/*
ds@1952
   111
** Define various macros that are missing from some systems.
ds@1952
   112
*/
ds@1952
   113
#ifndef O_LARGEFILE
ds@1952
   114
# define O_LARGEFILE 0
ds@1952
   115
#endif
ds@1952
   116
#ifdef SQLITE_DISABLE_LFS
ds@1952
   117
# undef O_LARGEFILE
ds@1952
   118
# define O_LARGEFILE 0
ds@1952
   119
#endif
ds@1952
   120
#ifndef O_NOFOLLOW
ds@1952
   121
# define O_NOFOLLOW 0
ds@1952
   122
#endif
ds@1952
   123
#ifndef O_BINARY
ds@1952
   124
# define O_BINARY 0
ds@1952
   125
#endif
ds@1952
   126
ds@1952
   127
/*
ds@1952
   128
** The DJGPP compiler environment looks mostly like Unix, but it
ds@1952
   129
** lacks the fcntl() system call.  So redefine fcntl() to be something
ds@1952
   130
** that always succeeds.  This means that locking does not occur under
ds@1952
   131
** DJGPP.  But it's DOS - what did you expect?
ds@1952
   132
*/
ds@1952
   133
#ifdef __DJGPP__
ds@1952
   134
# define fcntl(A,B,C) 0
ds@1952
   135
#endif
ds@1952
   136
ds@1952
   137
/*
ds@1952
   138
** The threadid macro resolves to the thread-id or to 0.  Used for
ds@1952
   139
** testing and debugging only.
ds@1952
   140
*/
ds@1952
   141
#if SQLITE_THREADSAFE
ds@1952
   142
#define threadid pthread_self()
ds@1952
   143
#else
ds@1952
   144
#define threadid 0
ds@1952
   145
#endif
ds@1952
   146
ds@1952
   147
/*
ds@1952
   148
** Set or check the unixFile.tid field.  This field is set when an unixFile
ds@1952
   149
** is first opened.  All subsequent uses of the unixFile verify that the
ds@1952
   150
** same thread is operating on the unixFile.  Some operating systems do
ds@1952
   151
** not allow locks to be overridden by other threads and that restriction
ds@1952
   152
** means that sqlite3* database handles cannot be moved from one thread
ds@1952
   153
** to another.  This logic makes sure a user does not try to do that
ds@1952
   154
** by mistake.
ds@1952
   155
**
ds@1952
   156
** Version 3.3.1 (2006-01-15):  unixFile can be moved from one thread to
ds@1952
   157
** another as long as we are running on a system that supports threads
ds@1952
   158
** overriding each others locks (which now the most common behavior)
ds@1952
   159
** or if no locks are held.  But the unixFile.pLock field needs to be
ds@1952
   160
** recomputed because its key includes the thread-id.  See the 
ds@1952
   161
** transferOwnership() function below for additional information
ds@1952
   162
*/
ds@1952
   163
#if SQLITE_THREADSAFE
ds@1952
   164
# define SET_THREADID(X)   (X)->tid = pthread_self()
ds@1952
   165
# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
ds@1952
   166
                            !pthread_equal((X)->tid, pthread_self()))
ds@1952
   167
#else
ds@1952
   168
# define SET_THREADID(X)
ds@1952
   169
# define CHECK_THREADID(X) 0
ds@1952
   170
#endif
ds@1952
   171
ds@1952
   172
/*
ds@1952
   173
** Here is the dirt on POSIX advisory locks:  ANSI STD 1003.1 (1996)
ds@1952
   174
** section 6.5.2.2 lines 483 through 490 specify that when a process
ds@1952
   175
** sets or clears a lock, that operation overrides any prior locks set
ds@1952
   176
** by the same process.  It does not explicitly say so, but this implies
ds@1952
   177
** that it overrides locks set by the same process using a different
ds@1952
   178
** file descriptor.  Consider this test case:
ds@1952
   179
**
ds@1952
   180
**       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
ds@1952
   181
**       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
ds@1952
   182
**
ds@1952
   183
** Suppose ./file1 and ./file2 are really the same file (because
ds@1952
   184
** one is a hard or symbolic link to the other) then if you set
ds@1952
   185
** an exclusive lock on fd1, then try to get an exclusive lock
ds@1952
   186
** on fd2, it works.  I would have expected the second lock to
ds@1952
   187
** fail since there was already a lock on the file due to fd1.
ds@1952
   188
** But not so.  Since both locks came from the same process, the
ds@1952
   189
** second overrides the first, even though they were on different
ds@1952
   190
** file descriptors opened on different file names.
ds@1952
   191
**
ds@1952
   192
** Bummer.  If you ask me, this is broken.  Badly broken.  It means
ds@1952
   193
** that we cannot use POSIX locks to synchronize file access among
ds@1952
   194
** competing threads of the same process.  POSIX locks will work fine
ds@1952
   195
** to synchronize access for threads in separate processes, but not
ds@1952
   196
** threads within the same process.
ds@1952
   197
**
ds@1952
   198
** To work around the problem, SQLite has to manage file locks internally
ds@1952
   199
** on its own.  Whenever a new database is opened, we have to find the
ds@1952
   200
** specific inode of the database file (the inode is determined by the
ds@1952
   201
** st_dev and st_ino fields of the stat structure that fstat() fills in)
ds@1952
   202
** and check for locks already existing on that inode.  When locks are
ds@1952
   203
** created or removed, we have to look at our own internal record of the
ds@1952
   204
** locks to see if another thread has previously set a lock on that same
ds@1952
   205
** inode.
ds@1952
   206
**
ds@1952
   207
** The sqlite3_file structure for POSIX is no longer just an integer file
ds@1952
   208
** descriptor.  It is now a structure that holds the integer file
ds@1952
   209
** descriptor and a pointer to a structure that describes the internal
ds@1952
   210
** locks on the corresponding inode.  There is one locking structure
ds@1952
   211
** per inode, so if the same inode is opened twice, both unixFile structures
ds@1952
   212
** point to the same locking structure.  The locking structure keeps
ds@1952
   213
** a reference count (so we will know when to delete it) and a "cnt"
ds@1952
   214
** field that tells us its internal lock status.  cnt==0 means the
ds@1952
   215
** file is unlocked.  cnt==-1 means the file has an exclusive lock.
ds@1952
   216
** cnt>0 means there are cnt shared locks on the file.
ds@1952
   217
**
ds@1952
   218
** Any attempt to lock or unlock a file first checks the locking
ds@1952
   219
** structure.  The fcntl() system call is only invoked to set a 
ds@1952
   220
** POSIX lock if the internal lock structure transitions between
ds@1952
   221
** a locked and an unlocked state.
ds@1952
   222
**
ds@1952
   223
** 2004-Jan-11:
ds@1952
   224
** More recent discoveries about POSIX advisory locks.  (The more
ds@1952
   225
** I discover, the more I realize the a POSIX advisory locks are
ds@1952
   226
** an abomination.)
ds@1952
   227
**
ds@1952
   228
** If you close a file descriptor that points to a file that has locks,
ds@1952
   229
** all locks on that file that are owned by the current process are
ds@1952
   230
** released.  To work around this problem, each unixFile structure contains
ds@1952
   231
** a pointer to an openCnt structure.  There is one openCnt structure
ds@1952
   232
** per open inode, which means that multiple unixFile can point to a single
ds@1952
   233
** openCnt.  When an attempt is made to close an unixFile, if there are
ds@1952
   234
** other unixFile open on the same inode that are holding locks, the call
ds@1952
   235
** to close() the file descriptor is deferred until all of the locks clear.
ds@1952
   236
** The openCnt structure keeps a list of file descriptors that need to
ds@1952
   237
** be closed and that list is walked (and cleared) when the last lock
ds@1952
   238
** clears.
ds@1952
   239
**
ds@1952
   240
** First, under Linux threads, because each thread has a separate
ds@1952
   241
** process ID, lock operations in one thread do not override locks
ds@1952
   242
** to the same file in other threads.  Linux threads behave like
ds@1952
   243
** separate processes in this respect.  But, if you close a file
ds@1952
   244
** descriptor in linux threads, all locks are cleared, even locks
ds@1952
   245
** on other threads and even though the other threads have different
ds@1952
   246
** process IDs.  Linux threads is inconsistent in this respect.
ds@1952
   247
** (I'm beginning to think that linux threads is an abomination too.)
ds@1952
   248
** The consequence of this all is that the hash table for the lockInfo
ds@1952
   249
** structure has to include the process id as part of its key because
ds@1952
   250
** locks in different threads are treated as distinct.  But the 
ds@1952
   251
** openCnt structure should not include the process id in its
ds@1952
   252
** key because close() clears lock on all threads, not just the current
ds@1952
   253
** thread.  Were it not for this goofiness in linux threads, we could
ds@1952
   254
** combine the lockInfo and openCnt structures into a single structure.
ds@1952
   255
**
ds@1952
   256
** 2004-Jun-28:
ds@1952
   257
** On some versions of linux, threads can override each others locks.
ds@1952
   258
** On others not.  Sometimes you can change the behavior on the same
ds@1952
   259
** system by setting the LD_ASSUME_KERNEL environment variable.  The
ds@1952
   260
** POSIX standard is silent as to which behavior is correct, as far
ds@1952
   261
** as I can tell, so other versions of unix might show the same
ds@1952
   262
** inconsistency.  There is no little doubt in my mind that posix
ds@1952
   263
** advisory locks and linux threads are profoundly broken.
ds@1952
   264
**
ds@1952
   265
** To work around the inconsistencies, we have to test at runtime 
ds@1952
   266
** whether or not threads can override each others locks.  This test
ds@1952
   267
** is run once, the first time any lock is attempted.  A static 
ds@1952
   268
** variable is set to record the results of this test for future
ds@1952
   269
** use.
ds@1952
   270
*/
ds@1952
   271
ds@1952
   272
/*
ds@1952
   273
** An instance of the following structure serves as the key used
ds@1952
   274
** to locate a particular lockInfo structure given its inode.
ds@1952
   275
**
ds@1952
   276
** If threads cannot override each others locks, then we set the
ds@1952
   277
** lockKey.tid field to the thread ID.  If threads can override
ds@1952
   278
** each others locks then tid is always set to zero.  tid is omitted
ds@1952
   279
** if we compile without threading support.
ds@1952
   280
*/
ds@1952
   281
struct lockKey {
ds@1952
   282
  dev_t dev;       /* Device number */
ds@1952
   283
  ino_t ino;       /* Inode number */
ds@1952
   284
#if SQLITE_THREADSAFE
ds@1952
   285
  pthread_t tid;   /* Thread ID or zero if threads can override each other */
ds@1952
   286
#endif
ds@1952
   287
};
ds@1952
   288
ds@1952
   289
/*
ds@1952
   290
** An instance of the following structure is allocated for each open
ds@1952
   291
** inode on each thread with a different process ID.  (Threads have
ds@1952
   292
** different process IDs on linux, but not on most other unixes.)
ds@1952
   293
**
ds@1952
   294
** A single inode can have multiple file descriptors, so each unixFile
ds@1952
   295
** structure contains a pointer to an instance of this object and this
ds@1952
   296
** object keeps a count of the number of unixFile pointing to it.
ds@1952
   297
*/
ds@1952
   298
struct lockInfo {
ds@1952
   299
  struct lockKey key;  /* The lookup key */
ds@1952
   300
  int cnt;             /* Number of SHARED locks held */
ds@1952
   301
  int locktype;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
ds@1952
   302
  int nRef;            /* Number of pointers to this structure */
ds@1952
   303
};
ds@1952
   304
ds@1952
   305
/*
ds@1952
   306
** An instance of the following structure serves as the key used
ds@1952
   307
** to locate a particular openCnt structure given its inode.  This
ds@1952
   308
** is the same as the lockKey except that the thread ID is omitted.
ds@1952
   309
*/
ds@1952
   310
struct openKey {
ds@1952
   311
  dev_t dev;   /* Device number */
ds@1952
   312
  ino_t ino;   /* Inode number */
ds@1952
   313
};
ds@1952
   314
ds@1952
   315
/*
ds@1952
   316
** An instance of the following structure is allocated for each open
ds@1952
   317
** inode.  This structure keeps track of the number of locks on that
ds@1952
   318
** inode.  If a close is attempted against an inode that is holding
ds@1952
   319
** locks, the close is deferred until all locks clear by adding the
ds@1952
   320
** file descriptor to be closed to the pending list.
ds@1952
   321
*/
ds@1952
   322
struct openCnt {
ds@1952
   323
  struct openKey key;   /* The lookup key */
ds@1952
   324
  int nRef;             /* Number of pointers to this structure */
ds@1952
   325
  int nLock;            /* Number of outstanding locks */
ds@1952
   326
  int nPending;         /* Number of pending close() operations */
ds@1952
   327
  int *aPending;        /* Malloced space holding fd's awaiting a close() */
ds@1952
   328
};
ds@1952
   329
ds@1952
   330
/* 
ds@1952
   331
** These hash tables map inodes and file descriptors (really, lockKey and
ds@1952
   332
** openKey structures) into lockInfo and openCnt structures.  Access to 
ds@1952
   333
** these hash tables must be protected by a mutex.
ds@1952
   334
*/
ds@1952
   335
static Hash lockHash = {SQLITE_HASH_BINARY, 0, 0, 0, 0, 0};
ds@1952
   336
static Hash openHash = {SQLITE_HASH_BINARY, 0, 0, 0, 0, 0};
ds@1952
   337
ds@1952
   338
#ifdef SQLITE_ENABLE_LOCKING_STYLE
ds@1952
   339
/*
ds@1952
   340
** The locking styles are associated with the different file locking
ds@1952
   341
** capabilities supported by different file systems.  
ds@1952
   342
**
ds@1952
   343
** POSIX locking style fully supports shared and exclusive byte-range locks 
ds@1952
   344
** ADP locking only supports exclusive byte-range locks
ds@1952
   345
** FLOCK only supports a single file-global exclusive lock
ds@1952
   346
** DOTLOCK isn't a true locking style, it refers to the use of a special
ds@1952
   347
**   file named the same as the database file with a '.lock' extension, this
ds@1952
   348
**   can be used on file systems that do not offer any reliable file locking
ds@1952
   349
** NO locking means that no locking will be attempted, this is only used for
ds@1952
   350
**   read-only file systems currently
ds@1952
   351
** UNSUPPORTED means that no locking will be attempted, this is only used for
ds@1952
   352
**   file systems that are known to be unsupported
ds@1952
   353
*/
ds@1952
   354
typedef enum {
ds@1952
   355
        posixLockingStyle = 0,       /* standard posix-advisory locks */
ds@1952
   356
        afpLockingStyle,             /* use afp locks */
ds@1952
   357
        flockLockingStyle,           /* use flock() */
ds@1952
   358
        dotlockLockingStyle,         /* use <file>.lock files */
ds@1952
   359
        noLockingStyle,              /* useful for read-only file system */
ds@1952
   360
        unsupportedLockingStyle      /* indicates unsupported file system */
ds@1952
   361
} sqlite3LockingStyle;
ds@1952
   362
#endif /* SQLITE_ENABLE_LOCKING_STYLE */
ds@1952
   363
ds@1952
   364
/*
ds@1952
   365
** Helper functions to obtain and relinquish the global mutex.
ds@1952
   366
*/
ds@1952
   367
static void enterMutex(){
ds@1952
   368
  sqlite3_mutex_enter(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
ds@1952
   369
}
ds@1952
   370
static void leaveMutex(){
ds@1952
   371
  sqlite3_mutex_leave(sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER));
ds@1952
   372
}
ds@1952
   373
ds@1952
   374
#if SQLITE_THREADSAFE
ds@1952
   375
/*
ds@1952
   376
** This variable records whether or not threads can override each others
ds@1952
   377
** locks.
ds@1952
   378
**
ds@1952
   379
**    0:  No.  Threads cannot override each others locks.
ds@1952
   380
**    1:  Yes.  Threads can override each others locks.
ds@1952
   381
**   -1:  We don't know yet.
ds@1952
   382
**
ds@1952
   383
** On some systems, we know at compile-time if threads can override each
ds@1952
   384
** others locks.  On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
ds@1952
   385
** will be set appropriately.  On other systems, we have to check at
ds@1952
   386
** runtime.  On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
ds@1952
   387
** undefined.
ds@1952
   388
**
ds@1952
   389
** This variable normally has file scope only.  But during testing, we make
ds@1952
   390
** it a global so that the test code can change its value in order to verify
ds@1952
   391
** that the right stuff happens in either case.
ds@1952
   392
*/
ds@1952
   393
#ifndef SQLITE_THREAD_OVERRIDE_LOCK
ds@1952
   394
# define SQLITE_THREAD_OVERRIDE_LOCK -1
ds@1952
   395
#endif
ds@1952
   396
#ifdef SQLITE_TEST
ds@1952
   397
int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
ds@1952
   398
#else
ds@1952
   399
static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
ds@1952
   400
#endif
ds@1952
   401
ds@1952
   402
/*
ds@1952
   403
** This structure holds information passed into individual test
ds@1952
   404
** threads by the testThreadLockingBehavior() routine.
ds@1952
   405
*/
ds@1952
   406
struct threadTestData {
ds@1952
   407
  int fd;                /* File to be locked */
ds@1952
   408
  struct flock lock;     /* The locking operation */
ds@1952
   409
  int result;            /* Result of the locking operation */
ds@1952
   410
};
ds@1952
   411
ds@1952
   412
#ifdef SQLITE_LOCK_TRACE
ds@1952
   413
/*
ds@1952
   414
** Print out information about all locking operations.
ds@1952
   415
**
ds@1952
   416
** This routine is used for troubleshooting locks on multithreaded
ds@1952
   417
** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
ds@1952
   418
** command-line option on the compiler.  This code is normally
ds@1952
   419
** turned off.
ds@1952
   420
*/
ds@1952
   421
static int lockTrace(int fd, int op, struct flock *p){
ds@1952
   422
  char *zOpName, *zType;
ds@1952
   423
  int s;
ds@1952
   424
  int savedErrno;
ds@1952
   425
  if( op==F_GETLK ){
ds@1952
   426
    zOpName = "GETLK";
ds@1952
   427
  }else if( op==F_SETLK ){
ds@1952
   428
    zOpName = "SETLK";
ds@1952
   429
  }else{
ds@1952
   430
    s = fcntl(fd, op, p);
ds@1952
   431
    sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
ds@1952
   432
    return s;
ds@1952
   433
  }
ds@1952
   434
  if( p->l_type==F_RDLCK ){
ds@1952
   435
    zType = "RDLCK";
ds@1952
   436
  }else if( p->l_type==F_WRLCK ){
ds@1952
   437
    zType = "WRLCK";
ds@1952
   438
  }else if( p->l_type==F_UNLCK ){
ds@1952
   439
    zType = "UNLCK";
ds@1952
   440
  }else{
ds@1952
   441
    assert( 0 );
ds@1952
   442
  }
ds@1952
   443
  assert( p->l_whence==SEEK_SET );
ds@1952
   444
  s = fcntl(fd, op, p);
ds@1952
   445
  savedErrno = errno;
ds@1952
   446
  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
ds@1952
   447
     threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
ds@1952
   448
     (int)p->l_pid, s);
ds@1952
   449
  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
ds@1952
   450
    struct flock l2;
ds@1952
   451
    l2 = *p;
ds@1952
   452
    fcntl(fd, F_GETLK, &l2);
ds@1952
   453
    if( l2.l_type==F_RDLCK ){
ds@1952
   454
      zType = "RDLCK";
ds@1952
   455
    }else if( l2.l_type==F_WRLCK ){
ds@1952
   456
      zType = "WRLCK";
ds@1952
   457
    }else if( l2.l_type==F_UNLCK ){
ds@1952
   458
      zType = "UNLCK";
ds@1952
   459
    }else{
ds@1952
   460
      assert( 0 );
ds@1952
   461
    }
ds@1952
   462
    sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
ds@1952
   463
       zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
ds@1952
   464
  }
ds@1952
   465
  errno = savedErrno;
ds@1952
   466
  return s;
ds@1952
   467
}
ds@1952
   468
#define fcntl lockTrace
ds@1952
   469
#endif /* SQLITE_LOCK_TRACE */
ds@1952
   470
ds@1952
   471
/*
ds@1952
   472
** The testThreadLockingBehavior() routine launches two separate
ds@1952
   473
** threads on this routine.  This routine attempts to lock a file
ds@1952
   474
** descriptor then returns.  The success or failure of that attempt
ds@1952
   475
** allows the testThreadLockingBehavior() procedure to determine
ds@1952
   476
** whether or not threads can override each others locks.
ds@1952
   477
*/
ds@1952
   478
static void *threadLockingTest(void *pArg){
ds@1952
   479
  struct threadTestData *pData = (struct threadTestData*)pArg;
ds@1952
   480
  pData->result = fcntl(pData->fd, F_SETLK, &pData->lock);
ds@1952
   481
  return pArg;
ds@1952
   482
}
ds@1952
   483
ds@1952
   484
/*
ds@1952
   485
** This procedure attempts to determine whether or not threads
ds@1952
   486
** can override each others locks then sets the 
ds@1952
   487
** threadsOverrideEachOthersLocks variable appropriately.
ds@1952
   488
*/
ds@1952
   489
static void testThreadLockingBehavior(int fd_orig){
ds@1952
   490
  int fd;
ds@1952
   491
  struct threadTestData d[2];
ds@1952
   492
  pthread_t t[2];
ds@1952
   493
ds@1952
   494
  fd = dup(fd_orig);
ds@1952
   495
  if( fd<0 ) return;
ds@1952
   496
  memset(d, 0, sizeof(d));
ds@1952
   497
  d[0].fd = fd;
ds@1952
   498
  d[0].lock.l_type = F_RDLCK;
ds@1952
   499
  d[0].lock.l_len = 1;
ds@1952
   500
  d[0].lock.l_start = 0;
ds@1952
   501
  d[0].lock.l_whence = SEEK_SET;
ds@1952
   502
  d[1] = d[0];
ds@1952
   503
  d[1].lock.l_type = F_WRLCK;
ds@1952
   504
  pthread_create(&t[0], 0, threadLockingTest, &d[0]);
ds@1952
   505
  pthread_create(&t[1], 0, threadLockingTest, &d[1]);
ds@1952
   506
  pthread_join(t[0], 0);
ds@1952
   507
  pthread_join(t[1], 0);
ds@1952
   508
  close(fd);
ds@1952
   509
  threadsOverrideEachOthersLocks =  d[0].result==0 && d[1].result==0;
ds@1952
   510
}
ds@1952
   511
#endif /* SQLITE_THREADSAFE */
ds@1952
   512
ds@1952
   513
/*
ds@1952
   514
** Release a lockInfo structure previously allocated by findLockInfo().
ds@1952
   515
*/
ds@1952
   516
static void releaseLockInfo(struct lockInfo *pLock){
ds@1952
   517
  if (pLock == NULL)
ds@1952
   518
    return;
ds@1952
   519
  pLock->nRef--;
ds@1952
   520
  if( pLock->nRef==0 ){
ds@1952
   521
    sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
ds@1952
   522
    sqlite3_free(pLock);
ds@1952
   523
  }
ds@1952
   524
}
ds@1952
   525
ds@1952
   526
/*
ds@1952
   527
** Release a openCnt structure previously allocated by findLockInfo().
ds@1952
   528
*/
ds@1952
   529
static void releaseOpenCnt(struct openCnt *pOpen){
ds@1952
   530
  if (pOpen == NULL)
ds@1952
   531
    return;
ds@1952
   532
  pOpen->nRef--;
ds@1952
   533
  if( pOpen->nRef==0 ){
ds@1952
   534
    sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
ds@1952
   535
    free(pOpen->aPending);
ds@1952
   536
    sqlite3_free(pOpen);
ds@1952
   537
  }
ds@1952
   538
}
ds@1952
   539
ds@1952
   540
#ifdef SQLITE_ENABLE_LOCKING_STYLE
ds@1952
   541
/*
ds@1952
   542
** Tests a byte-range locking query to see if byte range locks are 
ds@1952
   543
** supported, if not we fall back to dotlockLockingStyle.
ds@1952
   544
*/
ds@1952
   545
static sqlite3LockingStyle sqlite3TestLockingStyle(
ds@1952
   546
  const char *filePath, 
ds@1952
   547
  int fd
ds@1952
   548
){
ds@1952
   549
  /* test byte-range lock using fcntl */
ds@1952
   550
  struct flock lockInfo;
ds@1952
   551
  
ds@1952
   552
  lockInfo.l_len = 1;
ds@1952
   553
  lockInfo.l_start = 0;
ds@1952
   554
  lockInfo.l_whence = SEEK_SET;
ds@1952
   555
  lockInfo.l_type = F_RDLCK;
ds@1952
   556
  
ds@1952
   557
  if( fcntl(fd, F_GETLK, &lockInfo)!=-1 ) {
ds@1952
   558
    return posixLockingStyle;
ds@1952
   559
  } 
ds@1952
   560
  
ds@1952
   561
  /* testing for flock can give false positives.  So if if the above test
ds@1952
   562
  ** fails, then we fall back to using dot-lock style locking.
ds@1952
   563
  */  
ds@1952
   564
  return dotlockLockingStyle;
ds@1952
   565
}
ds@1952
   566
ds@1952
   567
/* 
ds@1952
   568
** Examines the f_fstypename entry in the statfs structure as returned by 
ds@1952
   569
** stat() for the file system hosting the database file, assigns the 
ds@1952
   570
** appropriate locking style based on it's value.  These values and 
ds@1952
   571
** assignments are based on Darwin/OSX behavior and have not been tested on 
ds@1952
   572
** other systems.
ds@1952
   573
*/
ds@1952
   574
static sqlite3LockingStyle sqlite3DetectLockingStyle(
ds@1952
   575
  const char *filePath, 
ds@1952
   576
  int fd
ds@1952
   577
){
ds@1952
   578
ds@1952
   579
#ifdef SQLITE_FIXED_LOCKING_STYLE
ds@1952
   580
  return (sqlite3LockingStyle)SQLITE_FIXED_LOCKING_STYLE;
ds@1952
   581
#else
ds@1952
   582
  struct statfs fsInfo;
ds@1952
   583
ds@1952
   584
  if (statfs(filePath, &fsInfo) == -1)
ds@1952
   585
    return sqlite3TestLockingStyle(filePath, fd);
ds@1952
   586
  
ds@1952
   587
  if (fsInfo.f_flags & MNT_RDONLY)
ds@1952
   588
    return noLockingStyle;
ds@1952
   589
  
ds@1952
   590
  if( (!strcmp(fsInfo.f_fstypename, "hfs")) ||
ds@1952
   591
    (!strcmp(fsInfo.f_fstypename, "ufs")) )
ds@1952
   592
                return posixLockingStyle;
ds@1952
   593
  
ds@1952
   594
  if(!strcmp(fsInfo.f_fstypename, "afpfs"))
ds@1952
   595
    return afpLockingStyle;
ds@1952
   596
  
ds@1952
   597
  if(!strcmp(fsInfo.f_fstypename, "nfs")) 
ds@1952
   598
    return sqlite3TestLockingStyle(filePath, fd);
ds@1952
   599
  
ds@1952
   600
  if(!strcmp(fsInfo.f_fstypename, "smbfs"))
ds@1952
   601
    return flockLockingStyle;
ds@1952
   602
  
ds@1952
   603
  if(!strcmp(fsInfo.f_fstypename, "msdos"))
ds@1952
   604
    return dotlockLockingStyle;
ds@1952
   605
  
ds@1952
   606
  if(!strcmp(fsInfo.f_fstypename, "webdav"))
ds@1952
   607
    return unsupportedLockingStyle;
ds@1952
   608
  
ds@1952
   609
  return sqlite3TestLockingStyle(filePath, fd);  
ds@1952
   610
#endif /* SQLITE_FIXED_LOCKING_STYLE */
ds@1952
   611
}
ds@1952
   612
ds@1952
   613
#endif /* SQLITE_ENABLE_LOCKING_STYLE */
ds@1952
   614
ds@1952
   615
/*
ds@1952
   616
** Given a file descriptor, locate lockInfo and openCnt structures that
ds@1952
   617
** describes that file descriptor.  Create new ones if necessary.  The
ds@1952
   618
** return values might be uninitialized if an error occurs.
ds@1952
   619
**
ds@1952
   620
** Return the number of errors.
ds@1952
   621
*/
ds@1952
   622
static int findLockInfo(
ds@1952
   623
  int fd,                      /* The file descriptor used in the key */
ds@1952
   624
  struct lockInfo **ppLock,    /* Return the lockInfo structure here */
ds@1952
   625
  struct openCnt **ppOpen      /* Return the openCnt structure here */
ds@1952
   626
){
ds@1952
   627
  int rc;
ds@1952
   628
  struct lockKey key1;
ds@1952
   629
  struct openKey key2;
ds@1952
   630
  struct stat statbuf;
ds@1952
   631
  struct lockInfo *pLock;
ds@1952
   632
  struct openCnt *pOpen;
ds@1952
   633
  rc = fstat(fd, &statbuf);
ds@1952
   634
  if( rc!=0 ) return 1;
ds@1952
   635
ds@1952
   636
  memset(&key1, 0, sizeof(key1));
ds@1952
   637
  key1.dev = statbuf.st_dev;
ds@1952
   638
  key1.ino = statbuf.st_ino;
ds@1952
   639
#if SQLITE_THREADSAFE
ds@1952
   640
  if( threadsOverrideEachOthersLocks<0 ){
ds@1952
   641
    testThreadLockingBehavior(fd);
ds@1952
   642
  }
ds@1952
   643
  key1.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
ds@1952
   644
#endif
ds@1952
   645
  memset(&key2, 0, sizeof(key2));
ds@1952
   646
  key2.dev = statbuf.st_dev;
ds@1952
   647
  key2.ino = statbuf.st_ino;
ds@1952
   648
  pLock = (struct lockInfo*)sqlite3HashFind(&lockHash, &key1, sizeof(key1));
ds@1952
   649
  if( pLock==0 ){
ds@1952
   650
    struct lockInfo *pOld;
ds@1952
   651
    pLock = sqlite3_malloc( sizeof(*pLock) );
ds@1952
   652
    if( pLock==0 ){
ds@1952
   653
      rc = 1;
ds@1952
   654
      goto exit_findlockinfo;
ds@1952
   655
    }
ds@1952
   656
    pLock->key = key1;
ds@1952
   657
    pLock->nRef = 1;
ds@1952
   658
    pLock->cnt = 0;
ds@1952
   659
    pLock->locktype = 0;
ds@1952
   660
    pOld = sqlite3HashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
ds@1952
   661
    if( pOld!=0 ){
ds@1952
   662
      assert( pOld==pLock );
ds@1952
   663
      sqlite3_free(pLock);
ds@1952
   664
      rc = 1;
ds@1952
   665
      goto exit_findlockinfo;
ds@1952
   666
    }
ds@1952
   667
  }else{
ds@1952
   668
    pLock->nRef++;
ds@1952
   669
  }
ds@1952
   670
  *ppLock = pLock;
ds@1952
   671
  if( ppOpen!=0 ){
ds@1952
   672
    pOpen = (struct openCnt*)sqlite3HashFind(&openHash, &key2, sizeof(key2));
ds@1952
   673
    if( pOpen==0 ){
ds@1952
   674
      struct openCnt *pOld;
ds@1952
   675
      pOpen = sqlite3_malloc( sizeof(*pOpen) );
ds@1952
   676
      if( pOpen==0 ){
ds@1952
   677
        releaseLockInfo(pLock);
ds@1952
   678
        rc = 1;
ds@1952
   679
        goto exit_findlockinfo;
ds@1952
   680
      }
ds@1952
   681
      pOpen->key = key2;
ds@1952
   682
      pOpen->nRef = 1;
ds@1952
   683
      pOpen->nLock = 0;
ds@1952
   684
      pOpen->nPending = 0;
ds@1952
   685
      pOpen->aPending = 0;
ds@1952
   686
      pOld = sqlite3HashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
ds@1952
   687
      if( pOld!=0 ){
ds@1952
   688
        assert( pOld==pOpen );
ds@1952
   689
        sqlite3_free(pOpen);
ds@1952
   690
        releaseLockInfo(pLock);
ds@1952
   691
        rc = 1;
ds@1952
   692
        goto exit_findlockinfo;
ds@1952
   693
      }
ds@1952
   694
    }else{
ds@1952
   695
      pOpen->nRef++;
ds@1952
   696
    }
ds@1952
   697
    *ppOpen = pOpen;
ds@1952
   698
  }
ds@1952
   699
ds@1952
   700
exit_findlockinfo:
ds@1952
   701
  return rc;
ds@1952
   702
}
ds@1952
   703
ds@1952
   704
#ifdef SQLITE_DEBUG
ds@1952
   705
/*
ds@1952
   706
** Helper function for printing out trace information from debugging
ds@1952
   707
** binaries. This returns the string represetation of the supplied
ds@1952
   708
** integer lock-type.
ds@1952
   709
*/
ds@1952
   710
static const char *locktypeName(int locktype){
ds@1952
   711
  switch( locktype ){
ds@1952
   712
  case NO_LOCK: return "NONE";
ds@1952
   713
  case SHARED_LOCK: return "SHARED";
ds@1952
   714
  case RESERVED_LOCK: return "RESERVED";
ds@1952
   715
  case PENDING_LOCK: return "PENDING";
ds@1952
   716
  case EXCLUSIVE_LOCK: return "EXCLUSIVE";
ds@1952
   717
  }
ds@1952
   718
  return "ERROR";
ds@1952
   719
}
ds@1952
   720
#endif
ds@1952
   721
ds@1952
   722
/*
ds@1952
   723
** If we are currently in a different thread than the thread that the
ds@1952
   724
** unixFile argument belongs to, then transfer ownership of the unixFile
ds@1952
   725
** over to the current thread.
ds@1952
   726
**
ds@1952
   727
** A unixFile is only owned by a thread on systems where one thread is
ds@1952
   728
** unable to override locks created by a different thread.  RedHat9 is
ds@1952
   729
** an example of such a system.
ds@1952
   730
**
ds@1952
   731
** Ownership transfer is only allowed if the unixFile is currently unlocked.
ds@1952
   732
** If the unixFile is locked and an ownership is wrong, then return
ds@1952
   733
** SQLITE_MISUSE.  SQLITE_OK is returned if everything works.
ds@1952
   734
*/
ds@1952
   735
#if SQLITE_THREADSAFE
ds@1952
   736
static int transferOwnership(unixFile *pFile){
ds@1952
   737
  int rc;
ds@1952
   738
  pthread_t hSelf;
ds@1952
   739
  if( threadsOverrideEachOthersLocks ){
ds@1952
   740
    /* Ownership transfers not needed on this system */
ds@1952
   741
    return SQLITE_OK;
ds@1952
   742
  }
ds@1952
   743
  hSelf = pthread_self();
ds@1952
   744
  if( pthread_equal(pFile->tid, hSelf) ){
ds@1952
   745
    /* We are still in the same thread */
ds@1952
   746
    OSTRACE1("No-transfer, same thread\n");
ds@1952
   747
    return SQLITE_OK;
ds@1952
   748
  }
ds@1952
   749
  if( pFile->locktype!=NO_LOCK ){
ds@1952
   750
    /* We cannot change ownership while we are holding a lock! */
ds@1952
   751
    return SQLITE_MISUSE;
ds@1952
   752
  }
ds@1952
   753
  OSTRACE4("Transfer ownership of %d from %d to %d\n",
ds@1952
   754
            pFile->h, pFile->tid, hSelf);
ds@1952
   755
  pFile->tid = hSelf;
ds@1952
   756
  if (pFile->pLock != NULL) {
ds@1952
   757
    releaseLockInfo(pFile->pLock);
ds@1952
   758
    rc = findLockInfo(pFile->h, &pFile->pLock, 0);
ds@1952
   759
    OSTRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
ds@1952
   760
           locktypeName(pFile->locktype),
ds@1952
   761
           locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
ds@1952
   762
    return rc;
ds@1952
   763
  } else {
ds@1952
   764
    return SQLITE_OK;
ds@1952
   765
  }
ds@1952
   766
}
ds@1952
   767
#else
ds@1952
   768
  /* On single-threaded builds, ownership transfer is a no-op */
ds@1952
   769
# define transferOwnership(X) SQLITE_OK
ds@1952
   770
#endif
ds@1952
   771
ds@1952
   772
/*
ds@1952
   773
** Seek to the offset passed as the second argument, then read cnt 
ds@1952
   774
** bytes into pBuf. Return the number of bytes actually read.
ds@1952
   775
*/
ds@1952
   776
static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
ds@1952
   777
  int got;
ds@1952
   778
  i64 newOffset;
ds@1952
   779
  TIMER_START;
ds@1952
   780
#if defined(USE_PREAD)
ds@1952
   781
  got = pread(id->h, pBuf, cnt, offset);
ds@1952
   782
  SimulateIOError( got = -1 );
ds@1952
   783
#elif defined(USE_PREAD64)
ds@1952
   784
  got = pread64(id->h, pBuf, cnt, offset);
ds@1952
   785
  SimulateIOError( got = -1 );
ds@1952
   786
#else
ds@1952
   787
  newOffset = lseek(id->h, offset, SEEK_SET);
ds@1952
   788
  SimulateIOError( newOffset-- );
ds@1952
   789
  if( newOffset!=offset ){
ds@1952
   790
    return -1;
ds@1952
   791
  }
ds@1952
   792
  got = read(id->h, pBuf, cnt);
ds@1952
   793
#endif
ds@1952
   794
  TIMER_END;
ds@1952
   795
  OSTRACE5("READ    %-3d %5d %7lld %d\n", id->h, got, offset, TIMER_ELAPSED);
ds@1952
   796
  return got;
ds@1952
   797
}
ds@1952
   798
ds@1952
   799
/*
ds@1952
   800
** Read data from a file into a buffer.  Return SQLITE_OK if all
ds@1952
   801
** bytes were read successfully and SQLITE_IOERR if anything goes
ds@1952
   802
** wrong.
ds@1952
   803
*/
ds@1952
   804
static int unixRead(
ds@1952
   805
  sqlite3_file *id, 
ds@1952
   806
  void *pBuf, 
ds@1952
   807
  int amt,
ds@1952
   808
  sqlite3_int64 offset
ds@1952
   809
){
ds@1952
   810
  int got;
ds@1952
   811
  assert( id );
ds@1952
   812
  got = seekAndRead((unixFile*)id, offset, pBuf, amt);
ds@1952
   813
  if( got==amt ){
ds@1952
   814
    return SQLITE_OK;
ds@1952
   815
  }else if( got<0 ){
ds@1952
   816
    return SQLITE_IOERR_READ;
ds@1952
   817
  }else{
ds@1952
   818
    memset(&((char*)pBuf)[got], 0, amt-got);
ds@1952
   819
    return SQLITE_IOERR_SHORT_READ;
ds@1952
   820
  }
ds@1952
   821
}
ds@1952
   822
ds@1952
   823
/*
ds@1952
   824
** Seek to the offset in id->offset then read cnt bytes into pBuf.
ds@1952
   825
** Return the number of bytes actually read.  Update the offset.
ds@1952
   826
*/
ds@1952
   827
static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
ds@1952
   828
  int got;
ds@1952
   829
  i64 newOffset;
ds@1952
   830
  TIMER_START;
ds@1952
   831
#if defined(USE_PREAD)
ds@1952
   832
  got = pwrite(id->h, pBuf, cnt, offset);
ds@1952
   833
#elif defined(USE_PREAD64)
ds@1952
   834
  got = pwrite64(id->h, pBuf, cnt, offset);
ds@1952
   835
#else
ds@1952
   836
  newOffset = lseek(id->h, offset, SEEK_SET);
ds@1952
   837
  if( newOffset!=offset ){
ds@1952
   838
    return -1;
ds@1952
   839
  }
ds@1952
   840
  got = write(id->h, pBuf, cnt);
ds@1952
   841
#endif
ds@1952
   842
  TIMER_END;
ds@1952
   843
  OSTRACE5("WRITE   %-3d %5d %7lld %d\n", id->h, got, offset, TIMER_ELAPSED);
ds@1952
   844
  return got;
ds@1952
   845
}
ds@1952
   846
ds@1952
   847
ds@1952
   848
/*
ds@1952
   849
** Write data from a buffer into a file.  Return SQLITE_OK on success
ds@1952
   850
** or some other error code on failure.
ds@1952
   851
*/
ds@1952
   852
static int unixWrite(
ds@1952
   853
  sqlite3_file *id, 
ds@1952
   854
  const void *pBuf, 
ds@1952
   855
  int amt,
ds@1952
   856
  sqlite3_int64 offset 
ds@1952
   857
){
ds@1952
   858
  int wrote = 0;
ds@1952
   859
  assert( id );
ds@1952
   860
  assert( amt>0 );
ds@1952
   861
  while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
ds@1952
   862
    amt -= wrote;
ds@1952
   863
    offset += wrote;
ds@1952
   864
    pBuf = &((char*)pBuf)[wrote];
ds@1952
   865
  }
ds@1952
   866
  SimulateIOError(( wrote=(-1), amt=1 ));
ds@1952
   867
  SimulateDiskfullError(( wrote=0, amt=1 ));
ds@1952
   868
  if( amt>0 ){
ds@1952
   869
    if( wrote<0 ){
ds@1952
   870
      return SQLITE_IOERR_WRITE;
ds@1952
   871
    }else{
ds@1952
   872
      return SQLITE_FULL;
ds@1952
   873
    }
ds@1952
   874
  }
ds@1952
   875
  return SQLITE_OK;
ds@1952
   876
}
ds@1952
   877
ds@1952
   878
#ifdef SQLITE_TEST
ds@1952
   879
/*
ds@1952
   880
** Count the number of fullsyncs and normal syncs.  This is used to test
ds@1952
   881
** that syncs and fullsyncs are occuring at the right times.
ds@1952
   882
*/
ds@1952
   883
int sqlite3_sync_count = 0;
ds@1952
   884
int sqlite3_fullsync_count = 0;
ds@1952
   885
#endif
ds@1952
   886
ds@1952
   887
/*
ds@1952
   888
** Use the fdatasync() API only if the HAVE_FDATASYNC macro is defined.
ds@1952
   889
** Otherwise use fsync() in its place.
ds@1952
   890
*/
ds@1952
   891
#ifndef HAVE_FDATASYNC
ds@1952
   892
# define fdatasync fsync
ds@1952
   893
#endif
ds@1952
   894
ds@1952
   895
/*
ds@1952
   896
** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
ds@1952
   897
** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
ds@1952
   898
** only available on Mac OS X.  But that could change.
ds@1952
   899
*/
ds@1952
   900
#ifdef F_FULLFSYNC
ds@1952
   901
# define HAVE_FULLFSYNC 1
ds@1952
   902
#else
ds@1952
   903
# define HAVE_FULLFSYNC 0
ds@1952
   904
#endif
ds@1952
   905
ds@1952
   906
ds@1952
   907
/*
ds@1952
   908
** The fsync() system call does not work as advertised on many
ds@1952
   909
** unix systems.  The following procedure is an attempt to make
ds@1952
   910
** it work better.
ds@1952
   911
**
ds@1952
   912
** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
ds@1952
   913
** for testing when we want to run through the test suite quickly.
ds@1952
   914
** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
ds@1952
   915
** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
ds@1952
   916
** or power failure will likely corrupt the database file.
ds@1952
   917
*/
ds@1952
   918
static int full_fsync(int fd, int fullSync, int dataOnly){
ds@1952
   919
  int rc;
ds@1952
   920
ds@1952
   921
  /* Record the number of times that we do a normal fsync() and 
ds@1952
   922
  ** FULLSYNC.  This is used during testing to verify that this procedure
ds@1952
   923
  ** gets called with the correct arguments.
ds@1952
   924
  */
ds@1952
   925
#ifdef SQLITE_TEST
ds@1952
   926
  if( fullSync ) sqlite3_fullsync_count++;
ds@1952
   927
  sqlite3_sync_count++;
ds@1952
   928
#endif
ds@1952
   929
ds@1952
   930
  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
ds@1952
   931
  ** no-op
ds@1952
   932
  */
ds@1952
   933
#ifdef SQLITE_NO_SYNC
ds@1952
   934
  rc = SQLITE_OK;
ds@1952
   935
#else
ds@1952
   936
ds@1952
   937
#if HAVE_FULLFSYNC
ds@1952
   938
  if( fullSync ){
ds@1952
   939
    rc = fcntl(fd, F_FULLFSYNC, 0);
ds@1952
   940
  }else{
ds@1952
   941
    rc = 1;
ds@1952
   942
  }
ds@1952
   943
  /* If the FULLFSYNC failed, fall back to attempting an fsync().
ds@1952
   944
   * It shouldn't be possible for fullfsync to fail on the local 
ds@1952
   945
   * file system (on OSX), so failure indicates that FULLFSYNC
ds@1952
   946
   * isn't supported for this file system. So, attempt an fsync 
ds@1952
   947
   * and (for now) ignore the overhead of a superfluous fcntl call.  
ds@1952
   948
   * It'd be better to detect fullfsync support once and avoid 
ds@1952
   949
   * the fcntl call every time sync is called.
ds@1952
   950
   */
ds@1952
   951
  if( rc ) rc = fsync(fd);
ds@1952
   952
ds@1952
   953
#else 
ds@1952
   954
  if( dataOnly ){
ds@1952
   955
    rc = fdatasync(fd);
ds@1952
   956
  }else{
ds@1952
   957
    rc = fsync(fd);
ds@1952
   958
  }
ds@1952
   959
#endif /* HAVE_FULLFSYNC */
ds@1952
   960
#endif /* defined(SQLITE_NO_SYNC) */
ds@1952
   961
ds@1952
   962
  return rc;
ds@1952
   963
}
ds@1952
   964
ds@1952
   965
/*
ds@1952
   966
** Make sure all writes to a particular file are committed to disk.
ds@1952
   967
**
ds@1952
   968
** If dataOnly==0 then both the file itself and its metadata (file
ds@1952
   969
** size, access time, etc) are synced.  If dataOnly!=0 then only the
ds@1952
   970
** file data is synced.
ds@1952
   971
**
ds@1952
   972
** Under Unix, also make sure that the directory entry for the file
ds@1952
   973
** has been created by fsync-ing the directory that contains the file.
ds@1952
   974
** If we do not do this and we encounter a power failure, the directory
ds@1952
   975
** entry for the journal might not exist after we reboot.  The next
ds@1952
   976
** SQLite to access the file will not know that the journal exists (because
ds@1952
   977
** the directory entry for the journal was never created) and the transaction
ds@1952
   978
** will not roll back - possibly leading to database corruption.
ds@1952
   979
*/
ds@1952
   980
static int unixSync(sqlite3_file *id, int flags){
ds@1952
   981
  int rc;
ds@1952
   982
  unixFile *pFile = (unixFile*)id;
ds@1952
   983
ds@1952
   984
  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
ds@1952
   985
  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
ds@1952
   986
ds@1952
   987
  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
ds@1952
   988
  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
ds@1952
   989
      || (flags&0x0F)==SQLITE_SYNC_FULL
ds@1952
   990
  );
ds@1952
   991
ds@1952
   992
  assert( pFile );
ds@1952
   993
  OSTRACE2("SYNC    %-3d\n", pFile->h);
ds@1952
   994
  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
ds@1952
   995
  SimulateIOError( rc=1 );
ds@1952
   996
  if( rc ){
ds@1952
   997
    return SQLITE_IOERR_FSYNC;
ds@1952
   998
  }
ds@1952
   999
  if( pFile->dirfd>=0 ){
ds@1952
  1000
    OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
ds@1952
  1001
            HAVE_FULLFSYNC, isFullsync);
ds@1952
  1002
#ifndef SQLITE_DISABLE_DIRSYNC
ds@1952
  1003
    /* The directory sync is only attempted if full_fsync is
ds@1952
  1004
    ** turned off or unavailable.  If a full_fsync occurred above,
ds@1952
  1005
    ** then the directory sync is superfluous.
ds@1952
  1006
    */
ds@1952
  1007
    if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
ds@1952
  1008
       /*
ds@1952
  1009
       ** We have received multiple reports of fsync() returning
ds@1952
  1010
       ** errors when applied to directories on certain file systems.
ds@1952
  1011
       ** A failed directory sync is not a big deal.  So it seems
ds@1952
  1012
       ** better to ignore the error.  Ticket #1657
ds@1952
  1013
       */
ds@1952
  1014
       /* return SQLITE_IOERR; */
ds@1952
  1015
    }
ds@1952
  1016
#endif
ds@1952
  1017
    close(pFile->dirfd);  /* Only need to sync once, so close the directory */
ds@1952
  1018
    pFile->dirfd = -1;    /* when we are done. */
ds@1952
  1019
  }
ds@1952
  1020
  return SQLITE_OK;
ds@1952
  1021
}
ds@1952
  1022
ds@1952
  1023
/*
ds@1952
  1024
** Truncate an open file to a specified size
ds@1952
  1025
*/
ds@1952
  1026
static int unixTruncate(sqlite3_file *id, i64 nByte){
ds@1952
  1027
  int rc;
ds@1952
  1028
  assert( id );
ds@1952
  1029
  rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
ds@1952
  1030
  SimulateIOError( rc=1 );
ds@1952
  1031
  if( rc ){
ds@1952
  1032
    return SQLITE_IOERR_TRUNCATE;
ds@1952
  1033
  }else{
ds@1952
  1034
    return SQLITE_OK;
ds@1952
  1035
  }
ds@1952
  1036
}
ds@1952
  1037
ds@1952
  1038
/*
ds@1952
  1039
** Determine the current size of a file in bytes
ds@1952
  1040
*/
ds@1952
  1041
static int unixFileSize(sqlite3_file *id, i64 *pSize){
ds@1952
  1042
  int rc;
ds@1952
  1043
  struct stat buf;
ds@1952
  1044
  assert( id );
ds@1952
  1045
  rc = fstat(((unixFile*)id)->h, &buf);
ds@1952
  1046
  SimulateIOError( rc=1 );
ds@1952
  1047
  if( rc!=0 ){
ds@1952
  1048
    return SQLITE_IOERR_FSTAT;
ds@1952
  1049
  }
ds@1952
  1050
  *pSize = buf.st_size;
ds@1952
  1051
  return SQLITE_OK;
ds@1952
  1052
}
ds@1952
  1053
ds@1952
  1054
/*
ds@1952
  1055
** This routine checks if there is a RESERVED lock held on the specified
ds@1952
  1056
** file by this or any other process. If such a lock is held, return
ds@1952
  1057
** non-zero.  If the file is unlocked or holds only SHARED locks, then
ds@1952
  1058
** return zero.
ds@1952
  1059
*/
ds@1952
  1060
static int unixCheckReservedLock(sqlite3_file *id){
ds@1952
  1061
  int r = 0;
ds@1952
  1062
  unixFile *pFile = (unixFile*)id;
ds@1952
  1063
ds@1952
  1064
  assert( pFile );
ds@1952
  1065
  enterMutex(); /* Because pFile->pLock is shared across threads */
ds@1952
  1066
ds@1952
  1067
  /* Check if a thread in this process holds such a lock */
ds@1952
  1068
  if( pFile->pLock->locktype>SHARED_LOCK ){
ds@1952
  1069
    r = 1;
ds@1952
  1070
  }
ds@1952
  1071
ds@1952
  1072
  /* Otherwise see if some other process holds it.
ds@1952
  1073
  */
ds@1952
  1074
  if( !r ){
ds@1952
  1075
    struct flock lock;
ds@1952
  1076
    lock.l_whence = SEEK_SET;
ds@1952
  1077
    lock.l_start = RESERVED_BYTE;
ds@1952
  1078
    lock.l_len = 1;
ds@1952
  1079
    lock.l_type = F_WRLCK;
ds@1952
  1080
    fcntl(pFile->h, F_GETLK, &lock);
ds@1952
  1081
    if( lock.l_type!=F_UNLCK ){
ds@1952
  1082
      r = 1;
ds@1952
  1083
    }
ds@1952
  1084
  }
ds@1952
  1085
  
ds@1952
  1086
  leaveMutex();
ds@1952
  1087
  OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
ds@1952
  1088
ds@1952
  1089
  return r;
ds@1952
  1090
}
ds@1952
  1091
ds@1952
  1092
/*
ds@1952
  1093
** Lock the file with the lock specified by parameter locktype - one
ds@1952
  1094
** of the following:
ds@1952
  1095
**
ds@1952
  1096
**     (1) SHARED_LOCK
ds@1952
  1097
**     (2) RESERVED_LOCK
ds@1952
  1098
**     (3) PENDING_LOCK
ds@1952
  1099
**     (4) EXCLUSIVE_LOCK
ds@1952
  1100
**
ds@1952
  1101
** Sometimes when requesting one lock state, additional lock states
ds@1952
  1102
** are inserted in between.  The locking might fail on one of the later
ds@1952
  1103
** transitions leaving the lock state different from what it started but
ds@1952
  1104
** still short of its goal.  The following chart shows the allowed
ds@1952
  1105
** transitions and the inserted intermediate states:
ds@1952
  1106
**
ds@1952
  1107
**    UNLOCKED -> SHARED
ds@1952
  1108
**    SHARED -> RESERVED
ds@1952
  1109
**    SHARED -> (PENDING) -> EXCLUSIVE
ds@1952
  1110
**    RESERVED -> (PENDING) -> EXCLUSIVE
ds@1952
  1111
**    PENDING -> EXCLUSIVE
ds@1952
  1112
**
ds@1952
  1113
** This routine will only increase a lock.  Use the sqlite3OsUnlock()
ds@1952
  1114
** routine to lower a locking level.
ds@1952
  1115
*/
ds@1952
  1116
static int unixLock(sqlite3_file *id, int locktype){
ds@1952
  1117
  /* The following describes the implementation of the various locks and
ds@1952
  1118
  ** lock transitions in terms of the POSIX advisory shared and exclusive
ds@1952
  1119
  ** lock primitives (called read-locks and write-locks below, to avoid
ds@1952
  1120
  ** confusion with SQLite lock names). The algorithms are complicated
ds@1952
  1121
  ** slightly in order to be compatible with windows systems simultaneously
ds@1952
  1122
  ** accessing the same database file, in case that is ever required.
ds@1952
  1123
  **
ds@1952
  1124
  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
ds@1952
  1125
  ** byte', each single bytes at well known offsets, and the 'shared byte
ds@1952
  1126
  ** range', a range of 510 bytes at a well known offset.
ds@1952
  1127
  **
ds@1952
  1128
  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
ds@1952
  1129
  ** byte'.  If this is successful, a random byte from the 'shared byte
ds@1952
  1130
  ** range' is read-locked and the lock on the 'pending byte' released.
ds@1952
  1131
  **
ds@1952
  1132
  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
ds@1952
  1133
  ** A RESERVED lock is implemented by grabbing a write-lock on the
ds@1952
  1134
  ** 'reserved byte'. 
ds@1952
  1135
  **
ds@1952
  1136
  ** A process may only obtain a PENDING lock after it has obtained a
ds@1952
  1137
  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
ds@1952
  1138
  ** on the 'pending byte'. This ensures that no new SHARED locks can be
ds@1952
  1139
  ** obtained, but existing SHARED locks are allowed to persist. A process
ds@1952
  1140
  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
ds@1952
  1141
  ** This property is used by the algorithm for rolling back a journal file
ds@1952
  1142
  ** after a crash.
ds@1952
  1143
  **
ds@1952
  1144
  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
ds@1952
  1145
  ** implemented by obtaining a write-lock on the entire 'shared byte
ds@1952
  1146
  ** range'. Since all other locks require a read-lock on one of the bytes
ds@1952
  1147
  ** within this range, this ensures that no other locks are held on the
ds@1952
  1148
  ** database. 
ds@1952
  1149
  **
ds@1952
  1150
  ** The reason a single byte cannot be used instead of the 'shared byte
ds@1952
  1151
  ** range' is that some versions of windows do not support read-locks. By
ds@1952
  1152
  ** locking a random byte from a range, concurrent SHARED locks may exist
ds@1952
  1153
  ** even if the locking primitive used is always a write-lock.
ds@1952
  1154
  */
ds@1952
  1155
  int rc = SQLITE_OK;
ds@1952
  1156
  unixFile *pFile = (unixFile*)id;
ds@1952
  1157
  struct lockInfo *pLock = pFile->pLock;
ds@1952
  1158
  struct flock lock;
ds@1952
  1159
  int s;
ds@1952
  1160
ds@1952
  1161
  assert( pFile );
ds@1952
  1162
  OSTRACE7("LOCK    %d %s was %s(%s,%d) pid=%d\n", pFile->h,
ds@1952
  1163
      locktypeName(locktype), locktypeName(pFile->locktype),
ds@1952
  1164
      locktypeName(pLock->locktype), pLock->cnt , getpid());
ds@1952
  1165
ds@1952
  1166
  /* If there is already a lock of this type or more restrictive on the
ds@1952
  1167
  ** unixFile, do nothing. Don't use the end_lock: exit path, as
ds@1952
  1168
  ** enterMutex() hasn't been called yet.
ds@1952
  1169
  */
ds@1952
  1170
  if( pFile->locktype>=locktype ){
ds@1952
  1171
    OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
ds@1952
  1172
            locktypeName(locktype));
ds@1952
  1173
    return SQLITE_OK;
ds@1952
  1174
  }
ds@1952
  1175
ds@1952
  1176
  /* Make sure the locking sequence is correct
ds@1952
  1177
  */
ds@1952
  1178
  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
ds@1952
  1179
  assert( locktype!=PENDING_LOCK );
ds@1952
  1180
  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
ds@1952
  1181
ds@1952
  1182
  /* This mutex is needed because pFile->pLock is shared across threads
ds@1952
  1183
  */
ds@1952
  1184
  enterMutex();
ds@1952
  1185
ds@1952
  1186
  /* Make sure the current thread owns the pFile.
ds@1952
  1187
  */
ds@1952
  1188
  rc = transferOwnership(pFile);
ds@1952
  1189
  if( rc!=SQLITE_OK ){
ds@1952
  1190
    leaveMutex();
ds@1952
  1191
    return rc;
ds@1952
  1192
  }
ds@1952
  1193
  pLock = pFile->pLock;
ds@1952
  1194
ds@1952
  1195
  /* If some thread using this PID has a lock via a different unixFile*
ds@1952
  1196
  ** handle that precludes the requested lock, return BUSY.
ds@1952
  1197
  */
ds@1952
  1198
  if( (pFile->locktype!=pLock->locktype && 
ds@1952
  1199
          (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
ds@1952
  1200
  ){
ds@1952
  1201
    rc = SQLITE_BUSY;
ds@1952
  1202
    goto end_lock;
ds@1952
  1203
  }
ds@1952
  1204
ds@1952
  1205
  /* If a SHARED lock is requested, and some thread using this PID already
ds@1952
  1206
  ** has a SHARED or RESERVED lock, then increment reference counts and
ds@1952
  1207
  ** return SQLITE_OK.
ds@1952
  1208
  */
ds@1952
  1209
  if( locktype==SHARED_LOCK && 
ds@1952
  1210
      (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
ds@1952
  1211
    assert( locktype==SHARED_LOCK );
ds@1952
  1212
    assert( pFile->locktype==0 );
ds@1952
  1213
    assert( pLock->cnt>0 );
ds@1952
  1214
    pFile->locktype = SHARED_LOCK;
ds@1952
  1215
    pLock->cnt++;
ds@1952
  1216
    pFile->pOpen->nLock++;
ds@1952
  1217
    goto end_lock;
ds@1952
  1218
  }
ds@1952
  1219
ds@1952
  1220
  lock.l_len = 1L;
ds@1952
  1221
ds@1952
  1222
  lock.l_whence = SEEK_SET;
ds@1952
  1223
ds@1952
  1224
  /* A PENDING lock is needed before acquiring a SHARED lock and before
ds@1952
  1225
  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
ds@1952
  1226
  ** be released.
ds@1952
  1227
  */
ds@1952
  1228
  if( locktype==SHARED_LOCK 
ds@1952
  1229
      || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
ds@1952
  1230
  ){
ds@1952
  1231
    lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
ds@1952
  1232
    lock.l_start = PENDING_BYTE;
ds@1952
  1233
    s = fcntl(pFile->h, F_SETLK, &lock);
ds@1952
  1234
    if( s==(-1) ){
ds@1952
  1235
      rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
ds@1952
  1236
      goto end_lock;
ds@1952
  1237
    }
ds@1952
  1238
  }
ds@1952
  1239
ds@1952
  1240
ds@1952
  1241
  /* If control gets to this point, then actually go ahead and make
ds@1952
  1242
  ** operating system calls for the specified lock.
ds@1952
  1243
  */
ds@1952
  1244
  if( locktype==SHARED_LOCK ){
ds@1952
  1245
    assert( pLock->cnt==0 );
ds@1952
  1246
    assert( pLock->locktype==0 );
ds@1952
  1247
ds@1952
  1248
    /* Now get the read-lock */
ds@1952
  1249
    lock.l_start = SHARED_FIRST;
ds@1952
  1250
    lock.l_len = SHARED_SIZE;
ds@1952
  1251
    s = fcntl(pFile->h, F_SETLK, &lock);
ds@1952
  1252
ds@1952
  1253
    /* Drop the temporary PENDING lock */
ds@1952
  1254
    lock.l_start = PENDING_BYTE;
ds@1952
  1255
    lock.l_len = 1L;
ds@1952
  1256
    lock.l_type = F_UNLCK;
ds@1952
  1257
    if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
ds@1952
  1258
      rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
ds@1952
  1259
      goto end_lock;
ds@1952
  1260
    }
ds@1952
  1261
    if( s==(-1) ){
ds@1952
  1262
      rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
ds@1952
  1263
    }else{
ds@1952
  1264
      pFile->locktype = SHARED_LOCK;
ds@1952
  1265
      pFile->pOpen->nLock++;
ds@1952
  1266
      pLock->cnt = 1;
ds@1952
  1267
    }
ds@1952
  1268
  }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
ds@1952
  1269
    /* We are trying for an exclusive lock but another thread in this
ds@1952
  1270
    ** same process is still holding a shared lock. */
ds@1952
  1271
    rc = SQLITE_BUSY;
ds@1952
  1272
  }else{
ds@1952
  1273
    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
ds@1952
  1274
    ** assumed that there is a SHARED or greater lock on the file
ds@1952
  1275
    ** already.
ds@1952
  1276
    */
ds@1952
  1277
    assert( 0!=pFile->locktype );
ds@1952
  1278
    lock.l_type = F_WRLCK;
ds@1952
  1279
    switch( locktype ){
ds@1952
  1280
      case RESERVED_LOCK:
ds@1952
  1281
        lock.l_start = RESERVED_BYTE;
ds@1952
  1282
        break;
ds@1952
  1283
      case EXCLUSIVE_LOCK:
ds@1952
  1284
        lock.l_start = SHARED_FIRST;
ds@1952
  1285
        lock.l_len = SHARED_SIZE;
ds@1952
  1286
        break;
ds@1952
  1287
      default:
ds@1952
  1288
        assert(0);
ds@1952
  1289
    }
ds@1952
  1290
    s = fcntl(pFile->h, F_SETLK, &lock);
ds@1952
  1291
    if( s==(-1) ){
ds@1952
  1292
      rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
ds@1952
  1293
    }
ds@1952
  1294
  }
ds@1952
  1295
  
ds@1952
  1296
  if( rc==SQLITE_OK ){
ds@1952
  1297
    pFile->locktype = locktype;
ds@1952
  1298
    pLock->locktype = locktype;
ds@1952
  1299
  }else if( locktype==EXCLUSIVE_LOCK ){
ds@1952
  1300
    pFile->locktype = PENDING_LOCK;
ds@1952
  1301
    pLock->locktype = PENDING_LOCK;
ds@1952
  1302
  }
ds@1952
  1303
ds@1952
  1304
end_lock:
ds@1952
  1305
  leaveMutex();
ds@1952
  1306
  OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
ds@1952
  1307
      rc==SQLITE_OK ? "ok" : "failed");
ds@1952
  1308
  return rc;
ds@1952
  1309
}
ds@1952
  1310
ds@1952
  1311
/*
ds@1952
  1312
** Lower the locking level on file descriptor pFile to locktype.  locktype
ds@1952
  1313
** must be either NO_LOCK or SHARED_LOCK.
ds@1952
  1314
**
ds@1952
  1315
** If the locking level of the file descriptor is already at or below
ds@1952
  1316
** the requested locking level, this routine is a no-op.
ds@1952
  1317
*/
ds@1952
  1318
static int unixUnlock(sqlite3_file *id, int locktype){
ds@1952
  1319
  struct lockInfo *pLock;
ds@1952
  1320
  struct flock lock;
ds@1952
  1321
  int rc = SQLITE_OK;
ds@1952
  1322
  unixFile *pFile = (unixFile*)id;
ds@1952
  1323
ds@1952
  1324
  assert( pFile );
ds@1952
  1325
  OSTRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d\n", pFile->h, locktype,
ds@1952
  1326
      pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
ds@1952
  1327
ds@1952
  1328
  assert( locktype<=SHARED_LOCK );
ds@1952
  1329
  if( pFile->locktype<=locktype ){
ds@1952
  1330
    return SQLITE_OK;
ds@1952
  1331
  }
ds@1952
  1332
  if( CHECK_THREADID(pFile) ){
ds@1952
  1333
    return SQLITE_MISUSE;
ds@1952
  1334
  }
ds@1952
  1335
  enterMutex();
ds@1952
  1336
  pLock = pFile->pLock;
ds@1952
  1337
  assert( pLock->cnt!=0 );
ds@1952
  1338
  if( pFile->locktype>SHARED_LOCK ){
ds@1952
  1339
    assert( pLock->locktype==pFile->locktype );
ds@1952
  1340
    if( locktype==SHARED_LOCK ){
ds@1952
  1341
      lock.l_type = F_RDLCK;
ds@1952
  1342
      lock.l_whence = SEEK_SET;
ds@1952
  1343
      lock.l_start = SHARED_FIRST;
ds@1952
  1344
      lock.l_len = SHARED_SIZE;
ds@1952
  1345
      if( fcntl(pFile->h, F_SETLK, &lock)==(-1) ){
ds@1952
  1346
        /* This should never happen */
ds@1952
  1347
        rc = SQLITE_IOERR_RDLOCK;
ds@1952
  1348
      }
ds@1952
  1349
    }
ds@1952
  1350
    lock.l_type = F_UNLCK;
ds@1952
  1351
    lock.l_whence = SEEK_SET;
ds@1952
  1352
    lock.l_start = PENDING_BYTE;
ds@1952
  1353
    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
ds@1952
  1354
    if( fcntl(pFile->h, F_SETLK, &lock)!=(-1) ){
ds@1952
  1355
      pLock->locktype = SHARED_LOCK;
ds@1952
  1356
    }else{
ds@1952
  1357
      rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
ds@1952
  1358
    }
ds@1952
  1359
  }
ds@1952
  1360
  if( locktype==NO_LOCK ){
ds@1952
  1361
    struct openCnt *pOpen;
ds@1952
  1362
ds@1952
  1363
    /* Decrement the shared lock counter.  Release the lock using an
ds@1952
  1364
    ** OS call only when all threads in this same process have released
ds@1952
  1365
    ** the lock.
ds@1952
  1366
    */
ds@1952
  1367
    pLock->cnt--;
ds@1952
  1368
    if( pLock->cnt==0 ){
ds@1952
  1369
      lock.l_type = F_UNLCK;
ds@1952
  1370
      lock.l_whence = SEEK_SET;
ds@1952
  1371
      lock.l_start = lock.l_len = 0L;
ds@1952
  1372
      if( fcntl(pFile->h, F_SETLK, &lock)!=(-1) ){
ds@1952
  1373
        pLock->locktype = NO_LOCK;
ds@1952
  1374
      }else{
ds@1952
  1375
        rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
ds@1952
  1376
      }
ds@1952
  1377
    }
ds@1952
  1378
ds@1952
  1379
    /* Decrement the count of locks against this same file.  When the
ds@1952
  1380
    ** count reaches zero, close any other file descriptors whose close
ds@1952
  1381
    ** was deferred because of outstanding locks.
ds@1952
  1382
    */
ds@1952
  1383
    pOpen = pFile->pOpen;
ds@1952
  1384
    pOpen->nLock--;
ds@1952
  1385
    assert( pOpen->nLock>=0 );
ds@1952
  1386
    if( pOpen->nLock==0 && pOpen->nPending>0 ){
ds@1952
  1387
      int i;
ds@1952
  1388
      for(i=0; i<pOpen->nPending; i++){
ds@1952
  1389
        close(pOpen->aPending[i]);
ds@1952
  1390
      }
ds@1952
  1391
      free(pOpen->aPending);
ds@1952
  1392
      pOpen->nPending = 0;
ds@1952
  1393
      pOpen->aPending = 0;
ds@1952
  1394
    }
ds@1952
  1395
  }
ds@1952
  1396
  leaveMutex();
ds@1952
  1397
  pFile->locktype = locktype;
ds@1952
  1398
  return rc;
ds@1952
  1399
}
ds@1952
  1400
ds@1952
  1401
/*
ds@1952
  1402
** Close a file.
ds@1952
  1403
*/
ds@1952
  1404
static int unixClose(sqlite3_file *id){
ds@1952
  1405
  unixFile *pFile = (unixFile *)id;
ds@1952
  1406
  if( !pFile ) return SQLITE_OK;
ds@1952
  1407
  unixUnlock(id, NO_LOCK);
ds@1952
  1408
  if( pFile->dirfd>=0 ) close(pFile->dirfd);
ds@1952
  1409
  pFile->dirfd = -1;
ds@1952
  1410
  enterMutex();
ds@1952
  1411
ds@1952
  1412
  if( pFile->pOpen->nLock ){
ds@1952
  1413
    /* If there are outstanding locks, do not actually close the file just
ds@1952
  1414
    ** yet because that would clear those locks.  Instead, add the file
ds@1952
  1415
    ** descriptor to pOpen->aPending.  It will be automatically closed when
ds@1952
  1416
    ** the last lock is cleared.
ds@1952
  1417
    */
ds@1952
  1418
    int *aNew;
ds@1952
  1419
    struct openCnt *pOpen = pFile->pOpen;
ds@1952
  1420
    aNew = realloc( pOpen->aPending, (pOpen->nPending+1)*sizeof(int) );
ds@1952
  1421
    if( aNew==0 ){
ds@1952
  1422
      /* If a malloc fails, just leak the file descriptor */
ds@1952
  1423
    }else{
ds@1952
  1424
      pOpen->aPending = aNew;
ds@1952
  1425
      pOpen->aPending[pOpen->nPending] = pFile->h;
ds@1952
  1426
      pOpen->nPending++;
ds@1952
  1427
    }
ds@1952
  1428
  }else{
ds@1952
  1429
    /* There are no outstanding locks so we can close the file immediately */
ds@1952
  1430
    close(pFile->h);
ds@1952
  1431
  }
ds@1952
  1432
  releaseLockInfo(pFile->pLock);
ds@1952
  1433
  releaseOpenCnt(pFile->pOpen);
ds@1952
  1434
ds@1952
  1435
  leaveMutex();
ds@1952
  1436
  OSTRACE2("CLOSE   %-3d\n", pFile->h);
ds@1952
  1437
  OpenCounter(-1);
ds@1952
  1438
  memset(pFile, 0, sizeof(unixFile));
ds@1952
  1439
  return SQLITE_OK;
ds@1952
  1440
}
ds@1952
  1441
ds@1952
  1442
ds@1952
  1443
#ifdef SQLITE_ENABLE_LOCKING_STYLE
ds@1952
  1444
#pragma mark AFP Support
ds@1952
  1445
ds@1952
  1446
/*
ds@1952
  1447
 ** The afpLockingContext structure contains all afp lock specific state
ds@1952
  1448
 */
ds@1952
  1449
typedef struct afpLockingContext afpLockingContext;
ds@1952
  1450
struct afpLockingContext {
ds@1952
  1451
  unsigned long long sharedLockByte;
ds@1952
  1452
  char *filePath;
ds@1952
  1453
};
ds@1952
  1454
ds@1952
  1455
struct ByteRangeLockPB2
ds@1952
  1456
{
ds@1952
  1457
  unsigned long long offset;        /* offset to first byte to lock */
ds@1952
  1458
  unsigned long long length;        /* nbr of bytes to lock */
ds@1952
  1459
  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
ds@1952
  1460
  unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
ds@1952
  1461
  unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
ds@1952
  1462
  int fd;                           /* file desc to assoc this lock with */
ds@1952
  1463
};
ds@1952
  1464
ds@1952
  1465
#define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
ds@1952
  1466
ds@1952
  1467
/* 
ds@1952
  1468
** Return 0 on success, 1 on failure.  To match the behavior of the 
ds@1952
  1469
** normal posix file locking (used in unixLock for example), we should 
ds@1952
  1470
** provide 'richer' return codes - specifically to differentiate between
ds@1952
  1471
** 'file busy' and 'file system error' results.
ds@1952
  1472
*/
ds@1952
  1473
static int _AFPFSSetLock(
ds@1952
  1474
  const char *path, 
ds@1952
  1475
  int fd, 
ds@1952
  1476
  unsigned long long offset, 
ds@1952
  1477
  unsigned long long length, 
ds@1952
  1478
  int setLockFlag
ds@1952
  1479
){
ds@1952
  1480
  struct ByteRangeLockPB2       pb;
ds@1952
  1481
  int                     err;
ds@1952
  1482
  
ds@1952
  1483
  pb.unLockFlag = setLockFlag ? 0 : 1;
ds@1952
  1484
  pb.startEndFlag = 0;
ds@1952
  1485
  pb.offset = offset;
ds@1952
  1486
  pb.length = length; 
ds@1952
  1487
  pb.fd = fd;
ds@1952
  1488
  OSTRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n", 
ds@1952
  1489
    (setLockFlag?"ON":"OFF"), fd, offset, length);
ds@1952
  1490
  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
ds@1952
  1491
  if ( err==-1 ) {
ds@1952
  1492
    OSTRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, errno, 
ds@1952
  1493
      strerror(errno));
ds@1952
  1494
    return 1; /* error */
ds@1952
  1495
  } else {
ds@1952
  1496
    return 0;
ds@1952
  1497
  }
ds@1952
  1498
}
ds@1952
  1499
ds@1952
  1500
/*
ds@1952
  1501
 ** This routine checks if there is a RESERVED lock held on the specified
ds@1952
  1502
 ** file by this or any other process. If such a lock is held, return
ds@1952
  1503
 ** non-zero.  If the file is unlocked or holds only SHARED locks, then
ds@1952
  1504
 ** return zero.
ds@1952
  1505
 */
ds@1952
  1506
static int afpUnixCheckReservedLock(sqlite3_file *id){
ds@1952
  1507
  int r = 0;
ds@1952
  1508
  unixFile *pFile = (unixFile*)id;
ds@1952
  1509
  
ds@1952
  1510
  assert( pFile ); 
ds@1952
  1511
  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
ds@1952
  1512
  
ds@1952
  1513
  /* Check if a thread in this process holds such a lock */
ds@1952
  1514
  if( pFile->locktype>SHARED_LOCK ){
ds@1952
  1515
    r = 1;
ds@1952
  1516
  }
ds@1952
  1517
  
ds@1952
  1518
  /* Otherwise see if some other process holds it.
ds@1952
  1519
   */
ds@1952
  1520
  if ( !r ) {
ds@1952
  1521
    /* lock the byte */
ds@1952
  1522
    int failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);  
ds@1952
  1523
    if (failed) {
ds@1952
  1524
      /* if we failed to get the lock then someone else must have it */
ds@1952
  1525
      r = 1;
ds@1952
  1526
    } else {
ds@1952
  1527
      /* if we succeeded in taking the reserved lock, unlock it to restore
ds@1952
  1528
      ** the original state */
ds@1952
  1529
      _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0);
ds@1952
  1530
    }
ds@1952
  1531
  }
ds@1952
  1532
  OSTRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
ds@1952
  1533
  
ds@1952
  1534
  return r;
ds@1952
  1535
}
ds@1952
  1536
ds@1952
  1537
/* AFP-style locking following the behavior of unixLock, see the unixLock 
ds@1952
  1538
** function comments for details of lock management. */
ds@1952
  1539
static int afpUnixLock(sqlite3_file *id, int locktype)
ds@1952
  1540
{
ds@1952
  1541
  int rc = SQLITE_OK;
ds@1952
  1542
  unixFile *pFile = (unixFile*)id;
ds@1952
  1543
  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
ds@1952
  1544
  int gotPendingLock = 0;
ds@1952
  1545
  
ds@1952
  1546
  assert( pFile );
ds@1952
  1547
  OSTRACE5("LOCK    %d %s was %s pid=%d\n", pFile->h,
ds@1952
  1548
         locktypeName(locktype), locktypeName(pFile->locktype), getpid());  
ds@1952
  1549
  /* If there is already a lock of this type or more restrictive on the
ds@1952
  1550
    ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
ds@1952
  1551
    ** enterMutex() hasn't been called yet.
ds@1952
  1552
    */
ds@1952
  1553
  if( pFile->locktype>=locktype ){
ds@1952
  1554
    OSTRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
ds@1952
  1555
           locktypeName(locktype));
ds@1952
  1556
    return SQLITE_OK;
ds@1952
  1557
  }
ds@1952
  1558
ds@1952
  1559
  /* Make sure the locking sequence is correct
ds@1952
  1560
    */
ds@1952
  1561
  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
ds@1952
  1562
  assert( locktype!=PENDING_LOCK );
ds@1952
  1563
  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
ds@1952
  1564
  
ds@1952
  1565
  /* This mutex is needed because pFile->pLock is shared across threads
ds@1952
  1566
    */
ds@1952
  1567
  enterMutex();
ds@1952
  1568
ds@1952
  1569
  /* Make sure the current thread owns the pFile.
ds@1952
  1570
    */
ds@1952
  1571
  rc = transferOwnership(pFile);
ds@1952
  1572
  if( rc!=SQLITE_OK ){
ds@1952
  1573
    leaveMutex();
ds@1952
  1574
    return rc;
ds@1952
  1575
  }
ds@1952
  1576
    
ds@1952
  1577
  /* A PENDING lock is needed before acquiring a SHARED lock and before
ds@1952
  1578
    ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
ds@1952
  1579
    ** be released.
ds@1952
  1580
    */
ds@1952
  1581
  if( locktype==SHARED_LOCK 
ds@1952
  1582
      || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
ds@1952
  1583
      ){
ds@1952
  1584
    int failed = _AFPFSSetLock(context->filePath, pFile->h, 
ds@1952
  1585
      PENDING_BYTE, 1, 1);
ds@1952
  1586
    if (failed) {
ds@1952
  1587
      rc = SQLITE_BUSY;
ds@1952
  1588
      goto afp_end_lock;
ds@1952
  1589
    }
ds@1952
  1590
  }
ds@1952
  1591
  
ds@1952
  1592
  /* If control gets to this point, then actually go ahead and make
ds@1952
  1593
    ** operating system calls for the specified lock.
ds@1952
  1594
    */
ds@1952
  1595
  if( locktype==SHARED_LOCK ){
ds@1952
  1596
    int lk, failed;
ds@1952
  1597
    int tries = 0;
ds@1952
  1598
    
ds@1952
  1599
    /* Now get the read-lock */
ds@1952
  1600
    /* note that the quality of the randomness doesn't matter that much */
ds@1952
  1601
    lk = random(); 
ds@1952
  1602
    context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
ds@1952
  1603
    failed = _AFPFSSetLock(context->filePath, pFile->h, 
ds@1952
  1604
      SHARED_FIRST+context->sharedLockByte, 1, 1);
ds@1952
  1605
    
ds@1952
  1606
    /* Drop the temporary PENDING lock */
ds@1952
  1607
    if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)) {
ds@1952
  1608
      rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
ds@1952
  1609
      goto afp_end_lock;
ds@1952
  1610
    }
ds@1952
  1611
    
ds@1952
  1612
    if( failed ){
ds@1952
  1613
      rc = SQLITE_BUSY;
ds@1952
  1614
    } else {
ds@1952
  1615
      pFile->locktype = SHARED_LOCK;
ds@1952
  1616
    }
ds@1952
  1617
  }else{
ds@1952
  1618
    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
ds@1952
  1619
    ** assumed that there is a SHARED or greater lock on the file
ds@1952
  1620
    ** already.
ds@1952
  1621
    */
ds@1952
  1622
    int failed = 0;
ds@1952
  1623
    assert( 0!=pFile->locktype );
ds@1952
  1624
    if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
ds@1952
  1625
        /* Acquire a RESERVED lock */
ds@1952
  1626
        failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
ds@1952
  1627
    }
ds@1952
  1628
    if (!failed && locktype == EXCLUSIVE_LOCK) {
ds@1952
  1629
      /* Acquire an EXCLUSIVE lock */
ds@1952
  1630
        
ds@1952
  1631
      /* Remove the shared lock before trying the range.  we'll need to 
ds@1952
  1632
      ** reestablish the shared lock if we can't get the  afpUnixUnlock
ds@1952
  1633
      */
ds@1952
  1634
      if (!_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
ds@1952
  1635
                         context->sharedLockByte, 1, 0)) {
ds@1952
  1636
        /* now attemmpt to get the exclusive lock range */
ds@1952
  1637
        failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST, 
ds@1952
  1638
                               SHARED_SIZE, 1);
ds@1952
  1639
        if (failed && _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
ds@1952
  1640
                                    context->sharedLockByte, 1, 1)) {
ds@1952
  1641
          rc = SQLITE_IOERR_RDLOCK; /* this should never happen */
ds@1952
  1642
        }
ds@1952
  1643
      } else {
ds@1952
  1644
        /* */
ds@1952
  1645
        rc = SQLITE_IOERR_UNLOCK; /* this should never happen */
ds@1952
  1646
      }
ds@1952
  1647
    }
ds@1952
  1648
    if( failed && rc == SQLITE_OK){
ds@1952
  1649
      rc = SQLITE_BUSY;
ds@1952
  1650
    }
ds@1952
  1651
  }
ds@1952
  1652
  
ds@1952
  1653
  if( rc==SQLITE_OK ){
ds@1952
  1654
    pFile->locktype = locktype;
ds@1952
  1655
  }else if( locktype==EXCLUSIVE_LOCK ){
ds@1952
  1656
    pFile->locktype = PENDING_LOCK;
ds@1952
  1657
  }
ds@1952
  1658
  
ds@1952
  1659
afp_end_lock:
ds@1952
  1660
    leaveMutex();
ds@1952
  1661
  OSTRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
ds@1952
  1662
         rc==SQLITE_OK ? "ok" : "failed");
ds@1952
  1663
  return rc;
ds@1952
  1664
}
ds@1952
  1665
ds@1952
  1666
/*
ds@1952
  1667
 ** Lower the locking level on file descriptor pFile to locktype.  locktype
ds@1952
  1668
 ** must be either NO_LOCK or SHARED_LOCK.
ds@1952
  1669
 **
ds@1952
  1670
 ** If the locking level of the file descriptor is already at or below
ds@1952
  1671
 ** the requested locking level, this routine is a no-op.
ds@1952
  1672
 */
ds@1952
  1673
static int afpUnixUnlock(sqlite3_file *id, int locktype) {
ds@1952
  1674
  struct flock lock;
ds@1952
  1675
  int rc = SQLITE_OK;
ds@1952
  1676
  unixFile *pFile = (unixFile*)id;
ds@1952
  1677
  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
ds@1952
  1678
ds@1952
  1679
  assert( pFile );
ds@1952
  1680
  OSTRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
ds@1952
  1681
         pFile->locktype, getpid());
ds@1952
  1682
  
ds@1952
  1683
  assert( locktype<=SHARED_LOCK );
ds@1952
  1684
  if( pFile->locktype<=locktype ){
ds@1952
  1685
    return SQLITE_OK;
ds@1952
  1686
  }
ds@1952
  1687
  if( CHECK_THREADID(pFile) ){
ds@1952
  1688
    return SQLITE_MISUSE;
ds@1952
  1689
  }
ds@1952
  1690
  enterMutex();
ds@1952
  1691
  if( pFile->locktype>SHARED_LOCK ){
ds@1952
  1692
    if( locktype==SHARED_LOCK ){
ds@1952
  1693
      int failed = 0;
ds@1952
  1694
ds@1952
  1695
      /* unlock the exclusive range - then re-establish the shared lock */
ds@1952
  1696
      if (pFile->locktype==EXCLUSIVE_LOCK) {
ds@1952
  1697
        failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST, 
ds@1952
  1698
                                 SHARED_SIZE, 0);
ds@1952
  1699
        if (!failed) {
ds@1952
  1700
          /* successfully removed the exclusive lock */
ds@1952
  1701
          if (_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST+
ds@1952
  1702
                            context->sharedLockByte, 1, 1)) {
ds@1952
  1703
            /* failed to re-establish our shared lock */
ds@1952
  1704
            rc = SQLITE_IOERR_RDLOCK; /* This should never happen */
ds@1952
  1705
          }
ds@1952
  1706
        } else {
ds@1952
  1707
          /* This should never happen - failed to unlock the exclusive range */
ds@1952
  1708
          rc = SQLITE_IOERR_UNLOCK;
ds@1952
  1709
        } 
ds@1952
  1710
      }
ds@1952
  1711
    }
ds@1952
  1712
    if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
ds@1952
  1713
      if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)){
ds@1952
  1714
        /* failed to release the pending lock */
ds@1952
  1715
        rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
ds@1952
  1716
      }
ds@1952
  1717
    } 
ds@1952
  1718
    if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
ds@1952
  1719
      if (_AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0)) {
ds@1952
  1720
        /* failed to release the reserved lock */
ds@1952
  1721
        rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
ds@1952
  1722
      }
ds@1952
  1723
    } 
ds@1952
  1724
  }
ds@1952
  1725
  if( locktype==NO_LOCK ){
ds@1952
  1726
    int failed = _AFPFSSetLock(context->filePath, pFile->h, 
ds@1952
  1727
                               SHARED_FIRST + context->sharedLockByte, 1, 0);
ds@1952
  1728
    if (failed) {
ds@1952
  1729
      rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
ds@1952
  1730
    }
ds@1952
  1731
  }
ds@1952
  1732
  if (rc == SQLITE_OK)
ds@1952
  1733
    pFile->locktype = locktype;
ds@1952
  1734
  leaveMutex();
ds@1952
  1735
  return rc;
ds@1952
  1736
}
ds@1952
  1737
ds@1952
  1738
/*
ds@1952
  1739
 ** Close a file & cleanup AFP specific locking context 
ds@1952
  1740
 */
ds@1952
  1741
static int afpUnixClose(sqlite3_file *id) {
ds@1952
  1742
  unixFile *pFile = (unixFile*)pId;
ds@1952
  1743
ds@1952
  1744
  if( !pFile ) return SQLITE_OK;
ds@1952
  1745
  afpUnixUnlock(*pId, NO_LOCK);
ds@1952
  1746
  /* free the AFP locking structure */
ds@1952
  1747
  if (pFile->lockingContext != NULL) {
ds@1952
  1748
    if (((afpLockingContext *)pFile->lockingContext)->filePath != NULL)
ds@1952
  1749
      sqlite3_free(((afpLockingContext*)pFile->lockingContext)->filePath);
ds@1952
  1750
    sqlite3_free(pFile->lockingContext);
ds@1952
  1751
  }
ds@1952
  1752
ds@1952
  1753
  if( pFile->dirfd>=0 ) close(pFile->dirfd);
ds@1952
  1754
  pFile->dirfd = -1;
ds@1952
  1755
  close(pFile->h);
ds@1952
  1756
  OSTRACE2("CLOSE   %-3d\n", pFile->h);
ds@1952
  1757
  OpenCounter(-1);
ds@1952
  1758
  return SQLITE_OK;
ds@1952
  1759
}
ds@1952
  1760
ds@1952
  1761
ds@1952
  1762
#pragma mark flock() style locking
ds@1952
  1763
ds@1952
  1764
/*
ds@1952
  1765
 ** The flockLockingContext is not used
ds@1952
  1766
 */
ds@1952
  1767
typedef void flockLockingContext;
ds@1952
  1768
ds@1952
  1769
static int flockUnixCheckReservedLock(sqlite3_file *id) {
ds@1952
  1770
  unixFile *pFile = (unixFile*)id;
ds@1952
  1771
  
ds@1952
  1772
  if (pFile->locktype == RESERVED_LOCK) {
ds@1952
  1773
    return 1; /* already have a reserved lock */
ds@1952
  1774
  } else {
ds@1952
  1775
    /* attempt to get the lock */
ds@1952
  1776
    int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
ds@1952
  1777
    if (!rc) {
ds@1952
  1778
      /* got the lock, unlock it */
ds@1952
  1779
      flock(pFile->h, LOCK_UN);
ds@1952
  1780
      return 0;  /* no one has it reserved */
ds@1952
  1781
    }
ds@1952
  1782
    return 1; /* someone else might have it reserved */
ds@1952
  1783
  }
ds@1952
  1784
}
ds@1952
  1785
ds@1952
  1786
static int flockUnixLock(sqlite3_file *id, int locktype) {
ds@1952
  1787
  unixFile *pFile = (unixFile*)id;
ds@1952
  1788
  
ds@1952
  1789
  /* if we already have a lock, it is exclusive.  
ds@1952
  1790
  ** Just adjust level and punt on outta here. */
ds@1952
  1791
  if (pFile->locktype > NO_LOCK) {
ds@1952
  1792
    pFile->locktype = locktype;
ds@1952
  1793
    return SQLITE_OK;
ds@1952
  1794
  }
ds@1952
  1795
  
ds@1952
  1796
  /* grab an exclusive lock */
ds@1952
  1797
  int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
ds@1952
  1798
  if (rc) {
ds@1952
  1799
    /* didn't get, must be busy */
ds@1952
  1800
    return SQLITE_BUSY;
ds@1952
  1801
  } else {
ds@1952
  1802
    /* got it, set the type and return ok */
ds@1952
  1803
    pFile->locktype = locktype;
ds@1952
  1804
    return SQLITE_OK;
ds@1952
  1805
  }
ds@1952
  1806
}
ds@1952
  1807
ds@1952
  1808
static int flockUnixUnlock(sqlite3_file *id, int locktype) {
ds@1952
  1809
  unixFile *pFile = (unixFile*)id;
ds@1952
  1810
  
ds@1952
  1811
  assert( locktype<=SHARED_LOCK );
ds@1952
  1812
  
ds@1952
  1813
  /* no-op if possible */
ds@1952
  1814
  if( pFile->locktype==locktype ){
ds@1952
  1815
    return SQLITE_OK;
ds@1952
  1816
  }
ds@1952
  1817
  
ds@1952
  1818
  /* shared can just be set because we always have an exclusive */
ds@1952
  1819
  if (locktype==SHARED_LOCK) {
ds@1952
  1820
    pFile->locktype = locktype;
ds@1952
  1821
    return SQLITE_OK;
ds@1952
  1822
  }
ds@1952
  1823
  
ds@1952
  1824
  /* no, really, unlock. */
ds@1952
  1825
  int rc = flock(pFile->h, LOCK_UN);
ds@1952
  1826
  if (rc)
ds@1952
  1827
    return SQLITE_IOERR_UNLOCK;
ds@1952
  1828
  else {
ds@1952
  1829
    pFile->locktype = NO_LOCK;
ds@1952
  1830
    return SQLITE_OK;
ds@1952
  1831
  }
ds@1952
  1832
}
ds@1952
  1833
ds@1952
  1834
/*
ds@1952
  1835
 ** Close a file.
ds@1952
  1836
 */
ds@1952
  1837
static int flockUnixClose(sqlite3_file *pId) {
ds@1952
  1838
  unixFile *pFile = (unixFile*)*pId;
ds@1952
  1839
  
ds@1952
  1840
  if( !pFile ) return SQLITE_OK;
ds@1952
  1841
  flockUnixUnlock(*pId, NO_LOCK);
ds@1952
  1842
  
ds@1952
  1843
  if( pFile->dirfd>=0 ) close(pFile->dirfd);
ds@1952
  1844
  pFile->dirfd = -1;
ds@1952
  1845
  enterMutex();
ds@1952
  1846
  
ds@1952
  1847
  close(pFile->h);  
ds@1952
  1848
  leaveMutex();
ds@1952
  1849
  OSTRACE2("CLOSE   %-3d\n", pFile->h);
ds@1952
  1850
  OpenCounter(-1);
ds@1952
  1851
  return SQLITE_OK;
ds@1952
  1852
}
ds@1952
  1853
ds@1952
  1854
#pragma mark Old-School .lock file based locking
ds@1952
  1855
ds@1952
  1856
/*
ds@1952
  1857
 ** The dotlockLockingContext structure contains all dotlock (.lock) lock
ds@1952
  1858
 ** specific state
ds@1952
  1859
 */
ds@1952
  1860
typedef struct dotlockLockingContext dotlockLockingContext;
ds@1952
  1861
struct dotlockLockingContext {
ds@1952
  1862
  char *lockPath;
ds@1952
  1863
};
ds@1952
  1864
ds@1952
  1865
ds@1952
  1866
static int dotlockUnixCheckReservedLock(sqlite3_file *id) {
ds@1952
  1867
  unixFile *pFile = (unixFile*)id;
ds@1952
  1868
  dotlockLockingContext *context = 
ds@1952
  1869
    (dotlockLockingContext *) pFile->lockingContext;
ds@1952
  1870
  
ds@1952
  1871
  if (pFile->locktype == RESERVED_LOCK) {
ds@1952
  1872
    return 1; /* already have a reserved lock */
ds@1952
  1873
  } else {
ds@1952
  1874
    struct stat statBuf;
ds@1952
  1875
    if (lstat(context->lockPath,&statBuf) == 0)
ds@1952
  1876
      /* file exists, someone else has the lock */
ds@1952
  1877
      return 1;
ds@1952
  1878
    else
ds@1952
  1879
      /* file does not exist, we could have it if we want it */
ds@1952
  1880
      return 0;
ds@1952
  1881
  }
ds@1952
  1882
}
ds@1952
  1883
ds@1952
  1884
static int dotlockUnixLock(sqlite3_file *id, int locktype) {
ds@1952
  1885
  unixFile *pFile = (unixFile*)id;
ds@1952
  1886
  dotlockLockingContext *context = 
ds@1952
  1887
    (dotlockLockingContext *) pFile->lockingContext;
ds@1952
  1888
  
ds@1952
  1889
  /* if we already have a lock, it is exclusive.  
ds@1952
  1890
  ** Just adjust level and punt on outta here. */
ds@1952
  1891
  if (pFile->locktype > NO_LOCK) {
ds@1952
  1892
    pFile->locktype = locktype;
ds@1952
  1893
    
ds@1952
  1894
    /* Always update the timestamp on the old file */
ds@1952
  1895
    utimes(context->lockPath,NULL);
ds@1952
  1896
    return SQLITE_OK;
ds@1952
  1897
  }
ds@1952
  1898
  
ds@1952
  1899
  /* check to see if lock file already exists */
ds@1952
  1900
  struct stat statBuf;
ds@1952
  1901
  if (lstat(context->lockPath,&statBuf) == 0){
ds@1952
  1902
    return SQLITE_BUSY; /* it does, busy */
ds@1952
  1903
  }
ds@1952
  1904
  
ds@1952
  1905
  /* grab an exclusive lock */
ds@1952
  1906
  int fd = open(context->lockPath,O_RDONLY|O_CREAT|O_EXCL,0600);
ds@1952
  1907
  if (fd < 0) {
ds@1952
  1908
    /* failed to open/create the file, someone else may have stolen the lock */
ds@1952
  1909
    return SQLITE_BUSY; 
ds@1952
  1910
  }
ds@1952
  1911
  close(fd);
ds@1952
  1912
  
ds@1952
  1913
  /* got it, set the type and return ok */
ds@1952
  1914
  pFile->locktype = locktype;
ds@1952
  1915
  return SQLITE_OK;
ds@1952
  1916
}
ds@1952
  1917
ds@1952
  1918
static int dotlockUnixUnlock(sqlite3_file *id, int locktype) {
ds@1952
  1919
  unixFile *pFile = (unixFile*)id;
ds@1952
  1920
  dotlockLockingContext *context = 
ds@1952
  1921
    (dotlockLockingContext *) pFile->lockingContext;
ds@1952
  1922
  
ds@1952
  1923
  assert( locktype<=SHARED_LOCK );
ds@1952
  1924
  
ds@1952
  1925
  /* no-op if possible */
ds@1952
  1926
  if( pFile->locktype==locktype ){
ds@1952
  1927
    return SQLITE_OK;
ds@1952
  1928
  }
ds@1952
  1929
  
ds@1952
  1930
  /* shared can just be set because we always have an exclusive */
ds@1952
  1931
  if (locktype==SHARED_LOCK) {
ds@1952
  1932
    pFile->locktype = locktype;
ds@1952
  1933
    return SQLITE_OK;
ds@1952
  1934
  }
ds@1952
  1935
  
ds@1952
  1936
  /* no, really, unlock. */
ds@1952
  1937
  unlink(context->lockPath);
ds@1952
  1938
  pFile->locktype = NO_LOCK;
ds@1952
  1939
  return SQLITE_OK;
ds@1952
  1940
}
ds@1952
  1941
ds@1952
  1942
/*
ds@1952
  1943
 ** Close a file.
ds@1952
  1944
 */
ds@1952
  1945
static int dotlockUnixClose(sqlite3_file *id) {
ds@1952
  1946
  unixFile *pFile = (unixFile*)id;
ds@1952
  1947
  
ds@1952
  1948
  if( !pFile ) return SQLITE_OK;
ds@1952
  1949
  dotlockUnixUnlock(*pId, NO_LOCK);
ds@1952
  1950
  /* free the dotlock locking structure */
ds@1952
  1951
  if (pFile->lockingContext != NULL) {
ds@1952
  1952
    if (((dotlockLockingContext *)pFile->lockingContext)->lockPath != NULL)
ds@1952
  1953
      sqlite3_free( ( (dotlockLockingContext *)
ds@1952
  1954
        pFile->lockingContext)->lockPath);
ds@1952
  1955
    sqlite3_free(pFile->lockingContext);
ds@1952
  1956
  }
ds@1952
  1957
  
ds@1952
  1958
  if( pFile->dirfd>=0 ) close(pFile->dirfd);
ds@1952
  1959
  pFile->dirfd = -1;
ds@1952
  1960
  enterMutex();
ds@1952
  1961
  
ds@1952
  1962
  close(pFile->h);
ds@1952
  1963
  
ds@1952
  1964
  leaveMutex();
ds@1952
  1965
  OSTRACE2("CLOSE   %-3d\n", pFile->h);
ds@1952
  1966
  OpenCounter(-1);
ds@1952
  1967
  return SQLITE_OK;
ds@1952
  1968
}
ds@1952
  1969
ds@1952
  1970
ds@1952
  1971
#pragma mark No locking
ds@1952
  1972
ds@1952
  1973
/*
ds@1952
  1974
 ** The nolockLockingContext is void
ds@1952
  1975
 */
ds@1952
  1976
typedef void nolockLockingContext;
ds@1952
  1977
ds@1952
  1978
static int nolockUnixCheckReservedLock(sqlite3_file *id) {
ds@1952
  1979
  return 0;
ds@1952
  1980
}
ds@1952
  1981
ds@1952
  1982
static int nolockUnixLock(sqlite3_file *id, int locktype) {
ds@1952
  1983
  return SQLITE_OK;
ds@1952
  1984
}
ds@1952
  1985
ds@1952
  1986
static int nolockUnixUnlock(sqlite3_file *id, int locktype) {
ds@1952
  1987
  return SQLITE_OK;
ds@1952
  1988
}
ds@1952
  1989
ds@1952
  1990
/*
ds@1952
  1991
 ** Close a file.
ds@1952
  1992
 */
ds@1952
  1993
static int nolockUnixClose(sqlite3_file *id) {
ds@1952
  1994
  unixFile *pFile = (unixFile*)id;
ds@1952
  1995
  
ds@1952
  1996
  if( !pFile ) return SQLITE_OK;
ds@1952
  1997
  if( pFile->dirfd>=0 ) close(pFile->dirfd);
ds@1952
  1998
  pFile->dirfd = -1;
ds@1952
  1999
  enterMutex();
ds@1952
  2000
  
ds@1952
  2001
  close(pFile->h);
ds@1952
  2002
  
ds@1952
  2003
  leaveMutex();
ds@1952
  2004
  OSTRACE2("CLOSE   %-3d\n", pFile->h);
ds@1952
  2005
  OpenCounter(-1);
ds@1952
  2006
  return SQLITE_OK;
ds@1952
  2007
}
ds@1952
  2008
ds@1952
  2009
#endif /* SQLITE_ENABLE_LOCKING_STYLE */
ds@1952
  2010
ds@1952
  2011
ds@1952
  2012
/*
ds@1952
  2013
** Information and control of an open file handle.
ds@1952
  2014
*/
ds@1952
  2015
static int unixFileControl(sqlite3_file *id, int op, void *pArg){
ds@1952
  2016
  switch( op ){
ds@1952
  2017
    case SQLITE_FCNTL_LOCKSTATE: {
ds@1952
  2018
      *(int*)pArg = ((unixFile*)id)->locktype;
ds@1952
  2019
      return SQLITE_OK;
ds@1952
  2020
    }
ds@1952
  2021
  }
ds@1952
  2022
  return SQLITE_ERROR;
ds@1952
  2023
}
ds@1952
  2024
ds@1952
  2025
/*
ds@1952
  2026
** Return the sector size in bytes of the underlying block device for
ds@1952
  2027
** the specified file. This is almost always 512 bytes, but may be
ds@1952
  2028
** larger for some devices.
ds@1952
  2029
**
ds@1952
  2030
** SQLite code assumes this function cannot fail. It also assumes that
ds@1952
  2031
** if two files are created in the same file-system directory (i.e.
ds@1952
  2032
** a database and it's journal file) that the sector size will be the
ds@1952
  2033
** same for both.
ds@1952
  2034
*/
ds@1952
  2035
static int unixSectorSize(sqlite3_file *id){
ds@1952
  2036
  return SQLITE_DEFAULT_SECTOR_SIZE;
ds@1952
  2037
}
ds@1952
  2038
ds@1952
  2039
/*
ds@1952
  2040
** Return the device characteristics for the file. This is always 0.
ds@1952
  2041
*/
ds@1952
  2042
static int unixDeviceCharacteristics(sqlite3_file *id){
ds@1952
  2043
  return 0;
ds@1952
  2044
}
ds@1952
  2045
ds@1952
  2046
/*
ds@1952
  2047
** This vector defines all the methods that can operate on an sqlite3_file
ds@1952
  2048
** for unix.
ds@1952
  2049
*/
ds@1952
  2050
static const sqlite3_io_methods sqlite3UnixIoMethod = {
ds@1952
  2051
  1,                        /* iVersion */
ds@1952
  2052
  unixClose,
ds@1952
  2053
  unixRead,
ds@1952
  2054
  unixWrite,
ds@1952
  2055
  unixTruncate,
ds@1952
  2056
  unixSync,
ds@1952
  2057
  unixFileSize,
ds@1952
  2058
  unixLock,
ds@1952
  2059
  unixUnlock,
ds@1952
  2060
  unixCheckReservedLock,
ds@1952
  2061
  unixFileControl,
ds@1952
  2062
  unixSectorSize,
ds@1952
  2063
  unixDeviceCharacteristics
ds@1952
  2064
};
ds@1952
  2065
ds@1952
  2066
#ifdef SQLITE_ENABLE_LOCKING_STYLE
ds@1952
  2067
/*
ds@1952
  2068
** This vector defines all the methods that can operate on an sqlite3_file
ds@1952
  2069
** for unix with AFP style file locking.
ds@1952
  2070
*/
ds@1952
  2071
static const sqlite3_io_methods sqlite3AFPLockingUnixIoMethod = {
ds@1952
  2072
  1,                        /* iVersion */
ds@1952
  2073
  unixClose,
ds@1952
  2074
  unixRead,
ds@1952
  2075
  unixWrite,
ds@1952
  2076
  unixTruncate,
ds@1952
  2077
  unixSync,
ds@1952
  2078
  unixFileSize,
ds@1952
  2079
  afpUnixLock,
ds@1952
  2080
  afpUnixUnlock,
ds@1952
  2081
  afpUnixCheckReservedLock,
ds@1952
  2082
  unixFileControl,
ds@1952
  2083
  unixSectorSize,
ds@1952
  2084
  unixDeviceCharacteristics
ds@1952
  2085
};
ds@1952
  2086
ds@1952
  2087
/*
ds@1952
  2088
** This vector defines all the methods that can operate on an sqlite3_file
ds@1952
  2089
** for unix with flock() style file locking.
ds@1952
  2090
*/
ds@1952
  2091
static const sqlite3_io_methods sqlite3FlockLockingUnixIoMethod = {
ds@1952
  2092
  1,                        /* iVersion */
ds@1952
  2093
  flockUnixClose,
ds@1952
  2094
  unixRead,
ds@1952
  2095
  unixWrite,
ds@1952
  2096
  unixTruncate,
ds@1952
  2097
  unixSync,
ds@1952
  2098
  unixFileSize,
ds@1952
  2099
  flockUnixLock,
ds@1952
  2100
  flockUnixUnlock,
ds@1952
  2101
  flockUnixCheckReservedLock,
ds@1952
  2102
  unixFileControl,
ds@1952
  2103
  unixSectorSize,
ds@1952
  2104
  unixDeviceCharacteristics
ds@1952
  2105
};
ds@1952
  2106
ds@1952
  2107
/*
ds@1952
  2108
** This vector defines all the methods that can operate on an sqlite3_file
ds@1952
  2109
** for unix with dotlock style file locking.
ds@1952
  2110
*/
ds@1952
  2111
static const sqlite3_io_methods sqlite3DotlockLockingUnixIoMethod = {
ds@1952
  2112
  1,                        /* iVersion */
ds@1952
  2113
  dotlockUnixClose,
ds@1952
  2114
  unixRead,
ds@1952
  2115
  unixWrite,
ds@1952
  2116
  unixTruncate,
ds@1952
  2117
  unixSync,
ds@1952
  2118
  unixFileSize,
ds@1952
  2119
  dotlockUnixLock,
ds@1952
  2120
  dotlockUnixUnlock,
ds@1952
  2121
  dotlockUnixCheckReservedLock,
ds@1952
  2122
  unixFileControl,
ds@1952
  2123
  unixSectorSize,
ds@1952
  2124
  unixDeviceCharacteristics
ds@1952
  2125
};
ds@1952
  2126
ds@1952
  2127
/*
ds@1952
  2128
** This vector defines all the methods that can operate on an sqlite3_file
ds@1952
  2129
** for unix with dotlock style file locking.
ds@1952
  2130
*/
ds@1952
  2131
static const sqlite3_io_methods sqlite3NolockLockingUnixIoMethod = {
ds@1952
  2132
  1,                        /* iVersion */
ds@1952
  2133
  nolockUnixClose,
ds@1952
  2134
  unixRead,
ds@1952
  2135
  unixWrite,
ds@1952
  2136
  unixTruncate,
ds@1952
  2137
  unixSync,
ds@1952
  2138
  unixFileSize,
ds@1952
  2139
  nolockUnixLock,
ds@1952
  2140
  nolockUnixUnlock,
ds@1952
  2141
  nolockUnixCheckReservedLock,
ds@1952
  2142
  unixFileControl,
ds@1952
  2143
  unixSectorSize,
ds@1952
  2144
  unixDeviceCharacteristics
ds@1952
  2145
};
ds@1952
  2146
ds@1952
  2147
#endif /* SQLITE_ENABLE_LOCKING_STYLE */
ds@1952
  2148
ds@1952
  2149
/*
ds@1952
  2150
** Allocate memory for a new unixFile and initialize that unixFile.
ds@1952
  2151
** Write a pointer to the new unixFile into *pId.
ds@1952
  2152
** If we run out of memory, close the file and return an error.
ds@1952
  2153
*/
ds@1952
  2154
#ifdef SQLITE_ENABLE_LOCKING_STYLE
ds@1952
  2155
/* 
ds@1952
  2156
** When locking extensions are enabled, the filepath and locking style 
ds@1952
  2157
** are needed to determine the unixFile pMethod to use for locking operations.
ds@1952
  2158
** The locking-style specific lockingContext data structure is created 
ds@1952
  2159
** and assigned here also.
ds@1952
  2160
*/
ds@1952
  2161
static int fillInUnixFile(
ds@1952
  2162
  int h,                  /* Open file descriptor of file being opened */
ds@1952
  2163
  int dirfd,              /* Directory file descriptor */
ds@1952
  2164
  sqlite3_file *pId,      /* Write completed initialization here */
ds@1952
  2165
  const char *zFilename,  /* Name of the file being opened */
ds@1952
  2166
){
ds@1952
  2167
  sqlite3LockingStyle lockingStyle;
ds@1952
  2168
  unixFile *pNew = (unixFile *)pId;
ds@1952
  2169
  int rc;
ds@1952
  2170
ds@1952
  2171
  memset(pNew, 0, sizeof(unixFile));
ds@1952
  2172
  lockingStyle = sqlite3DetectLockingStyle(zFilename, h);
ds@1952
  2173
  if ( lockingStyle == posixLockingStyle ) {
ds@1952
  2174
    enterMutex();
ds@1952
  2175
    rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
ds@1952
  2176
    leaveMutex();
ds@1952
  2177
    if( rc ){
ds@1952
  2178
      close(h);
ds@1952
  2179
      unlink(zFilename);
ds@1952
  2180
      return SQLITE_NOMEM;
ds@1952
  2181
    }
ds@1952
  2182
  } else {
ds@1952
  2183
    /*  pLock and pOpen are only used for posix advisory locking */
ds@1952
  2184
    pNew->pLock = NULL;
ds@1952
  2185
    pNew->pOpen = NULL;
ds@1952
  2186
  }
ds@1952
  2187
  pNew->dirfd = -1;
ds@1952
  2188
  pNew->h = h;
ds@1952
  2189
  SET_THREADID(pNew);
ds@1952
  2190
  pNew = sqlite3_malloc( sizeof(unixFile) );
ds@1952
  2191
  if( pNew==0 ){
ds@1952
  2192
    close(h);
ds@1952
  2193
    enterMutex();
ds@1952
  2194
    releaseLockInfo(pNew->pLock);
ds@1952
  2195
    releaseOpenCnt(pNew->pOpen);
ds@1952
  2196
    leaveMutex();
ds@1952
  2197
    return SQLITE_NOMEM;
ds@1952
  2198
  }else{
ds@1952
  2199
    switch(lockingStyle) {
ds@1952
  2200
      case afpLockingStyle: {
ds@1952
  2201
        /* afp locking uses the file path so it needs to be included in
ds@1952
  2202
        ** the afpLockingContext */
ds@1952
  2203
        int nFilename;
ds@1952
  2204
        pNew->pMethod = &sqlite3AFPLockingUnixIoMethod;
ds@1952
  2205
        pNew->lockingContext = 
ds@1952
  2206
          sqlite3_malloc(sizeof(afpLockingContext));
ds@1952
  2207
        nFilename = strlen(zFilename)+1;
ds@1952
  2208
        ((afpLockingContext *)pNew->lockingContext)->filePath = 
ds@1952
  2209
          sqlite3_malloc(nFilename);
ds@1952
  2210
        memcpy(((afpLockingContext *)pNew->lockingContext)->filePath, 
ds@1952
  2211
               zFilename, nFilename);
ds@1952
  2212
        srandomdev();
ds@1952
  2213
        break;
ds@1952
  2214
      }
ds@1952
  2215
      case flockLockingStyle:
ds@1952
  2216
        /* flock locking doesn't need additional lockingContext information */
ds@1952
  2217
        pNew->pMethod = &sqlite3FlockLockingUnixIoMethod;
ds@1952
  2218
        break;
ds@1952
  2219
      case dotlockLockingStyle: {
ds@1952
  2220
        /* dotlock locking uses the file path so it needs to be included in
ds@1952
  2221
         ** the dotlockLockingContext */
ds@1952
  2222
        int nFilename;
ds@1952
  2223
        pNew->pMethod = &sqlite3DotlockLockingUnixIoMethod;
ds@1952
  2224
        pNew->lockingContext = sqlite3_malloc(
ds@1952
  2225
          sizeof(dotlockLockingContext));
ds@1952
  2226
        nFilename = strlen(zFilename) + 6;
ds@1952
  2227
        ((dotlockLockingContext *)pNew->lockingContext)->lockPath = 
ds@1952
  2228
            sqlite3_malloc( nFilename );
ds@1952
  2229
        sqlite3_snprintf(nFilename, 
ds@1952
  2230
                ((dotlockLockingContext *)pNew->lockingContext)->lockPath, 
ds@1952
  2231
                "%s.lock", zFilename);
ds@1952
  2232
        break;
ds@1952
  2233
      }
ds@1952
  2234
      case posixLockingStyle:
ds@1952
  2235
        /* posix locking doesn't need additional lockingContext information */
ds@1952
  2236
        pNew->pMethod = &sqlite3UnixIoMethod;
ds@1952
  2237
        break;
ds@1952
  2238
      case noLockingStyle:
ds@1952
  2239
      case unsupportedLockingStyle:
ds@1952
  2240
      default: 
ds@1952
  2241
        pNew->pMethod = &sqlite3NolockLockingUnixIoMethod;
ds@1952
  2242
    }
ds@1952
  2243
    OpenCounter(+1);
ds@1952
  2244
    return SQLITE_OK;
ds@1952
  2245
  }
ds@1952
  2246
}
ds@1952
  2247
#else /* SQLITE_ENABLE_LOCKING_STYLE */
ds@1952
  2248
static int fillInUnixFile(
ds@1952
  2249
  int h,                 /* Open file descriptor on file being opened */
ds@1952
  2250
  int dirfd,
ds@1952
  2251
  sqlite3_file *pId,     /* Write to the unixFile structure here */
ds@1952
  2252
  const char *zFilename  /* Name of the file being opened */
ds@1952
  2253
){
ds@1952
  2254
  unixFile *pNew = (unixFile *)pId;
ds@1952
  2255
  int rc;
ds@1952
  2256
ds@1952
  2257
#ifdef FD_CLOEXEC
ds@1952
  2258
  fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
ds@1952
  2259
#endif
ds@1952
  2260
ds@1952
  2261
  enterMutex();
ds@1952
  2262
  rc = findLockInfo(h, &pNew->pLock, &pNew->pOpen);
ds@1952
  2263
  leaveMutex();
ds@1952
  2264
  if( rc ){
ds@1952
  2265
    close(h);
ds@1952
  2266
    return SQLITE_NOMEM;
ds@1952
  2267
  }
ds@1952
  2268
ds@1952
  2269
  OSTRACE3("OPEN    %-3d %s\n", h, zFilename);
ds@1952
  2270
  pNew->dirfd = -1;
ds@1952
  2271
  pNew->h = h;
ds@1952
  2272
  pNew->dirfd = dirfd;
ds@1952
  2273
  SET_THREADID(pNew);
ds@1952
  2274
ds@1952
  2275
  pNew->pMethod = &sqlite3UnixIoMethod;
ds@1952
  2276
  OpenCounter(+1);
ds@1952
  2277
  return SQLITE_OK;
ds@1952
  2278
}
ds@1952
  2279
#endif /* SQLITE_ENABLE_LOCKING_STYLE */
ds@1952
  2280
ds@1952
  2281
/*
ds@1952
  2282
** Open a file descriptor to the directory containing file zFilename.
ds@1952
  2283
** If successful, *pFd is set to the opened file descriptor and
ds@1952
  2284
** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
ds@1952
  2285
** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
ds@1952
  2286
** value.
ds@1952
  2287
**
ds@1952
  2288
** If SQLITE_OK is returned, the caller is responsible for closing
ds@1952
  2289
** the file descriptor *pFd using close().
ds@1952
  2290
*/
ds@1952
  2291
static int openDirectory(const char *zFilename, int *pFd){
ds@1952
  2292
  int ii;
ds@1952
  2293
  int fd = -1;
ds@1952
  2294
  char zDirname[MAX_PATHNAME+1];
ds@1952
  2295
ds@1952
  2296
  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
ds@1952
  2297
  for(ii=strlen(zDirname); ii>=0 && zDirname[ii]!='/'; ii--);
ds@1952
  2298
  if( ii>0 ){
ds@1952
  2299
    zDirname[ii] = '\0';
ds@1952
  2300
    fd = open(zDirname, O_RDONLY|O_BINARY, 0);
ds@1952
  2301
    if( fd>=0 ){
ds@1952
  2302
#ifdef FD_CLOEXEC
ds@1952
  2303
      fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
ds@1952
  2304
#endif
ds@1952
  2305
      OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
ds@1952
  2306
    }
ds@1952
  2307
  }
ds@1952
  2308
  *pFd = fd;
ds@1952
  2309
  return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
ds@1952
  2310
}
ds@1952
  2311
ds@1952
  2312
/*
ds@1952
  2313
** Open the file zPath.
ds@1952
  2314
** 
ds@1952
  2315
** Previously, the SQLite OS layer used three functions in place of this
ds@1952
  2316
** one:
ds@1952
  2317
**
ds@1952
  2318
**     sqlite3OsOpenReadWrite();
ds@1952
  2319
**     sqlite3OsOpenReadOnly();
ds@1952
  2320
**     sqlite3OsOpenExclusive();
ds@1952
  2321
**
ds@1952
  2322
** These calls correspond to the following combinations of flags:
ds@1952
  2323
**
ds@1952
  2324
**     ReadWrite() ->     (READWRITE | CREATE)
ds@1952
  2325
**     ReadOnly()  ->     (READONLY) 
ds@1952
  2326
**     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
ds@1952
  2327
**
ds@1952
  2328
** The old OpenExclusive() accepted a boolean argument - "delFlag". If
ds@1952
  2329
** true, the file was configured to be automatically deleted when the
ds@1952
  2330
** file handle closed. To achieve the same effect using this new 
ds@1952
  2331
** interface, add the DELETEONCLOSE flag to those specified above for 
ds@1952
  2332
** OpenExclusive().
ds@1952
  2333
*/
ds@1952
  2334
static int unixOpen(
ds@1952
  2335
  sqlite3_vfs *pVfs, 
ds@1952
  2336
  const char *zPath, 
ds@1952
  2337
  sqlite3_file *pFile,
ds@1952
  2338
  int flags,
ds@1952
  2339
  int *pOutFlags
ds@1952
  2340
){
ds@1952
  2341
  int fd = 0;                    /* File descriptor returned by open() */
ds@1952
  2342
  int dirfd = -1;                /* Directory file descriptor */
ds@1952
  2343
  int oflags = 0;                /* Flags to pass to open() */
ds@1952
  2344
  int eType = flags&0xFFFFFF00;  /* Type of file to open */
ds@1952
  2345
ds@1952
  2346
  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
ds@1952
  2347
  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
ds@1952
  2348
  int isCreate     = (flags & SQLITE_OPEN_CREATE);
ds@1952
  2349
  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
ds@1952
  2350
  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
ds@1952
  2351
ds@1952
  2352
  /* If creating a master or main-file journal, this function will open
ds@1952
  2353
  ** a file-descriptor on the directory too. The first time unixSync()
ds@1952
  2354
  ** is called the directory file descriptor will be fsync()ed and close()d.
ds@1952
  2355
  */
ds@1952
  2356
  int isOpenDirectory = (isCreate && 
ds@1952
  2357
      (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
ds@1952
  2358
  );
ds@1952
  2359
ds@1952
  2360
  /* Check the following statements are true: 
ds@1952
  2361
  **
ds@1952
  2362
  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
ds@1952
  2363
  **   (b) if CREATE is set, then READWRITE must also be set, and
ds@1952
  2364
  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
ds@1952
  2365
  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
ds@1952
  2366
  */
ds@1952
  2367
  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
ds@1952
  2368
  assert(isCreate==0 || isReadWrite);
ds@1952
  2369
  assert(isExclusive==0 || isCreate);
ds@1952
  2370
  assert(isDelete==0 || isCreate);
ds@1952
  2371
ds@1952
  2372
ds@1952
  2373
  /* The main DB, main journal, and master journal are never automatically
ds@1952
  2374
  ** deleted
ds@1952
  2375
  */
ds@1952
  2376
  assert( eType!=SQLITE_OPEN_MAIN_DB || !isDelete );
ds@1952
  2377
  assert( eType!=SQLITE_OPEN_MAIN_JOURNAL || !isDelete );
ds@1952
  2378
  assert( eType!=SQLITE_OPEN_MASTER_JOURNAL || !isDelete );
ds@1952
  2379
ds@1952
  2380
  /* Assert that the upper layer has set one of the "file-type" flags. */
ds@1952
  2381
  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
ds@1952
  2382
       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
ds@1952
  2383
       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
ds@1952
  2384
       || eType==SQLITE_OPEN_TRANSIENT_DB
ds@1952
  2385
  );
ds@1952
  2386
ds@1952
  2387
  if( isReadonly )  oflags |= O_RDONLY;
ds@1952
  2388
  if( isReadWrite ) oflags |= O_RDWR;
ds@1952
  2389
  if( isCreate )    oflags |= O_CREAT;
ds@1952
  2390
  if( isExclusive ) oflags |= (O_EXCL|O_NOFOLLOW);
ds@1952
  2391
  oflags |= (O_LARGEFILE|O_BINARY);
ds@1952
  2392
ds@1952
  2393
  memset(pFile, 0, sizeof(unixFile));
ds@1952
  2394
  fd = open(zPath, oflags, isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
ds@1952
  2395
  if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
ds@1952
  2396
    /* Failed to open the file for read/write access. Try read-only. */
ds@1952
  2397
    flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
ds@1952
  2398
    flags |= SQLITE_OPEN_READONLY;
ds@1952
  2399
    return unixOpen(pVfs, zPath, pFile, flags, pOutFlags);
ds@1952
  2400
  }
ds@1952
  2401
  if( fd<0 ){
ds@1952
  2402
    return SQLITE_CANTOPEN;
ds@1952
  2403
  }
ds@1952
  2404
  if( isDelete ){
ds@1952
  2405
    unlink(zPath);
ds@1952
  2406
  }
ds@1952
  2407
  if( pOutFlags ){
ds@1952
  2408
    *pOutFlags = flags;
ds@1952
  2409
  }
ds@1952
  2410
ds@1952
  2411
  assert(fd!=0);
ds@1952
  2412
  if( isOpenDirectory ){
ds@1952
  2413
    int rc = openDirectory(zPath, &dirfd);
ds@1952
  2414
    if( rc!=SQLITE_OK ){
ds@1952
  2415
      close(fd);
ds@1952
  2416
      return rc;
ds@1952
  2417
    }
ds@1952
  2418
  }
ds@1952
  2419
  return fillInUnixFile(fd, dirfd, pFile, zPath);
ds@1952
  2420
}
ds@1952
  2421
ds@1952
  2422
/*
ds@1952
  2423
** Delete the file at zPath. If the dirSync argument is true, fsync()
ds@1952
  2424
** the directory after deleting the file.
ds@1952
  2425
*/
ds@1952
  2426
static int unixDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
ds@1952
  2427
  int rc = SQLITE_OK;
ds@1952
  2428
  SimulateIOError(return SQLITE_IOERR_DELETE);
ds@1952
  2429
  unlink(zPath);
ds@1952
  2430
  if( dirSync ){
ds@1952
  2431
    int fd;
ds@1952
  2432
    rc = openDirectory(zPath, &fd);
ds@1952
  2433
    if( rc==SQLITE_OK ){
ds@1952
  2434
      if( fsync(fd) ){
ds@1952
  2435
        rc = SQLITE_IOERR_DIR_FSYNC;
ds@1952
  2436
      }
ds@1952
  2437
      close(fd);
ds@1952
  2438
    }
ds@1952
  2439
  }
ds@1952
  2440
  return rc;
ds@1952
  2441
}
ds@1952
  2442
ds@1952
  2443
/*
ds@1952
  2444
** Test the existance of or access permissions of file zPath. The
ds@1952
  2445
** test performed depends on the value of flags:
ds@1952
  2446
**
ds@1952
  2447
**     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
ds@1952
  2448
**     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
ds@1952
  2449
**     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
ds@1952
  2450
**
ds@1952
  2451
** Otherwise return 0.
ds@1952
  2452
*/
ds@1952
  2453
static int unixAccess(sqlite3_vfs *pVfs, const char *zPath, int flags){
ds@1952
  2454
  int amode = 0;
ds@1952
  2455
  switch( flags ){
ds@1952
  2456
    case SQLITE_ACCESS_EXISTS:
ds@1952
  2457
      amode = F_OK;
ds@1952
  2458
      break;
ds@1952
  2459
    case SQLITE_ACCESS_READWRITE:
ds@1952
  2460
      amode = W_OK|R_OK;
ds@1952
  2461
      break;
ds@1952
  2462
    case SQLITE_ACCESS_READ:
ds@1952
  2463
      amode = R_OK;
ds@1952
  2464
      break;
ds@1952
  2465
ds@1952
  2466
    default:
ds@1952
  2467
      assert(!"Invalid flags argument");
ds@1952
  2468
  }
ds@1952
  2469
  return (access(zPath, amode)==0);
ds@1952
  2470
}
ds@1952
  2471
ds@1952
  2472
/*
ds@1952
  2473
** Create a temporary file name in zBuf.  zBuf must be allocated
ds@1952
  2474
** by the calling process and must be big enough to hold at least
ds@1952
  2475
** pVfs->mxPathname bytes.
ds@1952
  2476
*/
ds@1952
  2477
static int unixGetTempname(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
ds@1952
  2478
  static const char *azDirs[] = {
ds@1952
  2479
     0,
ds@1952
  2480
     "/var/tmp",
ds@1952
  2481
     "/usr/tmp",
ds@1952
  2482
     "/tmp",
ds@1952
  2483
     ".",
ds@1952
  2484
  };
ds@1952
  2485
  static const unsigned char zChars[] =
ds@1952
  2486
    "abcdefghijklmnopqrstuvwxyz"
ds@1952
  2487
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ds@1952
  2488
    "0123456789";
ds@1952
  2489
  int i, j;
ds@1952
  2490
  struct stat buf;
ds@1952
  2491
  const char *zDir = ".";
ds@1952
  2492
ds@1952
  2493
  /* It's odd to simulate an io-error here, but really this is just
ds@1952
  2494
  ** using the io-error infrastructure to test that SQLite handles this
ds@1952
  2495
  ** function failing. 
ds@1952
  2496
  */
ds@1952
  2497
  SimulateIOError( return SQLITE_ERROR );
ds@1952
  2498
ds@1952
  2499
  azDirs[0] = sqlite3_temp_directory;
ds@1952
  2500
  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
ds@1952
  2501
    if( azDirs[i]==0 ) continue;
ds@1952
  2502
    if( stat(azDirs[i], &buf) ) continue;
ds@1952
  2503
    if( !S_ISDIR(buf.st_mode) ) continue;
ds@1952
  2504
    if( access(azDirs[i], 07) ) continue;
ds@1952
  2505
    zDir = azDirs[i];
ds@1952
  2506
    break;
ds@1952
  2507
  }
ds@1952
  2508
  do{
ds@1952
  2509
    assert( pVfs->mxPathname==MAX_PATHNAME );
ds@1952
  2510
    assert( nBuf>=MAX_PATHNAME );
ds@1952
  2511
    sqlite3_snprintf(MAX_PATHNAME-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
ds@1952
  2512
    j = strlen(zBuf);
ds@1952
  2513
    sqlite3Randomness(15, &zBuf[j]);
ds@1952
  2514
    for(i=0; i<15; i++, j++){
ds@1952
  2515
      zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
ds@1952
  2516
    }
ds@1952
  2517
    zBuf[j] = 0;
ds@1952
  2518
  }while( access(zBuf,0)==0 );
ds@1952
  2519
  return SQLITE_OK;
ds@1952
  2520
}
ds@1952
  2521
ds@1952
  2522
ds@1952
  2523
/*
ds@1952
  2524
** Turn a relative pathname into a full pathname. The relative path
ds@1952
  2525
** is stored as a nul-terminated string in the buffer pointed to by
ds@1952
  2526
** zPath. 
ds@1952
  2527
**
ds@1952
  2528
** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
ds@1952
  2529
** (in this case, MAX_PATHNAME bytes). The full-path is written to
ds@1952
  2530
** this buffer before returning.
ds@1952
  2531
*/
ds@1952
  2532
static int unixFullPathname(
ds@1952
  2533
  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
ds@1952
  2534
  const char *zPath,            /* Possibly relative input path */
ds@1952
  2535
  int nOut,                     /* Size of output buffer in bytes */
ds@1952
  2536
  char *zOut                    /* Output buffer */
ds@1952
  2537
){
ds@1952
  2538
ds@1952
  2539
  /* It's odd to simulate an io-error here, but really this is just
ds@1952
  2540
  ** using the io-error infrastructure to test that SQLite handles this
ds@1952
  2541
  ** function failing. This function could fail if, for example, the
ds@1952
  2542
  ** current working directly has been unlinked.
ds@1952
  2543
  */
ds@1952
  2544
  SimulateIOError( return SQLITE_ERROR );
ds@1952
  2545
ds@1952
  2546
  assert( pVfs->mxPathname==MAX_PATHNAME );
ds@1952
  2547
  zOut[MAX_PATHNAME-1] = '\0';
ds@1952
  2548
  if( zPath[0]=='/' ){
ds@1952
  2549
    sqlite3_snprintf(MAX_PATHNAME, zOut, "%s", zPath);
ds@1952
  2550
  }else{
ds@1952
  2551
    int nCwd;
ds@1952
  2552
    if( getcwd(zOut, MAX_PATHNAME-1)==0 ){
ds@1952
  2553
      return SQLITE_CANTOPEN;
ds@1952
  2554
    }
ds@1952
  2555
    nCwd = strlen(zOut);
ds@1952
  2556
    sqlite3_snprintf(MAX_PATHNAME-nCwd, &zOut[nCwd], "/%s", zPath);
ds@1952
  2557
  }
ds@1952
  2558
  return SQLITE_OK;
ds@1952
  2559
ds@1952
  2560
#if 0
ds@1952
  2561
  /*
ds@1952
  2562
  ** Remove "/./" path elements and convert "/A/./" path elements
ds@1952
  2563
  ** to just "/".
ds@1952
  2564
  */
ds@1952
  2565
  if( zFull ){
ds@1952
  2566
    int i, j;
ds@1952
  2567
    for(i=j=0; zFull[i]; i++){
ds@1952
  2568
      if( zFull[i]=='/' ){
ds@1952
  2569
        if( zFull[i+1]=='/' ) continue;
ds@1952
  2570
        if( zFull[i+1]=='.' && zFull[i+2]=='/' ){
ds@1952
  2571
          i += 1;
ds@1952
  2572
          continue;
ds@1952
  2573
        }
ds@1952
  2574
        if( zFull[i+1]=='.' && zFull[i+2]=='.' && zFull[i+3]=='/' ){
ds@1952
  2575
          while( j>0 && zFull[j-1]!='/' ){ j--; }
ds@1952
  2576
          i += 3;
ds@1952
  2577
          continue;
ds@1952
  2578
        }
ds@1952
  2579
      }
ds@1952
  2580
      zFull[j++] = zFull[i];
ds@1952
  2581
    }
ds@1952
  2582
    zFull[j] = 0;
ds@1952
  2583
  }
ds@1952
  2584
#endif
ds@1952
  2585
}
ds@1952
  2586
ds@1952
  2587
ds@1952
  2588
#ifndef SQLITE_OMIT_LOAD_EXTENSION
ds@1952
  2589
/*
ds@1952
  2590
** Interfaces for opening a shared library, finding entry points
ds@1952
  2591
** within the shared library, and closing the shared library.
ds@1952
  2592
*/
ds@1952
  2593
#include <dlfcn.h>
ds@1952
  2594
static void *unixDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
ds@1952
  2595
  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
ds@1952
  2596
}
ds@1952
  2597
ds@1952
  2598
/*
ds@1952
  2599
** SQLite calls this function immediately after a call to unixDlSym() or
ds@1952
  2600
** unixDlOpen() fails (returns a null pointer). If a more detailed error
ds@1952
  2601
** message is available, it is written to zBufOut. If no error message
ds@1952
  2602
** is available, zBufOut is left unmodified and SQLite uses a default
ds@1952
  2603
** error message.
ds@1952
  2604
*/
ds@1952
  2605
static void unixDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
ds@1952
  2606
  char *zErr;
ds@1952
  2607
  enterMutex();
ds@1952
  2608
  zErr = dlerror();
ds@1952
  2609
  if( zErr ){
ds@1952
  2610
    sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
ds@1952
  2611
  }
ds@1952
  2612
  leaveMutex();
ds@1952
  2613
}
ds@1952
  2614
static void *unixDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
ds@1952
  2615
  return dlsym(pHandle, zSymbol);
ds@1952
  2616
}
ds@1952
  2617
static void unixDlClose(sqlite3_vfs *pVfs, void *pHandle){
ds@1952
  2618
  dlclose(pHandle);
ds@1952
  2619
}
ds@1952
  2620
#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
ds@1952
  2621
  #define unixDlOpen  0
ds@1952
  2622
  #define unixDlError 0
ds@1952
  2623
  #define unixDlSym   0
ds@1952
  2624
  #define unixDlClose 0
ds@1952
  2625
#endif
ds@1952
  2626
ds@1952
  2627
/*
ds@1952
  2628
** Write nBuf bytes of random data to the supplied buffer zBuf.
ds@1952
  2629
*/
ds@1952
  2630
static int unixRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
ds@1952
  2631
ds@1952
  2632
  assert(nBuf>=(sizeof(time_t)+sizeof(int)));
ds@1952
  2633
ds@1952
  2634
  /* We have to initialize zBuf to prevent valgrind from reporting
ds@1952
  2635
  ** errors.  The reports issued by valgrind are incorrect - we would
ds@1952
  2636
  ** prefer that the randomness be increased by making use of the
ds@1952
  2637
  ** uninitialized space in zBuf - but valgrind errors tend to worry
ds@1952
  2638
  ** some users.  Rather than argue, it seems easier just to initialize
ds@1952
  2639
  ** the whole array and silence valgrind, even if that means less randomness
ds@1952
  2640
  ** in the random seed.
ds@1952
  2641
  **
ds@1952
  2642
  ** When testing, initializing zBuf[] to zero is all we do.  That means
ds@1952
  2643
  ** that we always use the same random number sequence.  This makes the
ds@1952
  2644
  ** tests repeatable.
ds@1952
  2645
  */
ds@1952
  2646
  memset(zBuf, 0, nBuf);
ds@1952
  2647
#if !defined(SQLITE_TEST)
ds@1952
  2648
  {
ds@1952
  2649
    int pid, fd;
ds@1952
  2650
    fd = open("/dev/urandom", O_RDONLY);
ds@1952
  2651
    if( fd<0 ){
ds@1952
  2652
      time_t t;
ds@1952
  2653
      time(&t);
ds@1952
  2654
      memcpy(zBuf, &t, sizeof(t));
ds@1952
  2655
      pid = getpid();
ds@1952
  2656
      memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
ds@1952
  2657
    }else{
ds@1952
  2658
      read(fd, zBuf, nBuf);
ds@1952
  2659
      close(fd);
ds@1952
  2660
    }
ds@1952
  2661
  }
ds@1952
  2662
#endif
ds@1952
  2663
  return SQLITE_OK;
ds@1952
  2664
}
ds@1952
  2665
ds@1952
  2666
ds@1952
  2667
/*
ds@1952
  2668
** Sleep for a little while.  Return the amount of time slept.
ds@1952
  2669
** The argument is the number of microseconds we want to sleep.
ds@1952
  2670
** The return value is the number of microseconds of sleep actually
ds@1952
  2671
** requested from the underlying operating system, a number which
ds@1952
  2672
** might be greater than or equal to the argument, but not less
ds@1952
  2673
** than the argument.
ds@1952
  2674
*/
ds@1952
  2675
static int unixSleep(sqlite3_vfs *pVfs, int microseconds){
ds@1952
  2676
#if defined(HAVE_USLEEP) && HAVE_USLEEP
ds@1952
  2677
  usleep(microseconds);
ds@1952
  2678
  return microseconds;
ds@1952
  2679
#else
ds@1952
  2680
  int seconds = (microseconds+999999)/1000000;
ds@1952
  2681
  sleep(seconds);
ds@1952
  2682
  return seconds*1000000;
ds@1952
  2683
#endif
ds@1952
  2684
}
ds@1952
  2685
ds@1952
  2686
/*
ds@1952
  2687
** The following variable, if set to a non-zero value, becomes the result
ds@1952
  2688
** returned from sqlite3OsCurrentTime().  This is used for testing.
ds@1952
  2689
*/
ds@1952
  2690
#ifdef SQLITE_TEST
ds@1952
  2691
int sqlite3_current_time = 0;
ds@1952
  2692
#endif
ds@1952
  2693
ds@1952
  2694
/*
ds@1952
  2695
** Find the current time (in Universal Coordinated Time).  Write the
ds@1952
  2696
** current time and date as a Julian Day number into *prNow and
ds@1952
  2697
** return 0.  Return 1 if the time and date cannot be found.
ds@1952
  2698
*/
ds@1952
  2699
static int unixCurrentTime(sqlite3_vfs *pVfs, double *prNow){
ds@1952
  2700
#ifdef NO_GETTOD
ds@1952
  2701
  time_t t;
ds@1952
  2702
  time(&t);
ds@1952
  2703
  *prNow = t/86400.0 + 2440587.5;
ds@1952
  2704
#else
ds@1952
  2705
  struct timeval sNow;
ds@1952
  2706
  gettimeofday(&sNow, 0);
ds@1952
  2707
  *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
ds@1952
  2708
#endif
ds@1952
  2709
#ifdef SQLITE_TEST
ds@1952
  2710
  if( sqlite3_current_time ){
ds@1952
  2711
    *prNow = sqlite3_current_time/86400.0 + 2440587.5;
ds@1952
  2712
  }
ds@1952
  2713
#endif
ds@1952
  2714
  return 0;
ds@1952
  2715
}
ds@1952
  2716
ds@1952
  2717
/*
ds@1952
  2718
** Return a pointer to the sqlite3DefaultVfs structure.   We use
ds@1952
  2719
** a function rather than give the structure global scope because
ds@1952
  2720
** some compilers (MSVC) do not allow forward declarations of
ds@1952
  2721
** initialized structures.
ds@1952
  2722
*/
ds@1952
  2723
sqlite3_vfs *sqlite3OsDefaultVfs(void){
ds@1952
  2724
  static sqlite3_vfs unixVfs = {
ds@1952
  2725
    1,                  /* iVersion */
ds@1952
  2726
    sizeof(unixFile),   /* szOsFile */
ds@1952
  2727
    MAX_PATHNAME,       /* mxPathname */
ds@1952
  2728
    0,                  /* pNext */
ds@1952
  2729
    "unix",             /* zName */
ds@1952
  2730
    0,                  /* pAppData */
ds@1952
  2731
  
ds@1952
  2732
    unixOpen,           /* xOpen */
ds@1952
  2733
    unixDelete,         /* xDelete */
ds@1952
  2734
    unixAccess,         /* xAccess */
ds@1952
  2735
    unixGetTempname,    /* xGetTempName */
ds@1952
  2736
    unixFullPathname,   /* xFullPathname */
ds@1952
  2737
    unixDlOpen,         /* xDlOpen */
ds@1952
  2738
    unixDlError,        /* xDlError */
ds@1952
  2739
    unixDlSym,          /* xDlSym */
ds@1952
  2740
    unixDlClose,        /* xDlClose */
ds@1952
  2741
    unixRandomness,     /* xRandomness */
ds@1952
  2742
    unixSleep,          /* xSleep */
ds@1952
  2743
    unixCurrentTime     /* xCurrentTime */
ds@1952
  2744
  };
ds@1952
  2745
  
ds@1952
  2746
  return &unixVfs;
ds@1952
  2747
}
ds@1952
  2748
 
ds@1952
  2749
#endif /* OS_UNIX */