SQLite

Check-in [f4103dea5e]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Add the OS-X locking style patches to os_unix.c. Disabled by default. (CVS 3459)
Downloads: Tarball | ZIP archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: f4103dea5e1a87adccccca715946e174d1cc7450
User & Date: drh 2006-10-03 17:40:40.000
Context
2006-10-03
19:05
Report the error SQLITE_CORRUPT instead of SQLITE_IOERR if unable to rollback a hot journal that was damaged (for example) by filesystem corruption following a power failure. (CVS 3460) (check-in: 70501e4ea5 user: drh tags: trunk)
17:40
Add the OS-X locking style patches to os_unix.c. Disabled by default. (CVS 3459) (check-in: f4103dea5e user: drh tags: trunk)
12:08
Fix sqlite3_analyzer so that it works when compiled against Tcl8.5. (CVS 3458) (check-in: e774adce8e user: drh tags: trunk)
Changes
Unified Diff Ignore Whitespace Patch
Changes to src/os_unix.c.
12
13
14
15
16
17
18


19
20
21
22
23
24
25
**
** This file contains code that is specific to Unix systems.
*/
#include "sqliteInt.h"
#include "os.h"
#if OS_UNIX              /* This file is used on unix only */



/*
** These #defines should enable >2GB file support on Posix if the
** underlying operating system supports it.  If the OS lacks
** large file support, these should be no-ops.
**
** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
** on the compiler command line.  This is necessary if you are compiling







>
>







12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
**
** This file contains code that is specific to Unix systems.
*/
#include "sqliteInt.h"
#include "os.h"
#if OS_UNIX              /* This file is used on unix only */

/* #define SQLITE_ENABLE_LOCKING_STYLE 0 */

/*
** These #defines should enable >2GB file support on Posix if the
** underlying operating system supports it.  If the OS lacks
** large file support, these should be no-ops.
**
** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
** on the compiler command line.  This is necessary if you are compiling
43
44
45
46
47
48
49





50
51
52
53
54
55
56
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
#include <errno.h>






/*
** If we are to be thread-safe, include the pthreads header and define
** the SQLITE_UNIX_THREADS macro.
*/
#if defined(THREADSAFE) && THREADSAFE
# include <pthread.h>







>
>
>
>
>







45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
#include <errno.h>
#ifdef SQLITE_ENABLE_LOCKING_STYLE
#include <sys/ioctl.h>
#include <sys/param.h>
#include <sys/mount.h>
#endif /* SQLITE_ENABLE_LOCKING_STYLE */

/*
** If we are to be thread-safe, include the pthreads header and define
** the SQLITE_UNIX_THREADS macro.
*/
#if defined(THREADSAFE) && THREADSAFE
# include <pthread.h>
71
72
73
74
75
76
77



78
79
80
81
82
83
84
** protability layer.
*/
typedef struct unixFile unixFile;
struct unixFile {
  IoMethod const *pMethod;  /* Always the first entry */
  struct openCnt *pOpen;    /* Info about all open fd's on this inode */
  struct lockInfo *pLock;   /* Info about locks on this inode */



  int h;                    /* The file descriptor */
  unsigned char locktype;   /* The type of lock held on this fd */
  unsigned char isOpen;     /* True if needs to be closed */
  unsigned char fullSync;   /* Use F_FULLSYNC if available */
  int dirfd;                /* File descriptor for the directory */
  i64 offset;               /* Seek offset */
#ifdef SQLITE_UNIX_THREADS







>
>
>







78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
** protability layer.
*/
typedef struct unixFile unixFile;
struct unixFile {
  IoMethod const *pMethod;  /* Always the first entry */
  struct openCnt *pOpen;    /* Info about all open fd's on this inode */
  struct lockInfo *pLock;   /* Info about locks on this inode */
#ifdef SQLITE_ENABLE_LOCKING_STYLE
  void *lockingContext;     /* Locking style specific state */
#endif /* SQLITE_ENABLE_LOCKING_STYLE */
  int h;                    /* The file descriptor */
  unsigned char locktype;   /* The type of lock held on this fd */
  unsigned char isOpen;     /* True if needs to be closed */
  unsigned char fullSync;   /* Use F_FULLSYNC if available */
  int dirfd;                /* File descriptor for the directory */
  i64 offset;               /* Seek offset */
#ifdef SQLITE_UNIX_THREADS
342
343
344
345
346
347
348


























349
350
351
352
353
354
355
** these hash tables must be protected by a mutex.
*/
static Hash lockHash = {SQLITE_HASH_BINARY, 0, 0, 0, 
    sqlite3ThreadSafeMalloc, sqlite3ThreadSafeFree, 0, 0};
static Hash openHash = {SQLITE_HASH_BINARY, 0, 0, 0, 
    sqlite3ThreadSafeMalloc, sqlite3ThreadSafeFree, 0, 0};



























#ifdef SQLITE_UNIX_THREADS
/*
** This variable records whether or not threads can override each others
** locks.
**
**    0:  No.  Threads cannot override each others locks.
**    1:  Yes.  Threads can override each others locks.







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
** these hash tables must be protected by a mutex.
*/
static Hash lockHash = {SQLITE_HASH_BINARY, 0, 0, 0, 
    sqlite3ThreadSafeMalloc, sqlite3ThreadSafeFree, 0, 0};
static Hash openHash = {SQLITE_HASH_BINARY, 0, 0, 0, 
    sqlite3ThreadSafeMalloc, sqlite3ThreadSafeFree, 0, 0};

#ifdef SQLITE_ENABLE_LOCKING_STYLE
/*
** The locking styles are associated with the different file locking
** capabilities supported by different file systems.  
**
** POSIX locking style fully supports shared and exclusive byte-range locks 
** ADP locking only supports exclusive byte-range locks
** FLOCK only supports a single file-global exclusive lock
** DOTLOCK isn't a true locking style, it refers to the use of a special
**   file named the same as the database file with a '.lock' extension, this
**   can be used on file systems that do not offer any reliable file locking
** NO locking means that no locking will be attempted, this is only used for
**   read-only file systems currently
** UNSUPPORTED means that no locking will be attempted, this is only used for
**   file systems that are known to be unsupported
*/
typedef enum {
	posixLockingStyle = 0,       /* standard posix-advisory locks */
	afpLockingStyle,             /* use afp locks */
	flockLockingStyle,           /* use flock() */
	dotlockLockingStyle,         /* use <file>.lock files */
	noLockingStyle,              /* useful for read-only file system */
	unsupportedLockingStyle      /* indicates unsupported file system */
} sqlite3LockingStyle;
#endif /* SQLITE_ENABLE_LOCKING_STYLE */

#ifdef SQLITE_UNIX_THREADS
/*
** This variable records whether or not threads can override each others
** locks.
**
**    0:  No.  Threads cannot override each others locks.
**    1:  Yes.  Threads can override each others locks.
486
487
488
489
490
491
492


493
494
495
496
497
498
499
500
501
502
503
504


505
506
507
508
509
510
511
512







































































513
514
515
516
517
518
519
#endif /* SQLITE_UNIX_THREADS */

/*
** Release a lockInfo structure previously allocated by findLockInfo().
*/
static void releaseLockInfo(struct lockInfo *pLock){
  assert( sqlite3OsInMutex(1) );


  pLock->nRef--;
  if( pLock->nRef==0 ){
    sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
    sqlite3ThreadSafeFree(pLock);
  }
}

/*
** Release a openCnt structure previously allocated by findLockInfo().
*/
static void releaseOpenCnt(struct openCnt *pOpen){
  assert( sqlite3OsInMutex(1) );


  pOpen->nRef--;
  if( pOpen->nRef==0 ){
    sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
    free(pOpen->aPending);
    sqlite3ThreadSafeFree(pOpen);
  }
}








































































/*
** Given a file descriptor, locate lockInfo and openCnt structures that
** describes that file descriptor.  Create new ones if necessary.  The
** return values might be uninitialized if an error occurs.
**
** Return the number of errors.
*/







>
>












>
>








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
#endif /* SQLITE_UNIX_THREADS */

/*
** Release a lockInfo structure previously allocated by findLockInfo().
*/
static void releaseLockInfo(struct lockInfo *pLock){
  assert( sqlite3OsInMutex(1) );
  if (pLock == NULL)
    return;
  pLock->nRef--;
  if( pLock->nRef==0 ){
    sqlite3HashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
    sqlite3ThreadSafeFree(pLock);
  }
}

/*
** Release a openCnt structure previously allocated by findLockInfo().
*/
static void releaseOpenCnt(struct openCnt *pOpen){
  assert( sqlite3OsInMutex(1) );
  if (pOpen == NULL)
    return;
  pOpen->nRef--;
  if( pOpen->nRef==0 ){
    sqlite3HashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
    free(pOpen->aPending);
    sqlite3ThreadSafeFree(pOpen);
  }
}

#ifdef SQLITE_ENABLE_LOCKING_STYLE
/*
** Tests a byte-range locking query to see if byte range locks are 
** supported, if not we fall back to dotlockLockingStyle.
*/
static sqlite3LockingStyle sqlite3TestLockingStyle(const char *filePath, 
  int fd) {
  /* test byte-range lock using fcntl */
  struct flock lockInfo;
  
  lockInfo.l_len = 1;
  lockInfo.l_start = 0;
  lockInfo.l_whence = SEEK_SET;
  lockInfo.l_type = F_RDLCK;
  
  if (fcntl(fd, F_GETLK, (int) &lockInfo) != -1) {
    return posixLockingStyle;
  } 
  
  /* testing for flock can give false positives.  So if if the above test
  ** fails, then we fall back to using dot-lock style locking.
  */  
  return dotlockLockingStyle;
}

/* 
** Examines the f_fstypename entry in the statfs structure as returned by 
** stat() for the file system hosting the database file, assigns the 
** appropriate locking style based on it's value.  These values and 
** assignments are based on Darwin/OSX behavior and have not been tested on 
** other systems.
*/
static sqlite3LockingStyle sqlite3DetectLockingStyle(const char *filePath, 
  int fd) {

#ifdef SQLITE_FIXED_LOCKING_STYLE
  return (sqlite3LockingStyle)SQLITE_FIXED_LOCKING_STYLE;
#else
  struct statfs fsInfo;

  if (statfs(filePath, &fsInfo) == -1)
    return sqlite3TestLockingStyle(filePath, fd);
  
  if (fsInfo.f_flags & MNT_RDONLY)
    return noLockingStyle;
  
  if( (!strcmp(fsInfo.f_fstypename, "hfs")) ||
    (!strcmp(fsInfo.f_fstypename, "ufs")) )
		return posixLockingStyle;
  
  if(!strcmp(fsInfo.f_fstypename, "afpfs"))
    return afpLockingStyle;
  
  if(!strcmp(fsInfo.f_fstypename, "nfs")) 
    return sqlite3TestLockingStyle(filePath, fd);
  
  if(!strcmp(fsInfo.f_fstypename, "smbfs"))
    return flockLockingStyle;
  
  if(!strcmp(fsInfo.f_fstypename, "msdos"))
    return dotlockLockingStyle;
  
  if(!strcmp(fsInfo.f_fstypename, "webdav"))
    return unsupportedLockingStyle;
  
  return sqlite3TestLockingStyle(filePath, fd);  
#endif // SQLITE_FIXED_LOCKING_STYLE
}

#endif /* SQLITE_ENABLE_LOCKING_STYLE */

/*
** Given a file descriptor, locate lockInfo and openCnt structures that
** describes that file descriptor.  Create new ones if necessary.  The
** return values might be uninitialized if an error occurs.
**
** Return the number of errors.
*/
647
648
649
650
651
652
653

654
655
656
657
658
659



660
661
662
663
664
665
666
  }
  if( pFile->locktype!=NO_LOCK ){
    /* We cannot change ownership while we are holding a lock! */
    return SQLITE_MISUSE;
  }
  TRACE4("Transfer ownership of %d from %d to %d\n", pFile->h,pFile->tid,hSelf);
  pFile->tid = hSelf;

  releaseLockInfo(pFile->pLock);
  rc = findLockInfo(pFile->h, &pFile->pLock, 0);
  TRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
     locktypeName(pFile->locktype),
     locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
  return rc;



}
#else
  /* On single-threaded builds, ownership transfer is a no-op */
# define transferOwnership(X) SQLITE_OK
#endif

/*







>
|
|
|
|
|
|
>
>
>







758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
  }
  if( pFile->locktype!=NO_LOCK ){
    /* We cannot change ownership while we are holding a lock! */
    return SQLITE_MISUSE;
  }
  TRACE4("Transfer ownership of %d from %d to %d\n", pFile->h,pFile->tid,hSelf);
  pFile->tid = hSelf;
  if (pFile->pLock != NULL) {
    releaseLockInfo(pFile->pLock);
    rc = findLockInfo(pFile->h, &pFile->pLock, 0);
    TRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
           locktypeName(pFile->locktype),
           locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
    return rc;
  } else {
    return SQLITE_OK;
  }
}
#else
  /* On single-threaded builds, ownership transfer is a no-op */
# define transferOwnership(X) SQLITE_OK
#endif

/*
675
676
677
678
679
680
681
682





683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811



812
813
814
815
816
817
818
** Return TRUE if the named file exists.
*/
int sqlite3UnixFileExists(const char *zFilename){
  return access(zFilename, 0)==0;
}

/* Forward declaration */
static int allocateUnixFile(unixFile *pInit, OsFile **pId);






/*
** Attempt to open a file for both reading and writing.  If that
** fails, try opening it read-only.  If the file does not exist,
** try to create it.
**
** On success, a handle for the open file is written to *id
** and *pReadonly is set to 0 if the file was opened for reading and
** writing or 1 if the file was opened read-only.  The function returns
** SQLITE_OK.
**
** On failure, the function returns SQLITE_CANTOPEN and leaves
** *id and *pReadonly unchanged.
*/
int sqlite3UnixOpenReadWrite(
  const char *zFilename,
  OsFile **pId,
  int *pReadonly
){
  int rc;
  unixFile f;

  CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadWrite, zFilename, pId, pReadonly);
  assert( 0==*pId );
  f.h = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY,
                          SQLITE_DEFAULT_FILE_PERMISSIONS);
  if( f.h<0 ){
#ifdef EISDIR
    if( errno==EISDIR ){
      return SQLITE_CANTOPEN;
    }
#endif
    f.h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
    if( f.h<0 ){
      return SQLITE_CANTOPEN; 
    }
    *pReadonly = 1;
  }else{
    *pReadonly = 0;
  }
  sqlite3OsEnterMutex();
  rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
  sqlite3OsLeaveMutex();
  if( rc ){
    close(f.h);
    return SQLITE_NOMEM;
  }
  TRACE3("OPEN    %-3d %s\n", f.h, zFilename);
  return allocateUnixFile(&f, pId);
}


/*
** Attempt to open a new file for exclusive access by this process.
** The file will be opened for both reading and writing.  To avoid
** a potential security problem, we do not allow the file to have
** previously existed.  Nor do we allow the file to be a symbolic
** link.
**
** If delFlag is true, then make arrangements to automatically delete
** the file when it is closed.
**
** On success, write the file handle into *id and return SQLITE_OK.
**
** On failure, return SQLITE_CANTOPEN.
*/
int sqlite3UnixOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
  int rc;
  unixFile f;

  CRASH_TEST_OVERRIDE(sqlite3CrashOpenExclusive, zFilename, pId, delFlag);
  assert( 0==*pId );
  f.h = open(zFilename,
                O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY,
                SQLITE_DEFAULT_FILE_PERMISSIONS);
  if( f.h<0 ){
    return SQLITE_CANTOPEN;
  }
  sqlite3OsEnterMutex();
  rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
  sqlite3OsLeaveMutex();
  if( rc ){
    close(f.h);
    unlink(zFilename);
    return SQLITE_NOMEM;
  }
  if( delFlag ){
    unlink(zFilename);
  }
  TRACE3("OPEN-EX %-3d %s\n", f.h, zFilename);
  return allocateUnixFile(&f, pId);
}

/*
** Attempt to open a new file for read-only access.
**
** On success, write the file handle into *id and return SQLITE_OK.
**
** On failure, return SQLITE_CANTOPEN.
*/
int sqlite3UnixOpenReadOnly(const char *zFilename, OsFile **pId){
  int rc;
  unixFile f;

  CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadOnly, zFilename, pId, 0);
  assert( 0==*pId );
  f.h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
  if( f.h<0 ){
    return SQLITE_CANTOPEN;
  }
  sqlite3OsEnterMutex();
  rc = findLockInfo(f.h, &f.pLock, &f.pOpen);
  sqlite3OsLeaveMutex();
  if( rc ){
    close(f.h);
    return SQLITE_NOMEM;
  }
  TRACE3("OPEN-RO %-3d %s\n", f.h, zFilename);
  return allocateUnixFile(&f, pId);
}

/*
** Attempt to open a file descriptor for the directory that contains a
** file.  This file descriptor can be used to fsync() the directory
** in order to make sure the creation of a new file is actually written
** to disk.
**
** This routine is only meaningful for Unix.  It is a no-op under
** windows since windows does not support hard links.



**
** On success, a handle for a previously open file at *id is
** updated with the new directory file descriptor and SQLITE_OK is
** returned.
**
** On failure, the function returns SQLITE_CANTOPEN and leaves
** *id unchanged.







|
>
>
>
>
>



















|
<
|


|
|
|





|
|






<
<
<
<
<
<
<
<
|


















|
<



|


|


<
<
<
<
<
<
<
<
<
<
<
<
|










|
<
|


|
|


<
<
<
<
<
<
<
<
|










>
>
>







790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822

823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841








842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861

862
863
864
865
866
867
868
869
870












871
872
873
874
875
876
877
878
879
880
881
882

883
884
885
886
887
888
889








890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
** Return TRUE if the named file exists.
*/
int sqlite3UnixFileExists(const char *zFilename){
  return access(zFilename, 0)==0;
}

/* Forward declaration */
static int allocateUnixFile(
  int h,                    /* File descriptor of the open file */
  OsFile **pId,             /* Write the real file descriptor here */
  const char *zFilename,    /* Name of the file being opened */
  int delFlag               /* If true, make sure the file deletes on close */
);

/*
** Attempt to open a file for both reading and writing.  If that
** fails, try opening it read-only.  If the file does not exist,
** try to create it.
**
** On success, a handle for the open file is written to *id
** and *pReadonly is set to 0 if the file was opened for reading and
** writing or 1 if the file was opened read-only.  The function returns
** SQLITE_OK.
**
** On failure, the function returns SQLITE_CANTOPEN and leaves
** *id and *pReadonly unchanged.
*/
int sqlite3UnixOpenReadWrite(
  const char *zFilename,
  OsFile **pId,
  int *pReadonly
){
  int h;

  
  CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadWrite, zFilename, pId, pReadonly);
  assert( 0==*pId );
  h = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY,
                        SQLITE_DEFAULT_FILE_PERMISSIONS);
  if( h<0 ){
#ifdef EISDIR
    if( errno==EISDIR ){
      return SQLITE_CANTOPEN;
    }
#endif
    h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
    if( h<0 ){
      return SQLITE_CANTOPEN; 
    }
    *pReadonly = 1;
  }else{
    *pReadonly = 0;
  }








  return allocateUnixFile(h, pId, zFilename, 0);
}


/*
** Attempt to open a new file for exclusive access by this process.
** The file will be opened for both reading and writing.  To avoid
** a potential security problem, we do not allow the file to have
** previously existed.  Nor do we allow the file to be a symbolic
** link.
**
** If delFlag is true, then make arrangements to automatically delete
** the file when it is closed.
**
** On success, write the file handle into *id and return SQLITE_OK.
**
** On failure, return SQLITE_CANTOPEN.
*/
int sqlite3UnixOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
  int h;


  CRASH_TEST_OVERRIDE(sqlite3CrashOpenExclusive, zFilename, pId, delFlag);
  assert( 0==*pId );
  h = open(zFilename,
                O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY,
                SQLITE_DEFAULT_FILE_PERMISSIONS);
  if( h<0 ){
    return SQLITE_CANTOPEN;
  }












  return allocateUnixFile(h, pId, zFilename, delFlag);
}

/*
** Attempt to open a new file for read-only access.
**
** On success, write the file handle into *id and return SQLITE_OK.
**
** On failure, return SQLITE_CANTOPEN.
*/
int sqlite3UnixOpenReadOnly(const char *zFilename, OsFile **pId){
  int h;

  
  CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadOnly, zFilename, pId, 0);
  assert( 0==*pId );
  h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
  if( h<0 ){
    return SQLITE_CANTOPEN;
  }








  return allocateUnixFile(h, pId, zFilename, 0);
}

/*
** Attempt to open a file descriptor for the directory that contains a
** file.  This file descriptor can be used to fsync() the directory
** in order to make sure the creation of a new file is actually written
** to disk.
**
** This routine is only meaningful for Unix.  It is a no-op under
** windows since windows does not support hard links.
**
** If FULL_FSYNC is enabled, this function is not longer useful, 
** a FULL_FSYNC sync applies to all pending disk operations.
**
** On success, a handle for a previously open file at *id is
** updated with the new directory file descriptor and SQLITE_OK is
** returned.
**
** On failure, the function returns SQLITE_CANTOPEN and leaves
** *id unchanged.
1576
1577
1578
1579
1580
1581
1582































































































































































































































































































































































































































































































































































































1583
1584
1585
1586
1587
1588
1589
  TRACE2("CLOSE   %-3d\n", id->h);
  OpenCounter(-1);
  sqlite3ThreadSafeFree(id);
  *pId = 0;
  return SQLITE_OK;
}
































































































































































































































































































































































































































































































































































































/*
** Turn a relative pathname into a full pathname.  Return a pointer
** to the full pathname stored in space obtained from sqliteMalloc().
** The calling function is responsible for freeing this space once it
** is no longer needed.
*/
char *sqlite3UnixFullPathname(const char *zRelative){







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
  TRACE2("CLOSE   %-3d\n", id->h);
  OpenCounter(-1);
  sqlite3ThreadSafeFree(id);
  *pId = 0;
  return SQLITE_OK;
}


#ifdef SQLITE_ENABLE_LOCKING_STYLE
#pragma mark AFP Support

/*
 ** The afpLockingContext structure contains all afp lock specific state
 */
typedef struct afpLockingContext afpLockingContext;
struct afpLockingContext {
  unsigned long long sharedLockByte;
  char *filePath;
};

struct ByteRangeLockPB2
{
  unsigned long long offset;        /* offset to first byte to lock */
  unsigned long long length;        /* nbr of bytes to lock */
  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
  unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
  int fd;                           /* file desc to assoc this lock with */
};

#define afpfsByteRangeLock2FSCTL	_IOWR('z', 23, struct ByteRangeLockPB2)

/* return 0 on success, 1 on failure.  To match the behavior of the 
  normal posix file locking (used in unixLock for example), we should 
  provide 'richer' return codes - specifically to differentiate between
  'file busy' and 'file system error' results */
static int _AFPFSSetLock(const char *path, int fd, unsigned long long offset, 
                         unsigned long long length, int setLockFlag)
{
  struct ByteRangeLockPB2	pb;
  int                     err;
  
  pb.unLockFlag = setLockFlag ? 0 : 1;
  pb.startEndFlag = 0;
  pb.offset = offset;
  pb.length = length; 
  pb.fd = fd;
  TRACE5("AFPLOCK setting lock %s for %d in range %llx:%llx\n", 
    (setLockFlag?"ON":"OFF"), fd, offset, length);
  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  if ( err==-1 ) {
    TRACE4("AFPLOCK failed to fsctl() '%s' %d %s\n", path, errno, 
      strerror(errno));
    return 1; // error
  } else {
    return 0;
  }
}

/*
 ** This routine checks if there is a RESERVED lock held on the specified
 ** file by this or any other process. If such a lock is held, return
 ** non-zero.  If the file is unlocked or holds only SHARED locks, then
 ** return zero.
 */
static int afpUnixCheckReservedLock(OsFile *id){
  int r = 0;
  unixFile *pFile = (unixFile*)id;
  
  assert( pFile ); 
  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  
  /* Check if a thread in this process holds such a lock */
  if( pFile->locktype>SHARED_LOCK ){
    r = 1;
  }
  
  /* Otherwise see if some other process holds it.
   */
  if ( !r ) {
    // lock the byte
    int failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);  
    if (failed) {
      /* if we failed to get the lock then someone else must have it */
      r = 1;
    } else {
      /* if we succeeded in taking the reserved lock, unlock it to restore
      ** the original state */
      _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0);
    }
  }
  TRACE3("TEST WR-LOCK %d %d\n", pFile->h, r);
  
  return r;
}

/* AFP-style locking following the behavior of unixLock, see the unixLock 
** function comments for details of lock management. */
static int afpUnixLock(OsFile *id, int locktype)
{
  int rc = SQLITE_OK;
  unixFile *pFile = (unixFile*)id;
  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  int gotPendingLock = 0;
  
  assert( pFile );
  TRACE5("LOCK    %d %s was %s pid=%d\n", pFile->h,
         locktypeName(locktype), locktypeName(pFile->locktype), getpid());  
  /* If there is already a lock of this type or more restrictive on the
    ** OsFile, do nothing. Don't use the afp_end_lock: exit path, as
    ** sqlite3OsEnterMutex() hasn't been called yet.
    */
  if( pFile->locktype>=locktype ){
    TRACE3("LOCK    %d %s ok (already held)\n", pFile->h,
           locktypeName(locktype));
    return SQLITE_OK;
  }

  /* Make sure the locking sequence is correct
    */
  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  assert( locktype!=PENDING_LOCK );
  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  
  /* This mutex is needed because pFile->pLock is shared across threads
    */
  sqlite3OsEnterMutex();

  /* Make sure the current thread owns the pFile.
    */
  rc = transferOwnership(pFile);
  if( rc!=SQLITE_OK ){
    sqlite3OsLeaveMutex();
    return rc;
  }
    
  /* A PENDING lock is needed before acquiring a SHARED lock and before
    ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
    ** be released.
    */
  if( locktype==SHARED_LOCK 
      || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
      ){
    int failed = _AFPFSSetLock(context->filePath, pFile->h, 
      PENDING_BYTE, 1, 1);
    if (failed) {
      rc = SQLITE_BUSY;
      goto afp_end_lock;
    }
  }
  
  /* If control gets to this point, then actually go ahead and make
    ** operating system calls for the specified lock.
    */
  if( locktype==SHARED_LOCK ){
    int lk, failed;
    int tries = 0;
    
    /* Now get the read-lock */
    /* note that the quality of the randomness doesn't matter that much */
    lk = random(); 
    context->sharedLockByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
    failed = _AFPFSSetLock(context->filePath, pFile->h, 
      SHARED_FIRST+context->sharedLockByte, 1, 1);
    
    /* Drop the temporary PENDING lock */
    if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)) {
      rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
      goto afp_end_lock;
    }
    
    if( failed ){
      rc = SQLITE_BUSY;
    } else {
      pFile->locktype = SHARED_LOCK;
    }
  }else{
    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
    ** assumed that there is a SHARED or greater lock on the file
    ** already.
    */
    int failed = 0;
    assert( 0!=pFile->locktype );
    if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
        /* Acquire a RESERVED lock */
        failed = _AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1,1);
    }
    if (!failed && locktype == EXCLUSIVE_LOCK) {
      /* Acquire an EXCLUSIVE lock */
        
      /* Remove the shared lock before trying the range.  we'll need to 
      ** reestablish the shared lock if we can't get the  afpUnixUnlock
      */
      if (!_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
                         context->sharedLockByte, 1, 0)) {
        /* now attemmpt to get the exclusive lock range */
        failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST, 
                               SHARED_SIZE, 1);
        if (failed && _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST +
                                    context->sharedLockByte, 1, 1)) {
          rc = SQLITE_IOERR_RDLOCK; /* this should never happen */
        }
      } else {
        /* */
        rc = SQLITE_IOERR_UNLOCK; /* this should never happen */
      }
    }
    if( failed && rc == SQLITE_OK){
      rc = SQLITE_BUSY;
    }
  }
  
  if( rc==SQLITE_OK ){
    pFile->locktype = locktype;
  }else if( locktype==EXCLUSIVE_LOCK ){
    pFile->locktype = PENDING_LOCK;
  }
  
afp_end_lock:
    sqlite3OsLeaveMutex();
  TRACE4("LOCK    %d %s %s\n", pFile->h, locktypeName(locktype), 
         rc==SQLITE_OK ? "ok" : "failed");
  return rc;
}

/*
 ** Lower the locking level on file descriptor pFile to locktype.  locktype
 ** must be either NO_LOCK or SHARED_LOCK.
 **
 ** If the locking level of the file descriptor is already at or below
 ** the requested locking level, this routine is a no-op.
 */
static int afpUnixUnlock(OsFile *id, int locktype) {
  struct flock lock;
  int rc = SQLITE_OK;
  unixFile *pFile = (unixFile*)id;
  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;

  assert( pFile );
  TRACE5("UNLOCK  %d %d was %d pid=%d\n", pFile->h, locktype,
         pFile->locktype, getpid());
  
  assert( locktype<=SHARED_LOCK );
  if( pFile->locktype<=locktype ){
    return SQLITE_OK;
  }
  if( CHECK_THREADID(pFile) ){
    return SQLITE_MISUSE;
  }
  sqlite3OsEnterMutex();
  if( pFile->locktype>SHARED_LOCK ){
    if( locktype==SHARED_LOCK ){
      int failed = 0;

      /* unlock the exclusive range - then re-establish the shared lock */
      if (pFile->locktype==EXCLUSIVE_LOCK) {
        failed = _AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST, 
                                 SHARED_SIZE, 0);
        if (!failed) {
          /* successfully removed the exclusive lock */
          if (_AFPFSSetLock(context->filePath, pFile->h, SHARED_FIRST+
                            context->sharedLockByte, 1, 1)) {
            /* failed to re-establish our shared lock */
            rc = SQLITE_IOERR_RDLOCK; /* This should never happen */
          }
        } else {
          /* This should never happen - failed to unlock the exclusive range */
          rc = SQLITE_IOERR_UNLOCK;
        } 
      }
    }
    if (rc == SQLITE_OK && pFile->locktype>=PENDING_LOCK) {
      if (_AFPFSSetLock(context->filePath, pFile->h, PENDING_BYTE, 1, 0)){
        /* failed to release the pending lock */
        rc = SQLITE_IOERR_UNLOCK; /* This should never happen */
      }
    } 
    if (rc == SQLITE_OK && pFile->locktype>=RESERVED_LOCK) {
      if (_AFPFSSetLock(context->filePath, pFile->h, RESERVED_BYTE, 1, 0)) {
        /* failed to release the reserved lock */
        rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
      }
    } 
  }
  if( locktype==NO_LOCK ){
    int failed = _AFPFSSetLock(context->filePath, pFile->h, 
                               SHARED_FIRST + context->sharedLockByte, 1, 0);
    if (failed) {
      rc = SQLITE_IOERR_UNLOCK;  /* This should never happen */
    }
  }
  if (rc == SQLITE_OK)
    pFile->locktype = locktype;
  sqlite3OsLeaveMutex();
  return rc;
}

/*
 ** Close a file & cleanup AFP specific locking context 
 */
static int afpUnixClose(OsFile **pId) {
  unixFile *id = (unixFile*)*pId;
  
  if( !id ) return SQLITE_OK;
  afpUnixUnlock(*pId, NO_LOCK);
  /* free the AFP locking structure */
  if (id->lockingContext != NULL) {
    if (((afpLockingContext *)id->lockingContext)->filePath != NULL)
      sqlite3ThreadSafeFree(((afpLockingContext*)id->lockingContext)->filePath);
    sqlite3ThreadSafeFree(id->lockingContext);
  }
  
  if( id->dirfd>=0 ) close(id->dirfd);
  id->dirfd = -1;
  close(id->h);
  id->isOpen = 0;
  TRACE2("CLOSE   %-3d\n", id->h);
  OpenCounter(-1);
  sqlite3ThreadSafeFree(id);
  *pId = 0;
  return SQLITE_OK;
}


#pragma mark flock() style locking

/*
 ** The flockLockingContext is not used
 */
typedef void flockLockingContext;

static int flockUnixCheckReservedLock(OsFile *id) {
  unixFile *pFile = (unixFile*)id;
  
  if (pFile->locktype == RESERVED_LOCK) {
    return 1; // already have a reserved lock
  } else {
    // attempt to get the lock
    int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
    if (!rc) {
      // got the lock, unlock it
      flock(pFile->h, LOCK_UN);
      return 0;  // no one has it reserved
    }
    return 1; // someone else might have it reserved
  }
}

static int flockUnixLock(OsFile *id, int locktype) {
  unixFile *pFile = (unixFile*)id;
  
  // if we already have a lock, it is exclusive.  
  // Just adjust level and punt on outta here.
  if (pFile->locktype > NO_LOCK) {
    pFile->locktype = locktype;
    return SQLITE_OK;
  }
  
  // grab an exclusive lock
  int rc = flock(pFile->h, LOCK_EX | LOCK_NB);
  if (rc) {
    // didn't get, must be busy
    return SQLITE_BUSY;
  } else {
    // got it, set the type and return ok
    pFile->locktype = locktype;
    return SQLITE_OK;
  }
}

static int flockUnixUnlock(OsFile *id, int locktype) {
  unixFile *pFile = (unixFile*)id;
  
  assert( locktype<=SHARED_LOCK );
  
  // no-op if possible
  if( pFile->locktype==locktype ){
    return SQLITE_OK;
  }
  
  // shared can just be set because we always have an exclusive
  if (locktype==SHARED_LOCK) {
    pFile->locktype = locktype;
    return SQLITE_OK;
  }
  
  // no, really, unlock.
  int rc = flock(pFile->h, LOCK_UN);
  if (rc)
    return SQLITE_IOERR_UNLOCK;
  else {
    pFile->locktype = NO_LOCK;
    return SQLITE_OK;
  }
}

/*
 ** Close a file.
 */
static int flockUnixClose(OsFile **pId) {
  unixFile *id = (unixFile*)*pId;
  
  if( !id ) return SQLITE_OK;
  flockUnixUnlock(*pId, NO_LOCK);
  
  if( id->dirfd>=0 ) close(id->dirfd);
  id->dirfd = -1;
  sqlite3OsEnterMutex();
  
  close(id->h);  
  sqlite3OsLeaveMutex();
  id->isOpen = 0;
  TRACE2("CLOSE   %-3d\n", id->h);
  OpenCounter(-1);
  sqlite3ThreadSafeFree(id);
  *pId = 0;
  return SQLITE_OK;
}

#pragma mark Old-School .lock file based locking

/*
 ** The dotlockLockingContext structure contains all dotlock (.lock) lock
 ** specific state
 */
typedef struct dotlockLockingContext dotlockLockingContext;
struct dotlockLockingContext {
  char *lockPath;
};


static int dotlockUnixCheckReservedLock(OsFile *id) {
  unixFile *pFile = (unixFile*)id;
  dotlockLockingContext *context = 
    (dotlockLockingContext *) pFile->lockingContext;
  
  if (pFile->locktype == RESERVED_LOCK) {
    return 1; // already have a reserved lock
  } else {
    struct stat statBuf;
    if (lstat(context->lockPath,&statBuf) == 0)
      // file exists, someone else has the lock
      return 1;
    else
      // file does not exist, we could have it if we want it
      return 0;
  }
}

static int dotlockUnixLock(OsFile *id, int locktype) {
  unixFile *pFile = (unixFile*)id;
  dotlockLockingContext *context = 
    (dotlockLockingContext *) pFile->lockingContext;
  
  // if we already have a lock, it is exclusive.  
  // Just adjust level and punt on outta here.
  if (pFile->locktype > NO_LOCK) {
    pFile->locktype = locktype;
    
    /* Always update the timestamp on the old file */
    utimes(context->lockPath,NULL);
    return SQLITE_OK;
  }
  
  // check to see if lock file already exists
  struct stat statBuf;
  if (lstat(context->lockPath,&statBuf) == 0){
    return SQLITE_BUSY; // it does, busy
  }
  
  // grab an exclusive lock
  int fd = open(context->lockPath,O_RDONLY|O_CREAT|O_EXCL,0600);
  if (fd < 0) {
    // failed to open/create the file, someone else may have stolen the lock
    return SQLITE_BUSY; 
  }
  close(fd);
  
  // got it, set the type and return ok
  pFile->locktype = locktype;
  return SQLITE_OK;
}

static int dotlockUnixUnlock(OsFile *id, int locktype) {
  unixFile *pFile = (unixFile*)id;
  dotlockLockingContext *context = 
    (dotlockLockingContext *) pFile->lockingContext;
  
  assert( locktype<=SHARED_LOCK );
  
  // no-op if possible
  if( pFile->locktype==locktype ){
    return SQLITE_OK;
  }
  
  // shared can just be set because we always have an exclusive
  if (locktype==SHARED_LOCK) {
    pFile->locktype = locktype;
    return SQLITE_OK;
  }
  
  // no, really, unlock.
  unlink(context->lockPath);
  pFile->locktype = NO_LOCK;
  return SQLITE_OK;
}

/*
 ** Close a file.
 */
static int dotlockUnixClose(OsFile **pId) {
  unixFile *id = (unixFile*)*pId;
  
  if( !id ) return SQLITE_OK;
  dotlockUnixUnlock(*pId, NO_LOCK);
  /* free the dotlock locking structure */
  if (id->lockingContext != NULL) {
    if (((dotlockLockingContext *)id->lockingContext)->lockPath != NULL)
      sqlite3ThreadSafeFree( ( (dotlockLockingContext *)
        id->lockingContext)->lockPath);
    sqlite3ThreadSafeFree(id->lockingContext);
  }
  
  if( id->dirfd>=0 ) close(id->dirfd);
  id->dirfd = -1;
  sqlite3OsEnterMutex();
  
  close(id->h);
  
  sqlite3OsLeaveMutex();
  id->isOpen = 0;
  TRACE2("CLOSE   %-3d\n", id->h);
  OpenCounter(-1);
  sqlite3ThreadSafeFree(id);
  *pId = 0;
  return SQLITE_OK;
}


#pragma mark No locking

/*
 ** The nolockLockingContext is void
 */
typedef void nolockLockingContext;

static int nolockUnixCheckReservedLock(OsFile *id) {
  return 0;
}

static int nolockUnixLock(OsFile *id, int locktype) {
  return SQLITE_OK;
}

static int nolockUnixUnlock(OsFile *id, int locktype) {
  return SQLITE_OK;
}

/*
 ** Close a file.
 */
static int nolockUnixClose(OsFile **pId) {
  unixFile *id = (unixFile*)*pId;
  
  if( !id ) return SQLITE_OK;
  if( id->dirfd>=0 ) close(id->dirfd);
  id->dirfd = -1;
  sqlite3OsEnterMutex();
  
  close(id->h);
  
  sqlite3OsLeaveMutex();
  id->isOpen = 0;
  TRACE2("CLOSE   %-3d\n", id->h);
  OpenCounter(-1);
  sqlite3ThreadSafeFree(id);
  *pId = 0;
  return SQLITE_OK;
}

#endif /* SQLITE_ENABLE_LOCKING_STYLE */

/*
** Turn a relative pathname into a full pathname.  Return a pointer
** to the full pathname stored in space obtained from sqliteMalloc().
** The calling function is responsible for freeing this space once it
** is no longer needed.
*/
char *sqlite3UnixFullPathname(const char *zRelative){
1669
1670
1671
1672
1673
1674
1675

1676






















































































1677
1678
1679
1680







1681






























































































1682














1683
1684
1685
1686

1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
  unixFileSize,
  unixLock,
  unixUnlock,
  unixLockState,
  unixCheckReservedLock,
};


/*






















































































** Allocate memory for a unixFile.  Initialize the new unixFile
** to the value given in pInit and return a pointer to the new
** OsFile.  If we run out of memory, close the file and return NULL.
*/







static int allocateUnixFile(unixFile *pInit, OsFile **pId){






























































































  unixFile *pNew;














  pInit->dirfd = -1;
  pInit->fullSync = 0;
  pInit->locktype = 0;
  pInit->offset = 0;

  SET_THREADID(pInit);
  pNew = sqlite3ThreadSafeMalloc( sizeof(unixFile) );
  if( pNew==0 ){
    close(pInit->h);
    sqlite3OsEnterMutex();
    releaseLockInfo(pInit->pLock);
    releaseOpenCnt(pInit->pOpen);
    sqlite3OsLeaveMutex();
    *pId = 0;
    return SQLITE_NOMEM;
  }else{
    *pNew = *pInit;
    pNew->pMethod = &sqlite3UnixIoMethod;
    *pId = (OsFile*)pNew;
    OpenCounter(+1);
    return SQLITE_OK;
  }
}


#endif /* SQLITE_OMIT_DISKIO */
/***************************************************************************
** Everything above deals with file I/O.  Everything that follows deals
** with other miscellanous aspects of the operating system interface
****************************************************************************/








>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
|

>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
|
|
>
|


|

|
|




|






|







2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
  unixFileSize,
  unixLock,
  unixUnlock,
  unixLockState,
  unixCheckReservedLock,
};

#ifdef SQLITE_ENABLE_LOCKING_STYLE
/*
 ** This vector defines all the methods that can operate on an OsFile
 ** for unix with AFP style file locking.
 */
static const IoMethod sqlite3AFPLockingUnixIoMethod = {
    afpUnixClose,
    unixOpenDirectory,
    unixRead,
    unixWrite,
    unixSeek,
    unixTruncate,
    unixSync,
    unixSetFullSync,
    unixFileHandle,
    unixFileSize,
    afpUnixLock,
    afpUnixUnlock,
    unixLockState,
    afpUnixCheckReservedLock,
};

/*
 ** This vector defines all the methods that can operate on an OsFile
 ** for unix with flock() style file locking.
 */
static const IoMethod sqlite3FlockLockingUnixIoMethod = {
    flockUnixClose,
    unixOpenDirectory,
    unixRead,
    unixWrite,
    unixSeek,
    unixTruncate,
    unixSync,
    unixSetFullSync,
    unixFileHandle,
    unixFileSize,
    flockUnixLock,
    flockUnixUnlock,
    unixLockState,
    flockUnixCheckReservedLock,
};

/*
 ** This vector defines all the methods that can operate on an OsFile
 ** for unix with dotlock style file locking.
 */
static const IoMethod sqlite3DotlockLockingUnixIoMethod = {
    dotlockUnixClose,
    unixOpenDirectory,
    unixRead,
    unixWrite,
    unixSeek,
    unixTruncate,
    unixSync,
    unixSetFullSync,
    unixFileHandle,
    unixFileSize,
    dotlockUnixLock,
    dotlockUnixUnlock,
    unixLockState,
    dotlockUnixCheckReservedLock,
};

/*
 ** This vector defines all the methods that can operate on an OsFile
 ** for unix with dotlock style file locking.
 */
static const IoMethod sqlite3NolockLockingUnixIoMethod = {
  nolockUnixClose,
  unixOpenDirectory,
  unixRead,
  unixWrite,
  unixSeek,
  unixTruncate,
  unixSync,
  unixSetFullSync,
  unixFileHandle,
  unixFileSize,
  nolockUnixLock,
  nolockUnixUnlock,
  unixLockState,
  nolockUnixCheckReservedLock,
};

#endif /* SQLITE_ENABLE_LOCKING_STYLE */

/*
** Allocate memory for a new unixFile and initialize that unixFile.
** Write a pointer to the new unixFile into *pId.
** If we run out of memory, close the file and return an error.
*/
#ifdef SQLITE_ENABLE_LOCKING_STYLE
/* 
 ** When locking extensions are enabled, the filepath and locking style 
 ** are needed to determine the unixFile pMethod to use for locking operations.
 ** The locking-style specific lockingContext data structure is created 
 ** and assigned here also.
 */
static int allocateUnixFile(
  int h,                  /* Open file descriptor of file being opened */
  OsFile **pId,           /* Write completed initialization here */
  const char *zFilename,  /* Name of the file being opened */
  int delFlag             /* Delete-on-or-before-close flag */
){
  sqlite3LockingStyle lockStyle;
  unixFile *pNew;
  unixFile f;
  int rc;

  lockingStyle = sqlite3DetectLockingStyle(zFilename, f.h);
  if ( lockingStyle == posixLockingStyle ) {
    sqlite3OsEnterMutex();
    rc = findLockInfo(h, &f.pLock, &f.pOpen);
    sqlite3OsLeaveMutex();
    if( rc ){
      close(h);
      unlink(zFilename);
      return SQLITE_NOMEM;
    }
  } else {
    //  pLock and pOpen are only used for posix advisory locking 
    f.pLock = NULL;
    f.pOpen = NULL;
  }
  if( delFlag ){
    unlink(zFilename);
  }
  f.dirfd = -1;
  f.fullSync = 0;
  f.locktype = 0;
  f.offset = 0;
  f.h = h;
  SET_THREADID(&f);
  pNew = sqlite3ThreadSafeMalloc( sizeof(unixFile) );
  if( pNew==0 ){
    close(h);
    sqlite3OsEnterMutex();
    releaseLockInfo(f.pLock);
    releaseOpenCnt(f.pOpen);
    sqlite3OsLeaveMutex();
    *pId = 0;
    return SQLITE_NOMEM;
  }else{
    *pNew = f;
    switch(lockStyle) {
      case afpLockingStyle:
        /* afp locking uses the file path so it needs to be included in
        ** the afpLockingContext */
        pNew->pMethod = &sqlite3AFPLockingUnixIoMethod;
        pNew->lockingContext = 
          sqlite3ThreadSafeMalloc(sizeof(afpLockingContext));
        ((afpLockingContext *)pNew->lockingContext)->filePath = 
          sqlite3ThreadSafeMalloc(strlen(zFilename) + 1);
        strcpy(((afpLockingContext *)pNew->lockingContext)->filePath, 
               zFilename);
        srandomdev();
        break;
      case flockLockingStyle:
        /* flock locking doesn't need additional lockingContext information */
        pNew->pMethod = &sqlite3FlockLockingUnixIoMethod;
        break;
      case dotlockLockingStyle:
        /* dotlock locking uses the file path so it needs to be included in
         ** the dotlockLockingContext */
        pNew->pMethod = &sqlite3DotlockLockingUnixIoMethod;
        pNew->lockingContext = sqlite3ThreadSafeMalloc(
          sizeof(dotlockLockingContext));
        ((dotlockLockingContext *)pNew->lockingContext)->lockPath = 
            sqlite3ThreadSafeMalloc(strlen(zFilename) + strlen(".lock") + 1);
        sprintf(((dotlockLockingContext *)pNew->lockingContext)->lockPath, 
                "%s.lock", zFilename);
        break;
      case posixLockingStyle:
        /* posix locking doesn't need additional lockingContext information */
        pNew->pMethod = &sqlite3UnixIoMethod;
        break;
      case noLockingStyle:
      case unsupportedLockingStyle:
      default: 
        pNew->pMethod = &sqlite3NolockLockingUnixIoMethod;
    }
    *pId = (OsFile*)pNew;
    OpenCounter(+1);
    return SQLITE_OK;
  }
}
#else /* SQLITE_ENABLE_LOCKING_STYLE */
static int allocateUnixFile(
  int h,                 /* Open file descriptor on file being opened */
  OsFile **pId,          /* Write the resul unixFile structure here */
  const char *zFilename, /* Name of the file being opened */
  int delFlag            /* If true, delete the file on or before closing */
){
  unixFile *pNew;
  unixFile f;
  int rc;

  sqlite3OsEnterMutex();
  rc = findLockInfo(h, &f.pLock, &f.pOpen);
  sqlite3OsLeaveMutex();
  if( delFlag ){
    unlink(zFilename);
  }
  if( rc ){
    close(h);
    return SQLITE_NOMEM;
  }
  TRACE3("OPEN    %-3d %s\n", h, zFilename);
  f.dirfd = -1;
  f.fullSync = 0;
  f.locktype = 0;
  f.offset = 0;
  f.h = h;
  SET_THREADID(&f);
  pNew = sqlite3ThreadSafeMalloc( sizeof(unixFile) );
  if( pNew==0 ){
    close(h);
    sqlite3OsEnterMutex();
    releaseLockInfo(f.pLock);
    releaseOpenCnt(f.pOpen);
    sqlite3OsLeaveMutex();
    *pId = 0;
    return SQLITE_NOMEM;
  }else{
    *pNew = f;
    pNew->pMethod = &sqlite3UnixIoMethod;
    *pId = (OsFile*)pNew;
    OpenCounter(+1);
    return SQLITE_OK;
  }
}
#endif /* SQLITE_ENABLE_LOCKING_STYLE */

#endif /* SQLITE_OMIT_DISKIO */
/***************************************************************************
** Everything above deals with file I/O.  Everything that follows deals
** with other miscellanous aspects of the operating system interface
****************************************************************************/