myvfs.c
Go to the documentation of this file.
1 #pragma GCC diagnostic ignored "-Wcast-qual"
2 #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
3 #pragma GCC diagnostic ignored "-Wunused-function"
4 #pragma GCC diagnostic ignored "-Wunused-parameter"
5 
6 /*#include "sqliteInt.h"*/
7 #include <sqlite3.h>
8 #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
9 #define SQLITE_FCNTL_SIZE_HINT 5
10 #define SQLITE_FCNTL_CHUNK_SIZE 6
11 #define SQLITE_FCNTL_SYNC_OMITTED 8
12 
13 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
14 #define SQLITE_DEFAULT_SECTOR_SIZE 512
15 
16 #define UNUSED_PARAMETER(x) (void)(x)
17 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
18 
19 #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
20 
21 typedef sqlite_int64 i64;
22 
23 #define _LARGE_FILE 1
24 #define _FILE_OFFSET_BITS 64
25 #define _LARGEFILE_SOURCE 1
26 
27 #include <assert.h>
28 #include <dlfcn.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <sys/stat.h>
35 #include <sys/time.h>
36 #include <sys/types.h>
37 #include <time.h>
38 #include <unistd.h>
39 
40 /*
41 ** Default permissions when creating a new file
42 */
43 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
44 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
45 #endif
46 
47 /*
48 ** Maximum supported path-length.
49 */
50 #define MAX_PATHNAME 512
51 
52 #define SQLITE_TEMP_FILE_PREFIX "etilqs_"
53 
54 typedef struct unixShmNode unixShmNode; /* Shared memory instance */
55 
56 /*
57 ** An instance of the following structure serves as the key used
58 ** to locate a particular unixInodeInfo object.
59 */
60 struct unixFileId {
61  dev_t dev; /* Device number */
62  ino_t ino; /* Inode number */
63 };
64 
65 
66 /*
67 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
68 ** cannot be closed immediately. In these cases, instances of the following
69 ** structure are used to store the file descriptor while waiting for an
70 ** opportunity to either close or reuse it.
71 */
72 struct UnixUnusedFd {
73  int fd; /* File descriptor to close */
74  int flags; /* Flags this file descriptor was opened with */
75  struct UnixUnusedFd * pNext; /* Next unused file descriptor on same file */
76 };
77 
78 /*
79 ** An instance of the following structure is allocated for each open
80 ** inode. Or, on LinuxThreads, there is one of these structures for
81 ** each inode opened by each thread.
82 **
83 ** A single inode can have multiple file descriptors, so each unixFile
84 ** structure contains a pointer to an instance of this object and this
85 ** object keeps a count of the number of unixFile pointing to it.
86 */
87 struct unixInodeInfo {
88  struct unixFileId fileId; /* The lookup key */
89  int nShared; /* Number of SHARED locks held */
90  unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
91  unsigned char bProcessLock; /* An exclusive process lock is held */
92  int nRef; /* Number of pointers to this structure */
93  unixShmNode * pShmNode; /* Shared memory associated with this inode */
94  int nLock; /* Number of outstanding file locks */
95  struct UnixUnusedFd * pUnused; /* Unused file descriptors to close */
96  struct unixInodeInfo * pNext; /* List of all unixInodeInfo objects */
97  struct unixInodeInfo * pPrev; /* .... doubly linked */
98 };
99 
100 /*
101 ** A lists of all unixInodeInfo objects.
102 */
103 static struct unixInodeInfo * inodeList = 0;
104 
105 /*
106 ** The unixFile structure is subclass of sqlite3_file specific to the unix
107 ** VFS implementations.
108 */
109 typedef struct unixFile unixFile;
110 struct unixFile {
111  sqlite3_io_methods const * pMethod; /* Always the first entry */
112  struct unixInodeInfo * pInode; /* Info about locks on this inode */
113  int h; /* The file descriptor */
114  int dirfd; /* File descriptor for the directory */
115  unsigned char eFileLock; /* The type of lock held on this fd */
116  unsigned char ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
117  int lastErrno; /* The unix errno from last I/O error */
118  void * lockingContext; /* Locking style specific state */
119  struct UnixUnusedFd * pUnused; /* Pre-allocated UnixUnusedFd */
120  const char * zPath; /* Name of the file */
121  int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
122  /* The next group of variables are used to track whether or not the
123  ** transaction counter in bytes 24-27 of database files are updated
124  ** whenever any part of the database changes. An assertion fault will
125  ** occur if a file is updated without also updating the transaction
126  ** counter. This test is made to avoid new problems similar to the
127  ** one described by ticket #3584.
128  */
129  unsigned char transCntrChng; /* True if the transaction counter changed */
130  unsigned char dbUpdate; /* True if any part of database file changed */
131  unsigned char inNormalWrite; /* True if in a normal write operation */
132 };
133 
134 /*
135 ** Allowed values for the unixFile.ctrlFlags bitmask:
136 */
137 #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
138 #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
139 
140 /*
141 ** Define various macros that are missing from some systems.
142 */
143 #ifndef O_LARGEFILE
144 # define O_LARGEFILE 0
145 #endif
146 #ifdef SQLITE_DISABLE_LFS
147 # undef O_LARGEFILE
148 # define O_LARGEFILE 0
149 #endif
150 #ifndef O_NOFOLLOW
151 # define O_NOFOLLOW 0
152 #endif
153 #ifndef O_BINARY
154 # define O_BINARY 0
155 #endif
156 
157 #if 0 /* F13 */
158 typedef void (*sqlite3_syscall_ptr)(void);
159 #endif /* 0 */
160 
161 /* Function Directory */
162 static int sqlite3CantopenError(int lineno);
163 static int sqlite3Strlen30(const char * z);
164 static const sqlite3_io_methods * nolockIoFinderImpl(const char * z, unixFile * p);
165 static int unixLogErrorAtLine(int errcode, const char * zFunc, const char * zPath, int iLine);
166 static int robust_open(const char * z, int f, int m);
167 static void robust_close(unixFile * pFile, int h, int lineno);
168 static int robust_ftruncate(int h, sqlite3_int64 sz);
169 static int fillInUnixFile(sqlite3_vfs * pVfs, int h, int dirfd, sqlite3_file * pId, const char * zFilename, int noLock, int isDelete, int isReadOnly);
170 static int openDirectory(const char * zFilename, int * pFd);
171 static const char * unixTempFileDir(void);
172 static int unixGetTempname(int nBuf, char * zBuf);
173 static struct UnixUnusedFd * findReusableFd(const char * zPath, int flags);
174 static int findCreateFileMode(const char * zPath, int flags, mode_t * pMode);
175 static int fcntlSizeHint(unixFile * pFile, i64 nByte);
176 static int full_fsync(int fd, int fullSync, int dataOnly);
177 static int seekAndRead(unixFile * id, sqlite3_int64 offset, void * pBuf, int cnt);
178 static int seekAndWrite(unixFile * id, i64 offset, const void * pBuf, int cnt);
179 /* IoMethods calls */
180 static int nolockClose(sqlite3_file * id);
181 static int unixRead(sqlite3_file * id, void * pBuf, int amt, sqlite3_int64 offset);
182 static int unixWrite(sqlite3_file * id, const void * pBuf, int amt, sqlite3_int64 offset);
183 static int unixTruncate(sqlite3_file * id, i64 nByte);
184 static int unixSync(sqlite3_file * id, int flags);
185 static int unixFileSize(sqlite3_file * id, i64 * pSize);
186 static int nolockLock(sqlite3_file * NotUsed, int NotUsed2);
187 static int nolockUnlock(sqlite3_file * NotUsed, int NotUsed2);
188 static int nolockCheckReservedLock(sqlite3_file * NotUsed, int * pResOut);
189 static int unixFileControl(sqlite3_file * id, int op, void * pArg);
190 static int unixSectorSize(sqlite3_file * NotUsed);
191 static int unixDeviceCharacteristics(sqlite3_file * NotUsed);
192 /* VFS calls */
193 static int unixOpen(sqlite3_vfs * pVfs, const char * zPath, sqlite3_file * pFile, int flags, int * pOutFlags);
194 static int unixDelete(sqlite3_vfs * NotUsed, const char * zPath, int dirSync);
195 static int unixAccess(sqlite3_vfs * NotUsed, const char * zPath, int flags, int * pResOut);
196 static int unixFullPathname(sqlite3_vfs * pVfs, const char * zPath, int nOut, char * zOut);
197 static void * unixDlOpen(sqlite3_vfs * NotUsed, const char * zFilename);
198 static void unixDlError(sqlite3_vfs * NotUsed, int nBuf, char * zBufOut);
199 static void (*unixDlSym(sqlite3_vfs * NotUsed, void * p, const char * zSym))(void);
200 static void unixDlClose(sqlite3_vfs * NotUsed, void * pHandle);
201 static int unixRandomness(sqlite3_vfs * NotUsed, int nBuf, char * zBuf);
202 static int unixSleep(sqlite3_vfs * NotUsed, int microseconds);
203 static int unixCurrentTime(sqlite3_vfs * NotUsed, double * prNow);
204 static int unixGetLastError(sqlite3_vfs * NotUsed, int NotUsed2, char * NotUsed3);
205 static int unixCurrentTimeInt64(sqlite3_vfs * NotUsed, sqlite3_int64 * piNow);
206 static int unixSetSystemCall(sqlite3_vfs * pNotUsed, const char * zName, sqlite3_syscall_ptr pNewFunc);
207 static sqlite3_syscall_ptr unixGetSystemCall(sqlite3_vfs * pNotUsed, const char * zName);
208 static const char * unixNextSystemCall(sqlite3_vfs * p, const char * zName);
209 /**/
210 int sqlite3_os_init(void);
211 
212 static int sqlite3CantopenError(int lineno)
213 {
214 #if 0
215  sqlite3_log(SQLITE_CANTOPEN,
216  "cannot open file at line %d of [%.10s]",
217  lineno, 20 + sqlite3_sourceid());
218 #endif /* 0 */
219  fprintf(stderr,
220  "myvfs.c: cannot open file at line %d of [%.10s]",
221  lineno, 20 + sqlite3_sourceid());
222  return SQLITE_CANTOPEN;
223 }
224 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
225 
226 /*
227 ** Compute a string length that is limited to what can be stored in
228 ** lower 30 bits of a 32-bit signed integer.
229 **
230 ** The value returned will never be negative. Nor will it ever be greater
231 ** than the actual length of the string. For very long strings (greater
232 ** than 1GiB) the value returned might be less than the true string length.
233 */
234 static int sqlite3Strlen30(const char * z)
235 {
236  const char * z2 = z;
237  if (z == 0) {
238  return 0;
239  }
240  while (*z2) {
241  z2++;
242  }
243  return 0x3fffffff & (int)(z2 - z);
244 }
245 
246 /*
247 ** Many system calls are accessed through pointer-to-functions so that
248 ** they may be overridden at runtime to facilitate fault injection during
249 ** testing and sandboxing. The following array holds the names and pointers
250 ** to all overrideable system calls.
251 */
252 static struct unix_syscall {
253  const char * zName; /* Name of the sytem call */
254  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
255  sqlite3_syscall_ptr pDefault; /* Default value */
256 } aSyscall[] = {
257  { "open", (sqlite3_syscall_ptr)open, 0 },
258 #define osOpen ((int(*)(const char*,int,...))aSyscall[0].pCurrent)
259 
260  { "close", (sqlite3_syscall_ptr)close, 0 },
261 #define osClose ((int(*)(int))aSyscall[1].pCurrent)
262 
263  { "access", (sqlite3_syscall_ptr)access, 0 },
264 #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
265 
266  { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
267 #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
268 
269  { "stat", (sqlite3_syscall_ptr)stat, 0 },
270 #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
271 
272  /*
273  ** The DJGPP compiler environment looks mostly like Unix, but it
274  ** lacks the fcntl() system call. So redefine fcntl() to be something
275  ** that always succeeds. This means that locking does not occur under
276  ** DJGPP. But it is DOS - what did you expect?
277  */
278 #ifdef __DJGPP__
279  { "fstat", 0, 0 },
280 #define osFstat(a,b,c) 0
281 #else
282  { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
283 #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
284 #endif
285 
286  { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
287 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
288 
289  { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
290 #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
291 
292  { "read", (sqlite3_syscall_ptr)read, 0 },
293 #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
294 
295 #if defined(USE_PREAD)
296  { "pread", (sqlite3_syscall_ptr)pread, 0 },
297 #else
298  { "pread", (sqlite3_syscall_ptr)0, 0 },
299 #endif
300 #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
301 
302 #if defined(USE_PREAD64)
303  { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
304 #else
305  { "pread64", (sqlite3_syscall_ptr)0, 0 },
306 #endif
307 #define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
308 
309  { "write", (sqlite3_syscall_ptr)write, 0 },
310 #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
311 
312 #if defined(USE_PREAD)
313  { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
314 #else
315  { "pwrite", (sqlite3_syscall_ptr)0, 0 },
316 #endif
317 #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
318  aSyscall[12].pCurrent)
319 
320 #if defined(USE_PREAD64)
321  { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
322 #else
323  { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
324 #endif
325 #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
326  aSyscall[13].pCurrent)
327 
328  { "fchmod", (sqlite3_syscall_ptr)0, 0 },
329 #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
330 
331 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
332  { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
333 #else
334  { "fallocate", (sqlite3_syscall_ptr)0, 0 },
335 #endif
336 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
337 
338 }; /* End of the overrideable system calls */
339 
340 static const sqlite3_io_methods nolockIoMethods = {
341  1, /* iVersion */
342  nolockClose, /* xClose */
343  unixRead, /* xRead */
344  unixWrite, /* xWrite */
345  unixTruncate, /* xTruncate */
346  unixSync, /* xSync */
347  unixFileSize, /* xFileSize */
348  nolockLock, /* xLock */
349  nolockUnlock, /* xUnlock */
350  nolockCheckReservedLock, /* xCheckReservedLock */
351  unixFileControl, /* xFileControl */
352  unixSectorSize, /* xSectorSize */
353  unixDeviceCharacteristics, /* xDeviceCapabilities */
354 #if 0
355  0, /* xShmMap */
356  0, /* xShmLock */
357  0, /* xShmBarrier */
358  0 /* xShmUnmap */
359 #endif /* 0 */
360 };
361 
362 static const sqlite3_io_methods * nolockIoFinderImpl(const char * z, unixFile * p)
363 {
364  UNUSED_PARAMETER(z);
365  UNUSED_PARAMETER(p);
366  return &nolockIoMethods;
367 }
368 
369 static const sqlite3_io_methods * (*const nolockIoFinder)(const char *, unixFile * p)
371 
372 typedef const sqlite3_io_methods * (*finder_type)(const char *, unixFile *);
373 
374 /*
375 **
376 ** This function - unixLogError_x(), is only ever called via the macro
377 ** unixLogError().
378 **
379 ** It is invoked after an error occurs in an OS function and errno has been
380 ** set. It logs a message using sqlite3_log() containing the current value of
381 ** errno and, if possible, the human-readable equivalent from strerror() or
382 ** strerror_r().
383 **
384 ** The first argument passed to the macro should be the error code that
385 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
386 ** The two subsequent arguments should be the name of the OS function that
387 ** failed (e.g. "unlink", "open") and the the associated file-system path,
388 ** if any.
389 */
390 #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
392  int errcode, /* SQLite error code */
393  const char * zFunc, /* Name of OS function that failed */
394  const char * zPath, /* File path associated with error */
395  int iLine /* Source line number where error occurred */
396 )
397 {
398  char * zErr; /* Message from strerror() or equivalent */
399  int iErrno = errno; /* Saved syscall error number */
400  zErr = strerror(iErrno);
401  assert(errcode != SQLITE_OK);
402  if (zPath == 0) {
403  zPath = "";
404  }
405 #if 0
406  sqlite3_log(errcode,
407  "os_unix.c:%d: (%d) %s(%s) - %s",
408  iLine, iErrno, zFunc, zPath, zErr
409  );
410 #endif /* 0 */
411  fprintf(stderr,
412  "myvfs.c:%d: (%d) %s(%s) - %s",
413  iLine, iErrno, zFunc, zPath, zErr
414  );
415  return errcode;
416 }
417 
418 /*
419 ** Retry open() calls that fail due to EINTR
420 */
421 static int robust_open(const char * z, int f, int m)
422 {
423  int rc;
424  do {
425  rc = osOpen(z, f, m);
426  }
427  while (rc < 0 && errno == EINTR);
428  return rc;
429 }
430 
431 /*
432  * ** Close a file descriptor.
433  * **
434  * ** We assume that close() almost always works, since it is only in a
435  * ** very sick application or on a very sick platform that it might fail.
436  * ** If it does fail, simply leak the file descriptor, but do log the
437  * ** error.
438  * **
439  * ** Note that it is not safe to retry close() after EINTR since the
440  * ** file descriptor might have already been reused by another thread.
441  * ** So we don't even try to recover from an EINTR. Just log the error
442  * ** and move on.
443  * */
444 static void robust_close(unixFile * pFile, int h, int lineno)
445 {
446  if (osClose(h)) {
447  unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close", pFile ? pFile->zPath : 0, lineno);
448  }
449 }
450 
451 /*
452 ** Retry ftruncate() calls that fail due to EINTR
453 */
454 static int robust_ftruncate(int h, sqlite3_int64 sz)
455 {
456  int rc;
457  do {
458  rc = osFtruncate(h, sz);
459  }
460  while (rc < 0 && errno == EINTR);
461  return rc;
462 }
463 
464 /*
465  * ** This function performs the parts of the "close file" operation
466  * ** common to all locking schemes. It closes the directory and file
467  * ** handles, if they are valid, and sets all fields of the unixFile
468  * ** structure to 0.
469  * **
470  * ** It is *not* necessary to hold the mutex when this routine is called,
471  * ** even on VxWorks. A mutex will be acquired on VxWorks by the
472  * ** vxworksReleaseFileId() routine.
473  * */
474 static int closeUnixFile(sqlite3_file * id)
475 {
476  unixFile * pFile = (unixFile *)id;
477  if (pFile->dirfd >= 0) {
478  robust_close(pFile, pFile->dirfd, __LINE__);
479  pFile->dirfd = -1;
480  }
481  if (pFile->h >= 0) {
482  robust_close(pFile, pFile->h, __LINE__);
483  pFile->h = -1;
484  }
485  sqlite3_free(pFile->pUnused);
486  memset(pFile, 0, sizeof(unixFile));
487  return SQLITE_OK;
488 }
489 
490 /*
491 ** Initialize the contents of the unixFile structure pointed to by pId.
492 */
493 static int fillInUnixFile(
494  sqlite3_vfs * pVfs, /* Pointer to vfs object */
495  int h, /* Open file descriptor of file being opened */
496  int dirfd, /* Directory file descriptor */
497  sqlite3_file * pId, /* Write to the unixFile structure here */
498  const char * zFilename, /* Name of the file being opened */
499  int noLock, /* Omit locking if true */
500  int isDelete, /* Delete on close if true */
501  int isReadOnly /* True if the file is opened read-only */
502 )
503 {
504  const sqlite3_io_methods * pLockingStyle;
505  unixFile * pNew = (unixFile *)pId;
506  int rc = SQLITE_OK;
507  assert(pNew->pInode == NULL);
508  /* Parameter isDelete is only used on vxworks. Express this explicitly
509  ** here to prevent compiler warnings about unused parameters.
510  */
511  UNUSED_PARAMETER(isDelete);
512  /* Usually the path zFilename should not be a relative pathname. The
513  ** exception is when opening the proxy "conch" file in builds that
514  ** include the special Apple locking styles.
515  */
516  assert(zFilename == 0 || zFilename[0] == '/');
517  pNew->h = h;
518  pNew->dirfd = dirfd;
519  pNew->zPath = zFilename;
520  if (strcmp(pVfs->zName, "unix-excl") == 0) {
521  pNew->ctrlFlags = UNIXFILE_EXCL;
522  }
523  else {
524  pNew->ctrlFlags = 0;
525  }
526  if (isReadOnly) {
527  pNew->ctrlFlags |= UNIXFILE_RDONLY;
528  }
529  pLockingStyle = &nolockIoMethods;
530  pNew->lastErrno = 0;
531  if (rc != SQLITE_OK) {
532  if (dirfd >= 0) {
533  robust_close(pNew, dirfd, __LINE__);
534  }
535  if (h >= 0) {
536  robust_close(pNew, h, __LINE__);
537  }
538  }
539  else {
540  pNew->pMethod = pLockingStyle;
541  }
542  return rc;
543 }
544 
545 /*
546 ** Open a file descriptor to the directory containing file zFilename.
547 ** If successful, *pFd is set to the opened file descriptor and
548 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
549 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
550 ** value.
551 **
552 ** If SQLITE_OK is returned, the caller is responsible for closing
553 ** the file descriptor *pFd using close().
554 */
555 static int openDirectory(const char * zFilename, int * pFd)
556 {
557  int ii;
558  int fd = -1;
559  char zDirname[MAX_PATHNAME + 1];
560  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
561  for (ii = (int)strlen(zDirname); ii > 1 && zDirname[ii] != '/'; ii--) {
562  ;
563  }
564  if (ii > 0) {
565  zDirname[ii] = '\0';
566  fd = robust_open(zDirname, O_RDONLY | O_BINARY, 0);
567  }
568  *pFd = fd;
569  return (fd >= 0 ? SQLITE_OK : unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
570 }
571 
572 /*
573 ** Return the name of a directory in which to put temporary files.
574 ** If no suitable temporary file directory can be found, return NULL.
575 */
576 static const char * unixTempFileDir(void)
577 {
578  static const char * azDirs[] = {
579  0,
580  0,
581  "/var/tmp",
582  "/usr/tmp",
583  "/tmp",
584  0 /* List terminator */
585  };
586  unsigned int i;
587  struct stat buf;
588  const char * zDir = 0;
589  azDirs[0] = sqlite3_temp_directory;
590  if (!azDirs[1]) {
591  azDirs[1] = getenv("TMPDIR");
592  }
593  for (i = 0; i < sizeof(azDirs) / sizeof(azDirs[0]); zDir = azDirs[i++]) {
594  if (zDir == 0) {
595  continue;
596  }
597  if (osStat(zDir, &buf)) {
598  continue;
599  }
600  if (!S_ISDIR(buf.st_mode)) {
601  continue;
602  }
603  if (osAccess(zDir, 07)) {
604  continue;
605  }
606  break;
607  }
608  return zDir;
609 }
610 
611 /*
612 ** Create a temporary file name in zBuf. zBuf must be allocated
613 ** by the calling process and must be big enough to hold at least
614 ** pVfs->mxPathname bytes.
615 */
616 static int unixGetTempname(int nBuf, char * zBuf)
617 {
618  static const unsigned char zChars[] =
619  "abcdefghijklmnopqrstuvwxyz"
620  "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
621  "0123456789";
622  unsigned int i, j;
623  const char * zDir;
624  /* It's odd to simulate an io-error here, but really this is just
625  ** using the io-error infrastructure to test that SQLite handles this
626  ** function failing.
627  */
628  zDir = unixTempFileDir();
629  if (zDir == 0) {
630  zDir = ".";
631  }
632  /* Check that the output buffer is large enough for the temporary file
633  ** name. If it is not, return SQLITE_ERROR.
634  */
635  if ((strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf) {
636  return SQLITE_ERROR;
637  }
638  do {
639  sqlite3_snprintf(nBuf - 17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
640  j = (int)strlen(zBuf);
641  sqlite3_randomness(15, &zBuf[j]);
642  for (i = 0; i < 15; i++, j++) {
643  zBuf[j] = (char)zChars[((unsigned char)zBuf[j]) % (sizeof(zChars) - 1) ];
644  }
645  zBuf[j] = 0;
646  }
647  while (osAccess(zBuf, 0) == 0);
648  return SQLITE_OK;
649 }
650 
651 /*
652 ** Search for an unused file descriptor that was opened on the database
653 ** file (not a journal or master-journal file) identified by pathname
654 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
655 ** argument to this function.
656 **
657 ** Such a file descriptor may exist if a database connection was closed
658 ** but the associated file descriptor could not be closed because some
659 ** other file descriptor open on the same file is holding a file-lock.
660 ** Refer to comments in the unixClose() function and the lengthy comment
661 ** describing "Posix Advisory Locking" at the start of this file for
662 ** further details. Also, ticket #4018.
663 **
664 ** If a suitable file descriptor is found, then it is returned. If no
665 ** such file descriptor is located, -1 is returned.
666 */
667 static struct UnixUnusedFd * findReusableFd(const char * zPath, int flags) {
668  struct UnixUnusedFd * pUnused = 0;
669  /* Do not search for an unused file descriptor on vxworks. Not because
670  ** vxworks would not benefit from the change (it might, we're not sure),
671  ** but because no way to test it is currently available. It is better
672  ** not to risk breaking vxworks support for the sake of such an obscure
673  ** feature. */
674  struct stat sStat; /* Results of stat() call */
675  /* A stat() call may fail for various reasons. If this happens, it is
676  ** almost certain that an open() call on the same path will also fail.
677  ** For this reason, if an error occurs in the stat() call here, it is
678  ** ignored and -1 is returned. The caller will try to open a new file
679  ** descriptor on the same path, fail, and return an error to SQLite.
680  **
681  ** Even if a subsequent open() call does succeed, the consequences of
682  ** not searching for a resusable file descriptor are not dire. */
683  if (0 == stat(zPath, &sStat)) {
684  struct unixInodeInfo * pInode;
685  pInode = inodeList;
686  while (pInode && (pInode->fileId.dev != sStat.st_dev
687  || pInode->fileId.ino != sStat.st_ino)) {
688  pInode = pInode->pNext;
689  }
690  if (pInode) {
691  struct UnixUnusedFd ** pp;
692  for (pp = &pInode->pUnused; *pp && (*pp)->flags != flags; pp = &((*pp)->pNext)) {
693  ;
694  }
695  pUnused = *pp;
696  if (pUnused) {
697  *pp = pUnused->pNext;
698  }
699  }
700  }
701  return pUnused;
702 }
703 
704 /*
705 ** This function is called by unixOpen() to determine the unix permissions
706 ** to create new files with. If no error occurs, then SQLITE_OK is returned
707 ** and a value suitable for passing as the third argument to open(2) is
708 ** written to *pMode. If an IO error occurs, an SQLite error code is
709 ** returned and the value of *pMode is not modified.
710 **
711 ** If the file being opened is a temporary file, it is always created with
712 ** the octal permissions 0600 (read/writable by owner only). If the file
713 ** is a database or master journal file, it is created with the permissions
714 ** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
715 **
716 ** Finally, if the file being opened is a WAL or regular journal file, then
717 ** this function queries the file-system for the permissions on the
718 ** corresponding database file and sets *pMode to this value. Whenever
719 ** possible, WAL and journal files are created using the same permissions
720 ** as the associated database file.
721 */
723  const char * zPath, /* Path of file (possibly) being created */
724  int flags, /* Flags passed as 4th argument to xOpen() */
725  mode_t * pMode /* OUT: Permissions to open file with */
726 )
727 {
728  int rc = SQLITE_OK; /* Return Code */
729  if (flags & (SQLITE_OPEN_WAL | SQLITE_OPEN_MAIN_JOURNAL)) {
730  char zDb[MAX_PATHNAME + 1]; /* Database file path */
731  int nDb; /* Number of valid bytes in zDb */
732  struct stat sStat; /* Output of stat() on database file */
733  /* zPath is a path to a WAL or journal file. The following block derives
734  ** the path to the associated database file from zPath. This block handles
735  ** the following naming conventions:
736  **
737  ** "<path to db>-journal"
738  ** "<path to db>-wal"
739  ** "<path to db>-journal-NNNN"
740  ** "<path to db>-wal-NNNN"
741  **
742  ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are
743  ** used by the test_multiplex.c module.
744  */
745  nDb = sqlite3Strlen30(zPath) - 1;
746  while (nDb > 0 && zPath[nDb] != 'l') {
747  nDb--;
748  }
749  nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
750  memcpy(zDb, zPath, nDb);
751  zDb[nDb] = '\0';
752  if (0 == stat(zDb, &sStat)) {
753  *pMode = sStat.st_mode & 0777;
754  }
755  else {
756  rc = SQLITE_IOERR_FSTAT;
757  }
758  }
759  else if (flags & SQLITE_OPEN_DELETEONCLOSE) {
760  *pMode = 0600;
761  }
762  else {
764  }
765  return rc;
766 }
767 
768 /*
769 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
770 ** file-control operation.
771 **
772 ** If the user has configured a chunk-size for this file, it could be
773 ** that the file needs to be extended at this point. Otherwise, the
774 ** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
775 */
776 static int fcntlSizeHint(unixFile * pFile, i64 nByte)
777 {
778  if (pFile->szChunk) {
779  i64 nSize; /* Required file size */
780  struct stat buf; /* Used to hold return values of fstat() */
781  if (osFstat(pFile->h, &buf)) {
782  return SQLITE_IOERR_FSTAT;
783  }
784  nSize = ((nByte + pFile->szChunk - 1) / pFile->szChunk) * pFile->szChunk;
785  if (nSize > (i64)buf.st_size) {
786  /* The code below is handling the return value of osFallocate()
787  ** correctly. posix_fallocate() is defined to "returns zero on success,
788  ** or an error number on failure". See the manpage for details. */
789  int err;
790  do {
791  err = osFallocate(pFile->h, buf.st_size, nSize - buf.st_size);
792  }
793  while (err == EINTR);
794  if (err) {
795  return SQLITE_IOERR_WRITE;
796  }
797  }
798  }
799  return SQLITE_OK;
800 }
801 
802 /*
803 ** The fsync() system call does not work as advertised on many
804 ** unix systems. The following procedure is an attempt to make
805 ** it work better.
806 **
807 ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
808 ** for testing when we want to run through the test suite quickly.
809 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
810 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
811 ** or power failure will likely corrupt the database file.
812 **
813 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
814 ** The idea behind dataOnly is that it should only write the file content
815 ** to disk, not the inode. We only set dataOnly if the file size is
816 ** unchanged since the file size is part of the inode. However,
817 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
818 ** file size has changed. The only real difference between fdatasync()
819 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
820 ** inode if the mtime or owner or other inode attributes have changed.
821 ** We only care about the file size, not the other file attributes, so
822 ** as far as SQLite is concerned, an fdatasync() is always adequate.
823 ** So, we always use fdatasync() if it is available, regardless of
824 ** the value of the dataOnly flag.
825 */
826 static int full_fsync(int fd, int fullSync, int dataOnly)
827 {
828  int rc;
829  UNUSED_PARAMETER(fullSync);
830  UNUSED_PARAMETER(dataOnly);
831 #if __APPLE__ && __MACH__
832  rc = fcntl(fd, F_FULLFSYNC);
833 #else
834  rc = fdatasync(fd);
835 #endif
836  return rc;
837 }
838 
839 /*
840 ** Seek to the offset passed as the second argument, then read cnt
841 ** bytes into pBuf. Return the number of bytes actually read.
842 **
843 ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
844 ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
845 ** one system to another. Since SQLite does not define USE_PREAD
846 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
847 ** See tickets #2741 and #2681.
848 **
849 ** To avoid stomping the errno value on a failed read the lastErrno value
850 ** is set before returning.
851 */
852 static int seekAndRead(unixFile * id, sqlite3_int64 offset, void * pBuf, int cnt)
853 {
854  int got;
855  i64 newOffset;
856  newOffset = lseek(id->h, offset, SEEK_SET);
857  if (newOffset != offset) {
858  if (newOffset == -1) {
859  ((unixFile *)id)->lastErrno = errno;
860  }
861  else {
862  ((unixFile *)id)->lastErrno = 0;
863  }
864  return -1;
865  }
866  do {
867  got = osRead(id->h, pBuf, cnt);
868  }
869  while (got < 0 && errno == EINTR);
870  if (got < 0) {
871  ((unixFile *)id)->lastErrno = errno;
872  }
873  return got;
874 }
875 
876 /*
877 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
878 ** Return the number of bytes actually read. Update the offset.
879 **
880 ** To avoid stomping the errno value on a failed write the lastErrno value
881 ** is set before returning.
882 */
883 static int seekAndWrite(unixFile * id, i64 offset, const void * pBuf, int cnt)
884 {
885  int got;
886  i64 newOffset;
887  newOffset = lseek(id->h, offset, SEEK_SET);
888  if (newOffset != offset) {
889  if (newOffset == -1) {
890  ((unixFile *)id)->lastErrno = errno;
891  }
892  else {
893  ((unixFile *)id)->lastErrno = 0;
894  }
895  return -1;
896  }
897  do {
898  got = osWrite(id->h, pBuf, cnt);
899  }
900  while (got < 0 && errno == EINTR);
901  if (got < 0) {
902  ((unixFile *)id)->lastErrno = errno;
903  }
904  return got;
905 }
906 
907 /*--------------------------------------------------------------------------*/
908 /* IoMethods calls */
909 
910 static int nolockClose(sqlite3_file * id)
911 {
912  fprintf(stderr, "trace: begin nolockClose ...\n");
913  return closeUnixFile(id);
914 }
915 
916 /*
917 ** Read data from a file into a buffer. Return SQLITE_OK if all
918 ** bytes were read successfully and SQLITE_IOERR if anything goes
919 ** wrong.
920 */
921 static int unixRead(sqlite3_file * id, void * pBuf, int amt, sqlite3_int64 offset)
922 {
923  unixFile * pFile = (unixFile *)id;
924  int got;
925  fprintf(stderr, "trace: begin unixRead ...\n");
926  assert(id);
927  /* If this is a database file (not a journal, master-journal or temp
928  ** file), the bytes in the locking range should never be read or written. */
929 #if 0
930  assert(pFile->pUnused == 0
931  || offset >= PENDING_BYTE + 512
932  || offset + amt <= PENDING_BYTE
933  );
934 #endif
935  got = seekAndRead(pFile, offset, pBuf, amt);
936  if (got == amt) {
937  return SQLITE_OK;
938  }
939  else if (got < 0) {
940  /* lastErrno set by seekAndRead */
941  return SQLITE_IOERR_READ;
942  }
943  else {
944  pFile->lastErrno = 0; /* not a system error */
945  /* Unread parts of the buffer must be zero-filled */
946  memset(&((char *)pBuf)[got], 0, amt - got);
947  return SQLITE_IOERR_SHORT_READ;
948  }
949 }
950 
951 /*
952 ** Write data from a buffer into a file. Return SQLITE_OK on success
953 ** or some other error code on failure.
954 */
955 static int unixWrite(sqlite3_file * id, const void * pBuf, int amt, sqlite3_int64 offset)
956 {
957  unixFile * pFile = (unixFile *)id;
958  int wrote = 0;
959  fprintf(stderr, "trace: begin unixWrite ...\n");
960  assert(id);
961  assert(amt > 0);
962  /* If this is a database file (not a journal, master-journal or temp
963  ** file), the bytes in the locking range should never be read or written. */
964 #if 0
965  assert(pFile->pUnused == 0
966  || offset >= PENDING_BYTE + 512
967  || offset + amt <= PENDING_BYTE
968  );
969 #endif
970  /* If we are doing a normal write to a database file (as opposed to
971  ** doing a hot-journal rollback or a write to some file other than a
972  ** normal database file) then record the fact that the database
973  ** has changed. If the transaction counter is modified, record that
974  ** fact too.
975  */
976  if (pFile->inNormalWrite) {
977  pFile->dbUpdate = 1; /* The database has been modified */
978  if (offset <= 24 && offset + amt >= 27) {
979  int rc;
980  char oldCntr[4];
981  rc = seekAndRead(pFile, 24, oldCntr, 4);
982  if (rc != 4 || memcmp(oldCntr, &((char *)pBuf)[24 - offset], 4) != 0) {
983  pFile->transCntrChng = 1; /* The transaction counter has changed */
984  }
985  }
986  }
987  while (amt > 0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt)) > 0) {
988  amt -= wrote;
989  offset += wrote;
990  pBuf = &((char *)pBuf)[wrote];
991  }
992  if (amt > 0) {
993  if (wrote < 0) {
994  /* lastErrno set by seekAndWrite */
995  return SQLITE_IOERR_WRITE;
996  }
997  else {
998  pFile->lastErrno = 0; /* not a system error */
999  return SQLITE_FULL;
1000  }
1001  }
1002  return SQLITE_OK;
1003 }
1004 
1005 /*
1006 ** Truncate an open file to a specified size
1007 */
1008 static int unixTruncate(sqlite3_file * id, i64 nByte)
1009 {
1010  unixFile * pFile = (unixFile *)id;
1011  int rc;
1012  fprintf(stderr, "trace: begin unixTruncate ...\n");
1013  assert(pFile);
1014  /* If the user has configured a chunk-size for this file, truncate the
1015  ** file so that it consists of an integer number of chunks (i.e. the
1016  ** actual file size after the operation may be larger than the requested
1017  ** size).
1018  */
1019  if (pFile->szChunk) {
1020  nByte = ((nByte + pFile->szChunk - 1) / pFile->szChunk) * pFile->szChunk;
1021  }
1022  rc = robust_ftruncate(pFile->h, (off_t)nByte);
1023  if (rc) {
1024  pFile->lastErrno = errno;
1025  return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
1026  }
1027  else {
1028  /* If we are doing a normal write to a database file (as opposed to
1029  ** doing a hot-journal rollback or a write to some file other than a
1030  ** normal database file) and we truncate the file to zero length,
1031  ** that effectively updates the change counter. This might happen
1032  ** when restoring a database using the backup API from a zero-length
1033  ** source.
1034  */
1035  if (pFile->inNormalWrite && nByte == 0) {
1036  pFile->transCntrChng = 1;
1037  }
1038  return SQLITE_OK;
1039  }
1040 }
1041 
1042 /*
1043 ** Make sure all writes to a particular file are committed to disk.
1044 **
1045 ** If dataOnly==0 then both the file itself and its metadata (file
1046 ** size, access time, etc) are synced. If dataOnly!=0 then only the
1047 ** file data is synced.
1048 **
1049 ** Under Unix, also make sure that the directory entry for the file
1050 ** has been created by fsync-ing the directory that contains the file.
1051 ** If we do not do this and we encounter a power failure, the directory
1052 ** entry for the journal might not exist after we reboot. The next
1053 ** SQLite to access the file will not know that the journal exists (because
1054 ** the directory entry for the journal was never created) and the transaction
1055 ** will not roll back - possibly leading to database corruption.
1056 */
1057 static int unixSync(sqlite3_file * id, int flags)
1058 {
1059  int rc;
1060  unixFile * pFile = (unixFile *)id;
1061  int isDataOnly = (flags & SQLITE_SYNC_DATAONLY);
1062  int isFullsync = (flags & 0x0F) == SQLITE_SYNC_FULL;
1063  fprintf(stderr, "trace: begin unixSync ...\n");
1064  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
1065  assert((flags & 0x0F) == SQLITE_SYNC_NORMAL
1066  || (flags & 0x0F) == SQLITE_SYNC_FULL
1067  );
1068  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
1069  ** line is to test that doing so does not cause any problems.
1070  */
1071  assert(pFile);
1072  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
1073  if (rc) {
1074  pFile->lastErrno = errno;
1075  return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
1076  }
1077  if (pFile->dirfd >= 0) {
1078  /* The directory sync is only attempted if full_fsync is
1079  ** turned off or unavailable. If a full_fsync occurred above,
1080  ** then the directory sync is superfluous.
1081  */
1082  if (full_fsync(pFile->dirfd, 0, 0)) {
1083  /*
1084  ** We have received multiple reports of fsync() returning
1085  ** errors when applied to directories on certain file systems.
1086  ** A failed directory sync is not a big deal. So it seems
1087  ** better to ignore the error. Ticket #1657
1088  */
1089  /* pFile->lastErrno = errno; */
1090  /* return SQLITE_IOERR; */
1091  }
1092  /* Only need to sync once, so close the directory when we are done */
1093  robust_close(pFile, pFile->dirfd, __LINE__);
1094  pFile->dirfd = -1;
1095  }
1096  return rc;
1097 }
1098 
1099 /*
1100 ** Determine the current size of a file in bytes
1101 */
1102 static int unixFileSize(sqlite3_file * id, i64 * pSize)
1103 {
1104  int rc;
1105  struct stat buf;
1106  assert(id);
1107  rc = osFstat(((unixFile *)id)->h, &buf);
1108  if (rc != 0) {
1109  ((unixFile *)id)->lastErrno = errno;
1110  return SQLITE_IOERR_FSTAT;
1111  }
1112  *pSize = buf.st_size;
1113  /* When opening a zero-size database, the findInodeInfo() procedure
1114  ** writes a single byte into that file in order to work around a bug
1115  ** in the OS-X msdos filesystem. In order to avoid problems with upper
1116  ** layers, we need to report this file size as zero even though it is
1117  ** really 1. Ticket #3260.
1118  */
1119  if (*pSize == 1) {
1120  *pSize = 0;
1121  }
1122  return SQLITE_OK;
1123 }
1124 
1125 static int nolockLock(sqlite3_file * NotUsed, int NotUsed2)
1126 {
1127  UNUSED_PARAMETER2(NotUsed, NotUsed2);
1128  return SQLITE_OK;
1129 }
1130 
1131 static int nolockUnlock(sqlite3_file * NotUsed, int NotUsed2)
1132 {
1133  UNUSED_PARAMETER2(NotUsed, NotUsed2);
1134  return SQLITE_OK;
1135 }
1136 
1137 static int nolockCheckReservedLock(sqlite3_file * NotUsed, int * pResOut)
1138 {
1139  UNUSED_PARAMETER(NotUsed);
1140  *pResOut = 0;
1141  return SQLITE_OK;
1142 }
1143 
1144 /*
1145 ** Information and control of an open file handle.
1146 */
1147 static int unixFileControl(sqlite3_file * id, int op, void * pArg)
1148 {
1149  switch (op) {
1150  case SQLITE_FCNTL_LOCKSTATE: {
1151  *(int *)pArg = ((unixFile *)id)->eFileLock;
1152  return SQLITE_OK;
1153  }
1154  case SQLITE_LAST_ERRNO: {
1155  *(int *)pArg = ((unixFile *)id)->lastErrno;
1156  return SQLITE_OK;
1157  }
1158  case SQLITE_FCNTL_CHUNK_SIZE: {
1159  ((unixFile *)id)->szChunk = *(int *)pArg;
1160  return SQLITE_OK;
1161  }
1162  case SQLITE_FCNTL_SIZE_HINT: {
1163  return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
1164  }
1165  /* The pager calls this method to signal that it has done
1166  ** a rollback and that the database is therefore unchanged and
1167  ** it hence it is OK for the transaction change counter to be
1168  ** unchanged.
1169  */
1171  ((unixFile *)id)->dbUpdate = 0;
1172  return SQLITE_OK;
1173  }
1175  return SQLITE_OK; /* A no-op */
1176  }
1177  }
1178  return SQLITE_NOTFOUND;
1179 }
1180 
1181 /*
1182 ** Return the sector size in bytes of the underlying block device for
1183 ** the specified file. This is almost always 512 bytes, but may be
1184 ** larger for some devices.
1185 **
1186 ** SQLite code assumes this function cannot fail. It also assumes that
1187 ** if two files are created in the same file-system directory (i.e.
1188 ** a database and its journal file) that the sector size will be the
1189 ** same for both.
1190 */
1191 static int unixSectorSize(sqlite3_file * NotUsed)
1192 {
1193  UNUSED_PARAMETER(NotUsed);
1195 }
1196 
1197 /*
1198 ** Return the device characteristics for the file. This is always 0 for unix.
1199 */
1200 static int unixDeviceCharacteristics(sqlite3_file * NotUsed)
1201 {
1202  UNUSED_PARAMETER(NotUsed);
1203  return 0;
1204 }
1205 
1206 /*--------------------------------------------------------------------------*/
1207 /* VFS calls */
1208 
1209 /*
1210 ** Open the file zPath.
1211 **
1212 ** Previously, the SQLite OS layer used three functions in place of this
1213 ** one:
1214 **
1215 ** sqlite3OsOpenReadWrite();
1216 ** sqlite3OsOpenReadOnly();
1217 ** sqlite3OsOpenExclusive();
1218 **
1219 ** These calls correspond to the following combinations of flags:
1220 **
1221 ** ReadWrite() -> (READWRITE | CREATE)
1222 ** ReadOnly() -> (READONLY)
1223 ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
1224 **
1225 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
1226 ** true, the file was configured to be automatically deleted when the
1227 ** file handle closed. To achieve the same effect using this new
1228 ** interface, add the DELETEONCLOSE flag to those specified above for
1229 ** OpenExclusive().
1230 */
1231 static int unixOpen(
1232  sqlite3_vfs * pVfs, /* The VFS for which this is the xOpen method */
1233  const char * zPath, /* Pathname of file to be opened */
1234  sqlite3_file * pFile, /* The file descriptor to be filled in */
1235  int flags, /* Input flags to control the opening */
1236  int * pOutFlags /* Output flags returned to SQLite core */
1237 )
1238 {
1239  unixFile * p = (unixFile *)pFile;
1240  int fd = -1; /* File descriptor returned by open() */
1241  int dirfd = -1; /* Directory file descriptor */
1242  int openFlags = 0; /* Flags to pass to open() */
1243  int eType = flags & 0xFFFFFF00; /* Type of file to open */
1244  int noLock; /* True to omit locking primitives */
1245  int rc = SQLITE_OK; /* Function Return Code */
1246  int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
1247  int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
1248  int isCreate = (flags & SQLITE_OPEN_CREATE);
1249  int isReadonly = (flags & SQLITE_OPEN_READONLY);
1250  int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
1251  /* If creating a master or main-file journal, this function will open
1252  ** a file-descriptor on the directory too. The first time unixSync()
1253  ** is called the directory file descriptor will be fsync()ed and close()d.
1254  */
1255  int isOpenDirectory = (isCreate && (
1256  eType == SQLITE_OPEN_MASTER_JOURNAL
1257  || eType == SQLITE_OPEN_MAIN_JOURNAL
1258  || eType == SQLITE_OPEN_WAL
1259  ));
1260  /* If argument zPath is a NULL pointer, this function is required to open
1261  ** a temporary file. Use this buffer to store the file name in.
1262  */
1263  char zTmpname[MAX_PATHNAME + 1];
1264  const char * zName = zPath;
1265  fprintf(stderr, "trace: begin unixOpen ...\n");
1266  /* Check the following statements are true:
1267  **
1268  ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
1269  ** (b) if CREATE is set, then READWRITE must also be set, and
1270  ** (c) if EXCLUSIVE is set, then CREATE must also be set.
1271  ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
1272  */
1273  assert((isReadonly == 0 || isReadWrite == 0) && (isReadWrite || isReadonly));
1274  assert(isCreate == 0 || isReadWrite);
1275  assert(isExclusive == 0 || isCreate);
1276  assert(isDelete == 0 || isCreate);
1277  /* The main DB, main journal, WAL file and master journal are never
1278  ** automatically deleted. Nor are they ever temporary files. */
1279  assert((!isDelete && zName) || eType != SQLITE_OPEN_MAIN_DB);
1280  assert((!isDelete && zName) || eType != SQLITE_OPEN_MAIN_JOURNAL);
1281  assert((!isDelete && zName) || eType != SQLITE_OPEN_MASTER_JOURNAL);
1282  assert((!isDelete && zName) || eType != SQLITE_OPEN_WAL);
1283  /* Assert that the upper layer has set one of the "file-type" flags. */
1284  assert(eType == SQLITE_OPEN_MAIN_DB || eType == SQLITE_OPEN_TEMP_DB
1285  || eType == SQLITE_OPEN_MAIN_JOURNAL || eType == SQLITE_OPEN_TEMP_JOURNAL
1286  || eType == SQLITE_OPEN_SUBJOURNAL || eType == SQLITE_OPEN_MASTER_JOURNAL
1287  || eType == SQLITE_OPEN_TRANSIENT_DB || eType == SQLITE_OPEN_WAL
1288  );
1289  memset(p, 0, sizeof(unixFile));
1290  if (eType == SQLITE_OPEN_MAIN_DB) {
1291  struct UnixUnusedFd * pUnused;
1292  pUnused = findReusableFd(zName, flags);
1293  if (pUnused) {
1294  fd = pUnused->fd;
1295  }
1296  else {
1297  pUnused = sqlite3_malloc(sizeof(*pUnused));
1298  if (!pUnused) {
1299  return SQLITE_NOMEM;
1300  }
1301  }
1302  p->pUnused = pUnused;
1303  }
1304  else if (!zName) {
1305  /* If zName is NULL, the upper layer is requesting a temp file. */
1306  assert(isDelete && !isOpenDirectory);
1307  rc = unixGetTempname(MAX_PATHNAME + 1, zTmpname);
1308  if (rc != SQLITE_OK) {
1309  return rc;
1310  }
1311  zName = zTmpname;
1312  }
1313  /* Determine the value of the flags parameter passed to POSIX function
1314  ** open(). These must be calculated even if open() is not called, as
1315  ** they may be stored as part of the file handle and used by the
1316  ** 'conch file' locking functions later on. */
1317  if (isReadonly) {
1318  openFlags |= O_RDONLY;
1319  }
1320  if (isReadWrite) {
1321  openFlags |= O_RDWR;
1322  }
1323  if (isCreate) {
1324  openFlags |= O_CREAT;
1325  }
1326  if (isExclusive) {
1327  openFlags |= (O_EXCL | O_NOFOLLOW);
1328  }
1329  openFlags |= (O_LARGEFILE | O_BINARY);
1330  if (fd < 0) {
1331  mode_t openMode; /* Permissions to create file with */
1332  rc = findCreateFileMode(zName, flags, &openMode);
1333  if (rc != SQLITE_OK) {
1334  assert(!p->pUnused);
1335  assert(eType == SQLITE_OPEN_WAL || eType == SQLITE_OPEN_MAIN_JOURNAL);
1336  return rc;
1337  }
1338  fd = robust_open(zName, openFlags, openMode);
1339  if (fd < 0 && errno != EISDIR && isReadWrite && !isExclusive) {
1340  /* Failed to open the file for read/write access. Try read-only. */
1341  flags &= ~(SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);
1342  openFlags &= ~(O_RDWR | O_CREAT);
1343  flags |= SQLITE_OPEN_READONLY;
1344  openFlags |= O_RDONLY;
1345  isReadonly = 1;
1346  fd = robust_open(zName, openFlags, openMode);
1347  }
1348  if (fd < 0) {
1349  rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
1350  goto open_finished;
1351  }
1352  }
1353  assert(fd >= 0);
1354  if (pOutFlags) {
1355  *pOutFlags = flags;
1356  }
1357  if (p->pUnused) {
1358  p->pUnused->fd = fd;
1359  p->pUnused->flags = flags;
1360  }
1361  if (isDelete) {
1362  unlink(zName);
1363  }
1364  if (isOpenDirectory) {
1365  rc = openDirectory(zPath, &dirfd);
1366  if (rc != SQLITE_OK) {
1367  /* It is safe to close fd at this point, because it is guaranteed not
1368  ** to be open on a database file. If it were open on a database file,
1369  ** it would not be safe to close as this would release any locks held
1370  ** on the file by this process. */
1371  assert(eType != SQLITE_OPEN_MAIN_DB);
1372  robust_close(p, fd, __LINE__);
1373  goto open_finished;
1374  }
1375  }
1376  noLock = eType != SQLITE_OPEN_MAIN_DB;
1377  rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
1378  isDelete, isReadonly);
1379 open_finished:
1380  if (rc != SQLITE_OK) {
1381  sqlite3_free(p->pUnused);
1382  }
1383  return rc;
1384 }
1385 
1386 /*
1387 ** Delete the file at zPath. If the dirSync argument is true, fsync()
1388 ** the directory after deleting the file.
1389 */
1390 static int unixDelete(
1391  sqlite3_vfs * NotUsed, /* VFS containing this as the xDelete method */
1392  const char * zPath, /* Name of file to be deleted */
1393  int dirSync /* If true, fsync() directory after deleting file */
1394 )
1395 {
1396  int rc = SQLITE_OK;
1397  UNUSED_PARAMETER(NotUsed);
1398  if (unlink(zPath) == (-1) && errno != ENOENT) {
1399  return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
1400  }
1401  if (dirSync) {
1402  int fd;
1403  rc = openDirectory(zPath, &fd);
1404  if (rc == SQLITE_OK) {
1405  if (fsync(fd)) {
1406  rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
1407  }
1408  robust_close(0, fd, __LINE__);
1409  }
1410  }
1411  return rc;
1412 }
1413 
1414 /*
1415 ** Test the existance of or access permissions of file zPath. The
1416 ** test performed depends on the value of flags:
1417 **
1418 ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
1419 ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
1420 ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
1421 **
1422 ** Otherwise return 0.
1423 */
1424 static int unixAccess(
1425  sqlite3_vfs * NotUsed, /* The VFS containing this xAccess method */
1426  const char * zPath, /* Path of the file to examine */
1427  int flags, /* What do we want to learn about the zPath file? */
1428  int * pResOut /* Write result boolean here */
1429 )
1430 {
1431  int amode = 0;
1432  UNUSED_PARAMETER(NotUsed);
1433  switch (flags) {
1434  case SQLITE_ACCESS_EXISTS:
1435  amode = F_OK;
1436  break;
1437  case SQLITE_ACCESS_READWRITE:
1438  amode = W_OK | R_OK;
1439  break;
1440  case SQLITE_ACCESS_READ:
1441  amode = R_OK;
1442  break;
1443  default:
1444  assert(!"Invalid flags argument");
1445  }
1446  *pResOut = (osAccess(zPath, amode) == 0);
1447  if (flags == SQLITE_ACCESS_EXISTS && *pResOut) {
1448  struct stat buf;
1449  if (0 == stat(zPath, &buf) && buf.st_size == 0) {
1450  *pResOut = 0;
1451  }
1452  }
1453  return SQLITE_OK;
1454 }
1455 
1456 /*
1457 ** Turn a relative pathname into a full pathname. The relative path
1458 ** is stored as a nul-terminated string in the buffer pointed to by
1459 ** zPath.
1460 **
1461 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
1462 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
1463 ** this buffer before returning.
1464 */
1465 static int unixFullPathname(
1466  sqlite3_vfs * pVfs, /* Pointer to vfs object */
1467  const char * zPath, /* Possibly relative input path */
1468  int nOut, /* Size of output buffer in bytes */
1469  char * zOut /* Output buffer */
1470 )
1471 {
1472  /* It's odd to simulate an io-error here, but really this is just
1473  ** using the io-error infrastructure to test that SQLite handles this
1474  ** function failing. This function could fail if, for example, the
1475  ** current working directory has been unlinked.
1476  */
1477  assert(pVfs->mxPathname == MAX_PATHNAME);
1478  UNUSED_PARAMETER(pVfs);
1479  zOut[nOut - 1] = '\0';
1480  if (zPath[0] == '/') {
1481  sqlite3_snprintf(nOut, zOut, "%s", zPath);
1482  }
1483  else {
1484  int nCwd;
1485  if (osGetcwd(zOut, nOut - 1) == 0) {
1486  return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
1487  }
1488  nCwd = (int)strlen(zOut);
1489  sqlite3_snprintf(nOut - nCwd, &zOut[nCwd], "/%s", zPath);
1490  }
1491  return SQLITE_OK;
1492 }
1493 
1494 /*
1495 ** Interfaces for opening a shared library, finding entry points
1496 ** within the shared library, and closing the shared library.
1497 */
1498 static void * unixDlOpen(sqlite3_vfs * NotUsed, const char * zFilename)
1499 {
1500  UNUSED_PARAMETER(NotUsed);
1501  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
1502 }
1503 
1504 /*
1505 ** SQLite calls this function immediately after a call to unixDlSym() or
1506 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
1507 ** message is available, it is written to zBufOut. If no error message
1508 ** is available, zBufOut is left unmodified and SQLite uses a default
1509 ** error message.
1510 */
1511 static void unixDlError(sqlite3_vfs * NotUsed, int nBuf, char * zBufOut)
1512 {
1513  const char * zErr;
1514  UNUSED_PARAMETER(NotUsed);
1515  zErr = dlerror();
1516  if (zErr) {
1517  sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
1518  }
1519 }
1520 
1521 static void (*unixDlSym(sqlite3_vfs * NotUsed, void * p, const char * zSym))(void)
1522 {
1523  /*
1524  ** GCC with -pedantic-errors says that C90 does not allow a void* to be
1525  ** cast into a pointer to a function. And yet the library dlsym() routine
1526  ** returns a void* which is really a pointer to a function. So how do we
1527  ** use dlsym() with -pedantic-errors?
1528  **
1529  ** Variable x below is defined to be a pointer to a function taking
1530  ** parameters void* and const char* and returning a pointer to a function.
1531  ** We initialize x by assigning it a pointer to the dlsym() function.
1532  ** (That assignment requires a cast.) Then we call the function that
1533  ** x points to.
1534  **
1535  ** This work-around is unlikely to work correctly on any system where
1536  ** you really cannot cast a function pointer into void*. But then, on the
1537  ** other hand, dlsym() will not work on such a system either, so we have
1538  ** not really lost anything.
1539  */
1540  void (*(*x)(void *, const char *))(void);
1541  UNUSED_PARAMETER(NotUsed);
1542  x = (void(*( *)(void *, const char *))(void))dlsym;
1543  return (*x)(p, zSym);
1544 }
1545 
1546 static void unixDlClose(sqlite3_vfs * NotUsed, void * pHandle)
1547 {
1548  UNUSED_PARAMETER(NotUsed);
1549  dlclose(pHandle);
1550 }
1551 
1552 /*
1553 ** Write nBuf bytes of random data to the supplied buffer zBuf.
1554 */
1555 static int unixRandomness(sqlite3_vfs * NotUsed, int nBuf, char * zBuf)
1556 {
1557  UNUSED_PARAMETER(NotUsed);
1558  assert((size_t)nBuf >= (sizeof(time_t) + sizeof(int)));
1559  /* We have to initialize zBuf to prevent valgrind from reporting
1560  ** errors. The reports issued by valgrind are incorrect - we would
1561  ** prefer that the randomness be increased by making use of the
1562  ** uninitialized space in zBuf - but valgrind errors tend to worry
1563  ** some users. Rather than argue, it seems easier just to initialize
1564  ** the whole array and silence valgrind, even if that means less randomness
1565  ** in the random seed.
1566  **
1567  ** When testing, initializing zBuf[] to zero is all we do. That means
1568  ** that we always use the same random number sequence. This makes the
1569  ** tests repeatable.
1570  */
1571  memset(zBuf, 0, nBuf);
1572  {
1573  int pid, fd;
1574  fd = robust_open("/dev/urandom", O_RDONLY, 0);
1575  if (fd < 0) {
1576  time_t t;
1577  time(&t);
1578  memcpy(zBuf, &t, sizeof(t));
1579  pid = getpid();
1580  memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
1581  assert(sizeof(t) + sizeof(pid) <= (size_t)nBuf);
1582  nBuf = sizeof(t) + sizeof(pid);
1583  }
1584  else {
1585  do {
1586  nBuf = osRead(fd, zBuf, nBuf);
1587  }
1588  while (nBuf < 0 && errno == EINTR);
1589  robust_close(0, fd, __LINE__);
1590  }
1591  }
1592  return nBuf;
1593 }
1594 
1595 
1596 /*
1597 ** Sleep for a little while. Return the amount of time slept.
1598 ** The argument is the number of microseconds we want to sleep.
1599 ** The return value is the number of microseconds of sleep actually
1600 ** requested from the underlying operating system, a number which
1601 ** might be greater than or equal to the argument, but not less
1602 ** than the argument.
1603 */
1604 static int unixSleep(sqlite3_vfs * NotUsed, int microseconds)
1605 {
1606  usleep(microseconds);
1607  UNUSED_PARAMETER(NotUsed);
1608  return microseconds;
1609 }
1610 
1611 /*
1612 ** Find the current time (in Universal Coordinated Time). Write the
1613 ** current time and date as a Julian Day number into *prNow and
1614 ** return 0. Return 1 if the time and date cannot be found.
1615 */
1616 static int unixCurrentTime(sqlite3_vfs * NotUsed, double * prNow)
1617 {
1618  sqlite3_int64 i;
1619  UNUSED_PARAMETER(NotUsed);
1620  unixCurrentTimeInt64(0, &i);
1621  *prNow = i / 86400000.0;
1622  return 0;
1623 }
1624 
1625 /*
1626 ** We added the xGetLastError() method with the intention of providing
1627 ** better low-level error messages when operating-system problems come up
1628 ** during SQLite operation. But so far, none of that has been implemented
1629 ** in the core. So this routine is never called. For now, it is merely
1630 ** a place-holder.
1631 */
1632 static int unixGetLastError(sqlite3_vfs * NotUsed, int NotUsed2, char * NotUsed3)
1633 {
1634  UNUSED_PARAMETER(NotUsed);
1635  UNUSED_PARAMETER(NotUsed2);
1636  UNUSED_PARAMETER(NotUsed3);
1637  return 0;
1638 }
1639 
1640 /*
1641 ** Find the current time (in Universal Coordinated Time). Write into *piNow
1642 ** the current time and date as a Julian Day number times 86_400_000. In
1643 ** other words, write into *piNow the number of milliseconds since the Julian
1644 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
1645 ** proleptic Gregorian calendar.
1646 **
1647 ** On success, return 0. Return 1 if the time and date cannot be found.
1648 */
1649 static int unixCurrentTimeInt64(sqlite3_vfs * NotUsed, sqlite3_int64 * piNow)
1650 {
1651  static const sqlite3_int64 unixEpoch = 24405875 * (sqlite3_int64)8640000;
1652  struct timeval sNow;
1653  gettimeofday(&sNow, 0);
1654  *piNow = unixEpoch + 1000 * (sqlite3_int64)sNow.tv_sec + sNow.tv_usec / 1000;
1655  UNUSED_PARAMETER(NotUsed);
1656  return 0;
1657 }
1658 
1659 /*
1660 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
1661 ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
1662 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
1663 ** system call named zName.
1664 */
1666  sqlite3_vfs * pNotUsed, /* The VFS pointer. Not used */
1667  const char * zName, /* Name of system call to override */
1668  sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
1669 )
1670 {
1671  unsigned int i;
1672  int rc = SQLITE_NOTFOUND;
1673  UNUSED_PARAMETER(pNotUsed);
1674  if (zName == 0) {
1675  /* If no zName is given, restore all system calls to their default
1676  ** settings and return NULL
1677  */
1678  rc = SQLITE_OK;
1679  for (i = 0; i < sizeof(aSyscall) / sizeof(aSyscall[0]); i++) {
1680  if (aSyscall[i].pDefault) {
1682  }
1683  }
1684  }
1685  else {
1686  /* If zName is specified, operate on only the one system call
1687  ** specified.
1688  */
1689  for (i = 0; i < sizeof(aSyscall) / sizeof(aSyscall[0]); i++) {
1690  if (strcmp(zName, aSyscall[i].zName) == 0) {
1691  if (aSyscall[i].pDefault == 0) {
1693  }
1694  rc = SQLITE_OK;
1695  if (pNewFunc == 0) {
1696  pNewFunc = aSyscall[i].pDefault;
1697  }
1698  aSyscall[i].pCurrent = pNewFunc;
1699  break;
1700  }
1701  }
1702  }
1703  return rc;
1704 }
1705 
1706 /*
1707 ** Return the value of a system call. Return NULL if zName is not a
1708 ** recognized system call name. NULL is also returned if the system call
1709 ** is currently undefined.
1710 */
1711 static sqlite3_syscall_ptr unixGetSystemCall(sqlite3_vfs * pNotUsed, const char * zName)
1712 {
1713  unsigned int i;
1714  UNUSED_PARAMETER(pNotUsed);
1715  for (i = 0; i < sizeof(aSyscall) / sizeof(aSyscall[0]); i++) {
1716  if (strcmp(zName, aSyscall[i].zName) == 0) {
1717  return aSyscall[i].pCurrent;
1718  }
1719  }
1720  return 0;
1721 }
1722 
1723 /*
1724 ** Return the name of the first system call after zName. If zName==NULL
1725 ** then return the name of the first system call. Return NULL if zName
1726 ** is the last system call or if zName is not the name of a valid
1727 ** system call.
1728 */
1729 static const char * unixNextSystemCall(sqlite3_vfs * p, const char * zName)
1730 {
1731  int i = -1;
1732  UNUSED_PARAMETER(p);
1733  if (zName) {
1734  for (i = 0; i < ArraySize(aSyscall) - 1; i++) {
1735  if (strcmp(zName, aSyscall[i].zName) == 0) {
1736  break;
1737  }
1738  }
1739  }
1740  for (i++; i < ArraySize(aSyscall); i++) {
1741  if (aSyscall[i].pCurrent != 0) {
1742  return aSyscall[i].zName;
1743  }
1744  }
1745  return 0;
1746 }
1747 
1748 int myvfs_init(void)
1749 {
1750  /*
1751  ** The following macro defines an initializer for an sqlite3_vfs object.
1752  ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
1753  ** to the "finder" function. (pAppData is a pointer to a pointer because
1754  ** silly C90 rules prohibit a void* from being cast to a function pointer
1755  ** and so we have to go through the intermediate pointer to avoid problems
1756  ** when compiling with -pedantic-errors on GCC.)
1757  **
1758  ** The FINDER parameter to this macro is the name of the pointer to the
1759  ** finder-function. The finder-function returns a pointer to the
1760  ** sqlite_io_methods object that implements the desired locking
1761  ** behaviors. See the division above that contains the IOMETHODS
1762  ** macro for addition information on finder-functions.
1763  **
1764  ** Most finders simply return a pointer to a fixed sqlite3_io_methods
1765  ** object. But the "autolockIoFinder" available on MacOSX does a little
1766  ** more than that; it looks at the filesystem type that hosts the
1767  ** database file and tries to choose an locking method appropriate for
1768  ** that filesystem time.
1769  */
1770 #define UNIXVFS(VFSNAME, FINDER) { \
1771  1, /* iVersion */ \
1772  sizeof(unixFile), /* szOsFile */ \
1773  MAX_PATHNAME, /* mxPathname */ \
1774  0, /* pNext */ \
1775  VFSNAME, /* zName */ \
1776  (void*)&FINDER, /* pAppData */ \
1777  unixOpen, /* xOpen */ \
1778  unixDelete, /* xDelete */ \
1779  unixAccess, /* xAccess */ \
1780  unixFullPathname, /* xFullPathname */ \
1781  unixDlOpen, /* xDlOpen */ \
1782  unixDlError, /* xDlError */ \
1783  unixDlSym, /* xDlSym */ \
1784  unixDlClose, /* xDlClose */ \
1785  unixRandomness, /* xRandomness */ \
1786  unixSleep, /* xSleep */ \
1787  unixCurrentTime, /* xCurrentTime */ \
1788  unixGetLastError, /* xGetLastError */ \
1789  /* unixCurrentTimeInt64, v2, xCurrentTimeInt64 */ \
1790  /* unixSetSystemCall, v3, xSetSystemCall */ \
1791  /* unixGetSystemCall, v3, xGetSystemCall */ \
1792  /* unixNextSystemCall, v3, xNextSystemCall */ \
1793  }
1794  /*
1795  ** All default VFSes for unix are contained in the following array.
1796  **
1797  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
1798  ** by the SQLite core when the VFS is registered. So the following
1799  ** array cannot be const.
1800  */
1801  static sqlite3_vfs aVfs[] = {
1802  UNIXVFS("myvfs", nolockIoFinder),
1803  };
1804  unsigned int i; /* Loop counter */
1805  /* Double-check that the aSyscall[] array has been constructed
1806  ** correctly. See ticket [bb3a86e890c8e96ab] */
1807  assert(ArraySize(aSyscall) == 16);
1808  /* Register all VFSes defined in the aVfs[] array */
1809  for (i = 0; i < (sizeof(aVfs) / sizeof(sqlite3_vfs)); i++) {
1810  sqlite3_vfs_register(&aVfs[i], i == 0);
1811  }
1812  return SQLITE_OK;
1813 }
1814 
int nShared
Definition: myvfs.c:89
static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow)
Definition: myvfs.c:1649
static const double m
Definition: Units.h:79
unixShmNode * pShmNode
Definition: myvfs.c:93
#define osClose
#define osPwrite
sqlite_int64 i64
Definition: tkeyvfs.cc:34
static int unixFileSize(sqlite3_file *id, i64 *pSize)
Definition: myvfs.c:1102
unsigned char transCntrChng
Definition: tkeyvfs.cc:116
int sqlite3_os_init(void)
static int unixOpen(sqlite3_vfs *pVfs, const char *zPath, sqlite3_file *pFile, int flags, int *pOutFlags)
Definition: myvfs.c:1231
static const sqlite3_io_methods * nolockIoFinderImpl(const char *z, unixFile *p)
Definition: myvfs.c:362
static const sqlite3_io_methods *(*const nolockIoFinder)(const char *, unixFile *p)
Definition: myvfs.c:369
sqlite3_syscall_ptr pDefault
Definition: tkeyvfs.cc:249
static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3)
Definition: myvfs.c:1632
static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf)
Definition: myvfs.c:1555
#define osFcntl
#define UNIXFILE_EXCL
Definition: myvfs.c:137
#define osFchmod
static int unixFullPathname(sqlite3_vfs *pVfs, const char *zPath, int nOut, char *zOut)
Definition: myvfs.c:1465
static int unixRead(sqlite3_file *id, void *pBuf, int amt, sqlite3_int64 offset)
Definition: myvfs.c:921
#define SQLITE_DEFAULT_SECTOR_SIZE
Definition: myvfs.c:14
const char * zName
Definition: tkeyvfs.cc:247
#define UNUSED_PARAMETER(x)
Definition: myvfs.c:16
static int robust_ftruncate(int h, sqlite3_int64 sz)
Definition: myvfs.c:454
struct UnixUnusedFd * pUnused
Definition: myvfs.c:119
static int unixSync(sqlite3_file *id, int flags)
Definition: myvfs.c:1057
sqlite3_syscall_ptr pCurrent
Definition: tkeyvfs.cc:248
static int sqlite3CantopenError(int lineno)
Definition: myvfs.c:212
static int unixSectorSize(sqlite3_file *NotUsed)
Definition: myvfs.c:1191
int nRef
Definition: myvfs.c:92
#define UNUSED_PARAMETER2(x, y)
Definition: myvfs.c:17
int myvfs_init(void)
Definition: myvfs.c:1748
static int sqlite3Strlen30(const char *z)
Definition: myvfs.c:234
static void * unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename)
Definition: myvfs.c:1498
static int unixWrite(sqlite3_file *id, const void *pBuf, int amt, sqlite3_int64 offset)
Definition: myvfs.c:955
#define osPread
#define SQLITE_FCNTL_SYNC_OMITTED
Definition: myvfs.c:11
#define osPwrite64
#define UNIXVFS(VFSNAME, FINDER)
#define UNIXFILE_RDONLY
Definition: myvfs.c:138
static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut)
Definition: myvfs.c:1511
static int fillInUnixFile(sqlite3_vfs *pVfs, int h, int dirfd, sqlite3_file *pId, const char *zFilename, int noLock, int isDelete, int isReadOnly)
Definition: myvfs.c:493
static int full_fsync(int fd, int fullSync, int dataOnly)
Definition: myvfs.c:826
static int openDirectory(const char *zFilename, int *pFd)
Definition: myvfs.c:555
#define MAX_PATHNAME
Definition: myvfs.c:50
struct unixInodeInfo * pNext
Definition: myvfs.c:96
static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt)
Definition: myvfs.c:852
unsigned char ctrlFlags
Definition: myvfs.c:116
static int unixLogErrorAtLine(int errcode, const char *zFunc, const char *zPath, int iLine)
Definition: myvfs.c:391
static int unixTruncate(sqlite3_file *id, i64 nByte)
Definition: myvfs.c:1008
static const char * unixNextSystemCall(sqlite3_vfs *p, const char *zName)
Definition: myvfs.c:1729
#define SQLITE_FCNTL_SIZE_HINT
Definition: myvfs.c:9
#define unixLogError(a, b, c)
Definition: myvfs.c:390
unsigned char bProcessLock
Definition: myvfs.c:91
static int findCreateFileMode(const char *zPath, int flags, mode_t *pMode)
Definition: myvfs.c:722
unsigned char eFileLock
Definition: myvfs.c:90
static int unixSetSystemCall(sqlite3_vfs *pNotUsed, const char *zName, sqlite3_syscall_ptr pNewFunc)
Definition: myvfs.c:1665
#define O_BINARY
Definition: myvfs.c:154
#define SQLITE_TEMP_FILE_PREFIX
Definition: myvfs.c:52
std::string getenv(std::string const &name)
Definition: getenv.cc:15
#define osOpen
#define SQLITE_OPEN_WAL
Definition: myvfs.c:8
static int closeUnixFile(sqlite3_file *id)
Definition: myvfs.c:474
double z
static struct UnixUnusedFd * findReusableFd(const char *zPath, int flags)
Definition: myvfs.c:667
struct unixInodeInfo * pPrev
Definition: myvfs.c:97
#define osFallocate
static int unixDeviceCharacteristics(sqlite3_file *NotUsed)
Definition: myvfs.c:1200
static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2)
Definition: myvfs.c:1131
sqlite_int64 i64
Definition: myvfs.c:21
#define SQLITE_DEFAULT_FILE_PERMISSIONS
Definition: myvfs.c:44
static int robust_open(const char *z, int f, int m)
Definition: myvfs.c:421
sqlite3_io_methods const * pMethod
Definition: tkeyvfs.cc:97
static int nolockLock(sqlite3_file *NotUsed, int NotUsed2)
Definition: myvfs.c:1125
struct UnixUnusedFd * pUnused
Definition: myvfs.c:95
#define osPread64
unsigned char inNormalWrite
Definition: tkeyvfs.cc:118
static int unixGetTempname(int nBuf, char *zBuf)
Definition: myvfs.c:616
#define SQLITE_CANTOPEN_BKPT
Definition: myvfs.c:224
static sqlite3_syscall_ptr unixGetSystemCall(sqlite3_vfs *pNotUsed, const char *zName)
Definition: myvfs.c:1711
int h
Definition: myvfs.c:113
static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow)
Definition: myvfs.c:1616
static int unixDelete(sqlite3_vfs *NotUsed, const char *zPath, int dirSync)
Definition: myvfs.c:1390
unsigned char eFileLock
Definition: myvfs.c:115
static int fcntlSizeHint(unixFile *pFile, i64 nByte)
Definition: myvfs.c:776
p
Definition: test.py:228
#define osFtruncate
static int unixFileControl(sqlite3_file *id, int op, void *pArg)
Definition: myvfs.c:1147
int dirfd
Definition: myvfs.c:114
ino_t ino
Definition: myvfs.c:62
static struct unixInodeInfo * inodeList
Definition: myvfs.c:103
struct unixFileId fileId
Definition: myvfs.c:88
int lastErrno
Definition: tkeyvfs.cc:106
static const char * unixTempFileDir(void)
Definition: myvfs.c:576
static int unixSleep(sqlite3_vfs *NotUsed, int microseconds)
Definition: myvfs.c:1604
#define osRead
static int unixAccess(sqlite3_vfs *NotUsed, const char *zPath, int flags, int *pResOut)
Definition: myvfs.c:1424
static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt)
Definition: myvfs.c:883
void * lockingContext
Definition: myvfs.c:118
#define SQLITE_FCNTL_DB_UNCHANGED
Definition: myvfs.c:13
struct unixInodeInfo * pInode
Definition: myvfs.c:112
#define O_LARGEFILE
Definition: myvfs.c:144
struct unixShmNode unixShmNode
Definition: myvfs.c:54
#define osStat
#define osFstat
unsigned char dbUpdate
Definition: tkeyvfs.cc:117
#define ArraySize(X)
Definition: myvfs.c:19
def access(path, mode)
const char * zPath
Definition: tkeyvfs.cc:107
#define osWrite
static void(*)(void) unixDlSym(sqlite3_vfs *NotUsed, void *p, const char *zSym)
Definition: myvfs.c:199
struct UnixUnusedFd * pNext
Definition: myvfs.c:75
static int nolockClose(sqlite3_file *id)
Definition: myvfs.c:910
dev_t dev
Definition: myvfs.c:61
int flags
Definition: myvfs.c:74
def open(path, mode='r', buf=-1)
static struct unix_syscall aSyscall[]
int szChunk
Definition: tkeyvfs.cc:108
static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle)
Definition: myvfs.c:1546
#define osGetcwd
static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut)
Definition: myvfs.c:1137
int fd
Definition: myvfs.c:73
static const sqlite3_io_methods nolockIoMethods
Definition: myvfs.c:340
#define SQLITE_FCNTL_CHUNK_SIZE
Definition: myvfs.c:10
int nLock
Definition: myvfs.c:94
static void robust_close(unixFile *pFile, int h, int lineno)
Definition: myvfs.c:444
#define osAccess
h
training ###############################
Definition: train_cnn.py:186
#define O_NOFOLLOW
Definition: myvfs.c:151