interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / ext / misc / tmstmpvfs.c

1058 lines · 34971 bytes Raw Blame History
1/*
2** 2026-01-05
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11******************************************************************************
12**
13** This file implements a VFS shim that writes a timestamp and other tracing
14** information into 16 bytes of reserved space at the end of each page of the
15** database file.
16**
17** The VFS also tries to generate log-files with names of the form:
18**
19** $(DATABASE)-tmstmp/$(TIME)-$(PID)-$(ID)
20**
21** Log files are only generated if directory $(DATABASE)-tmstmp exists.
22** The name of each log file is the current ISO8601 time in milliseconds,
23** the process ID, and a random 32-bit value (to disambiguate multiple
24** connections from the same process) separated by dashes. The log file
25** contains 16-bytes records for various events, such as opening or close
26** of the database or WAL file, writes to the WAL file, checkpoints, and
27** similar. The logfile is only generated if the connection attempts to
28** modify the database. There is a separate log file for each open database
29** connection.
30**
31** COMPILING
32**
33** To build this extension as a separately loaded shared library or
34** DLL, use compiler command-lines similar to the following:
35**
36** (linux) gcc -fPIC -shared tmstmpvfs.c -o tmstmpvfs.so
37** (mac) clang -fPIC -dynamiclib tmstmpvfs.c -o tmstmpvfs.dylib
38** (windows) cl tmstmpvfs.c -link -dll -out:tmstmpvfs.dll
39**
40** You may want to add additional compiler options, of course,
41** according to the needs of your project.
42**
43** Another option is to statically link both SQLite and this extension
44** into your application. If both this file and "sqlite3.c" are statically
45** linked, and if "sqlite3.c" is compiled with an option like:
46**
47** -DSQLITE_EXTRA_INIT=sqlite3_register_tmstmpvfs
48**
49** Then SQLite will use the tmstmp VFS by default throughout your
50** application.
51**
52** LOADING
53**
54** To load this extension as a shared library, you first have to
55** bring up a dummy SQLite database connection to use as the argument
56** to the sqlite3_load_extension() API call. Then you invoke the
57** sqlite3_load_extension() API and shutdown the dummy database
58** connection. All subsequent database connections that are opened
59** will include this extension. For example:
60**
61** sqlite3 *db;
62** sqlite3_open(":memory:", &db);
63** sqlite3_load_extension(db, "./tmstmpvfs");
64** sqlite3_close(db);
65**
66** Tmstmpvfs is a VFS Shim. When loaded, "tmstmpvfs" becomes the new
67** default VFS and it uses the prior default VFS as the next VFS
68** down in the stack. This is normally what you want. However, in
69** complex situations where multiple VFS shims are being loaded,
70** it might be important to ensure that tmstmpvfs is loaded in the
71** correct order so that it sequences itself into the default VFS
72** Shim stack in the right order.
73**
74** When running the CLI, you can load this extension at invocation by
75** adding a command-line option like this: "--vfs ./tmstmpvfs.so".
76** The --vfs option usually specifies the symbolic name of a built-in VFS.
77** But if the argument to --vfs is not a built-in VFS but is instead the
78** name of a file, the CLI tries to load that file as an extension. Note
79** that the full name of the extension file must be provided, including
80** the ".so" or ".dylib" or ".dll" suffix.
81**
82** An application can see if the tmstmpvfs is being used by examining
83** the results from SQLITE_FCNTL_VFSNAME (or the .vfsname command in
84** the CLI). If the answer include "tmstmp", then this VFS is being
85** used.
86**
87** USING
88**
89** Open database connections using the sqlite3_open() or
90** sqlite3_open_v2() interfaces, as normal. Ordinary database files
91** (without a timestamp) will operate normally.
92**
93** Timestamping only works on databases that have a reserve-bytes
94** value of exactly 16. The default value for reserve-bytes is 0.
95** Hence, newly created database files will omit the timestamp by
96** default. To create a database that includes a timestamp, change
97** the reserve-bytes value to 16 by running:
98**
99** int n = 16;
100** sqlite3_file_control(db, 0, SQLITE_FCNTL_RESERVE_BYTES, &n);
101**
102** If you do this immediately after creating a new database file,
103** before anything else has been written into the file, then that
104** might be all that you need to do. Otherwise, the API call
105** above should be followed by:
106**
107** sqlite3_exec(db, "VACUUM", 0, 0, 0);
108**
109** It never hurts to run the VACUUM, even if you don't need it.
110**
111** From the CLI, use the ".filectrl reserve_bytes 16" command,
112** followed by "VACUUM;".
113**
114** SQLite allows the number of reserve-bytes to be increased, but
115** not decreased. If you want to restore the reserve-bytes to 0
116** (to disable tmstmpvfs), the easiest approach is to use VACUUM INTO
117** with a URI filename as the argument and include "reserve=0" query
118** parameter on the URI. Example:
119**
120** VACUUM INTO 'file:notimestamps.db?reserve=0';
121**
122** Then switch over to using the new database file. The reserve=0 query
123** parameter only works on SQLite 3.52.0 and later.
124**
125** IMPLEMENTATION NOTES
126**
127** The timestamp information is stored in the last 16 bytes of each page.
128** This module only operates if the "bytes of reserved space on each page"
129** value at offset 20 the SQLite database header is exactly 16. If
130** the reserved-space value is not 16, no timestamp information is added
131** to database pages. Some, but not all, logfile entries will be made
132** still, but the size of the logs will be greatly reduced.
133**
134** The timestamp layout is as follows:
135**
136** bytes 0,1 Zero. Reserved for future expansion
137** bytes 2-7 Milliseconds since the Unix Epoch
138** bytes 8-11 WAL frame number
139** bytes 12 0: WAL write 2: rollback write
140** bytes 13-15 Lower 24 bits of Salt-1
141**
142** For transactions that occur in rollback mode, only the timestamp
143** in bytes 2-7 and byte 12 are non-zero. Byte 12 is set to 2 for
144** rollback writes.
145**
146** The 16-byte tag is added to each database page when the content
147** is written into the database file itself. This shim does not make
148** any changes to the page as it is written to the WAL file, since
149** that would mess up the WAL checksum.
150**
151** LOGGING
152**
153** An open database connection that attempts to write to the database
154** will create a log file if a directory name $(DATABASE)-tmstmp exists.
155** The name of the log file is:
156**
157** $(TIME)-$(PID)-$(RANDOM)
158**
159** Where TIME is an ISO 8601 date in milliseconds with no punctuation,
160** PID is the process ID, and RANDOM is a 32-bit random number expressed
161** as hexadecimal.
162**
163** The log consists of 16-byte records. Each record consists of five
164** unsigned integers:
165**
166** 1 1 6 4 4 <--- bytes
167** op a1 ts a2 a3
168**
169** The meanings of the a1-a3 values depend on op. ts is the timestamp
170** in milliseconds since the unix epoch (1970-01-01 00:00:00).
171** Opcodes are defined by the ELOG_* #defines below.
172**
173** ELOG_OPEN_DB "Open a connection to the database file"
174** op = 0x01
175** a2 = process-ID
176**
177** ELOG_OPEN_WAL "Open a connection to the -wal file"
178** op = 0x02
179** a2 = process-ID
180**
181** ELOG_WAL_PAGE "New page added to the WAL file"
182** op = 0x03
183** a1 = 0x1 set if last page of txn. 0x2 if all zeros
184** a2 = page number in the DB file
185** a3 = frame number in the WAL file
186**
187** ELOG_DB_PAGE "Database page updated using rollback mode"
188** op = 0x04
189** a1 = 0x2 set if all zeros
190** a2 = page number in the DB file
191**
192** ELOG_CKPT_START "Start of a checkpoint operation"
193** op = 0x05
194**
195** ELOG_CKPT_PAGE "Page xfer from WAL to database"
196** op = 0x06
197** a1 = 0x2 set if all zeros
198** a2 = database page number
199** a3 = frame number in the WAL file
200**
201** ELOG_CKPT_END "Start of a checkpoint operation"
202** op = 0x07
203**
204** ELOG_WAL_RESET "WAL file header overwritten"
205** op = 0x08
206** a3 = Salt1 value
207**
208** ELOG_CLOSE_WAL "Close the WAL file connection"
209** op = 0x0e
210**
211** ELOG_CLOSE_DB "Close the DB connection"
212** op = 0x0f
213**
214** VIEWING TIMESTAMPS AND LOGS
215**
216** The command-line utility at tool/showtmlog.c will read and display
217** the content of one or more tmstmpvfs.c log files. If all of the
218** log files are stored in directory $(DATABASE)-tmstmp, then you can
219** view them all using a command like shown below (with an extra "?"
220** inserted on the wildcard to avoid closing the C-language comment
221** that contains this text):
222**
223** showtmlog $(DATABASE)-tmstmp/?*
224**
225** The command-line utility at tools/showdb.c can be used to show the
226** timestamps on pages of a database file, using a command like this:
227**
228** showdb --tmstmp $(DATABASE) pgidx
229*
230** The command above shows the timestamp and the intended use of every
231** pages in the database, in human-readable form. If you also add
232** the --csv option to the command above, then the command generates
233** a Comma-Separated-Value (CSV) file as output, which contains a
234** decoding of the complete timestamp tag on each page of the database.
235** This CVS file can be easily imported into another SQLite database
236** using a CLI command like the following:
237**
238** .import --csv '|showdb --tmstmp -csv orig.db pgidx' ts_table
239**
240** In the command above, the database containing the timestamps is
241** "orig.db" and the content is imported into a new table named "ts_table".
242** The "ts_table" is created automatically, using the column names found
243** in the first line of the CSV file. All columns of the automatically
244** created ts_table are of type TEXT. It might make more sense to
245** create the table yourself, using more sensible datatypes, like this:
246**
247** CREATE TABLE ts_table (
248** pgno INT, -- page number
249** tm REAL, -- seconds since 1970-01-01
250** frame INT, -- WAL frame number
251** flg INT, -- flag (tag byte 12)
252** salt INT, -- WAL salt (tag bytes 13-15)
253** parent INT, -- Parent page number
254** child INT, -- Index of this page in its parent
255** ovfl INT, -- Index of this page on the overflow chain
256** txt TEXT -- Description of this page
257** );
258**
259** Then import using:
260**
261** .import --csv --skip 1 '|showdb --tmstmp --csv orig.db pgidx' ts_table
262**
263** Note the addition of the "--skip 1" option on ".import" to bypass the
264** first line of the CSV file that contains the column names.
265**
266** Both programs "showdb" and "showtmlog" can be built by running
267** "make showtmlog showdb" from the top-level of a recent SQLite
268** source tree.
269*/
270#if defined(SQLITE_AMALGAMATION) && !defined(SQLITE_TMSTMPVFS_STATIC)
271# define SQLITE_TMSTMPVFS_STATIC
272#endif
273#ifdef SQLITE_TMSTMPVFS_STATIC
274# include "sqlite3.h"
275#else
276# include "sqlite3ext.h"
277 SQLITE_EXTENSION_INIT1
278#endif
279#include <string.h>
280#include <assert.h>
281#include <stdio.h>
282
283/*
284** Forward declaration of objects used by this utility
285*/
286typedef struct sqlite3_vfs TmstmpVfs;
287typedef struct TmstmpFile TmstmpFile;
288typedef struct TmstmpLog TmstmpLog;
289
290/*
291** Bytes of reserved space used by this extension
292*/
293#define TMSTMP_RESERVE 16
294
295/*
296** The magic number used to identify TmstmpFile objects
297*/
298#define TMSTMP_MAGIC 0x2a87b72d
299
300/*
301** Useful datatype abbreviations
302*/
303#if !defined(SQLITE_AMALGAMATION)
304 typedef unsigned char u8;
305 typedef unsigned int u32;
306#endif
307
308/*
309** Current process id
310*/
311#if defined(_WIN32)
312# include <windows.h>
313# define GETPID (u32)GetCurrentProcessId()
314#else
315# include <unistd.h>
316# define GETPID (u32)getpid()
317#endif
318
319/* Access to a lower-level VFS that (might) implement dynamic loading,
320** access to randomness, etc.
321*/
322#define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
323#define ORIGFILE(p) ((sqlite3_file*)(((TmstmpFile*)(p))+1))
324
325/* Information for the tmstmp log file. */
326struct TmstmpLog {
327 char *zLogname; /* Log filename */
328 FILE *log; /* Open log file */
329 int n; /* Bytes of a[] used */
330 unsigned char a[16*6]; /* Buffered header for the log */
331};
332
333/* An open WAL or DB file */
334struct TmstmpFile {
335 sqlite3_file base; /* IO methods */
336 u32 uMagic; /* Magic number for sanity checking */
337 u32 salt1; /* Last WAL salt-1 value */
338 u32 iFrame; /* Last WAL frame number */
339 u32 pgno; /* Current page number */
340 u32 pgsz; /* Size of each page, in bytes */
341 u8 isWal; /* True if this is a WAL file */
342 u8 isDb; /* True if this is a DB file */
343 u8 isCommit; /* Last WAL frame header was a transaction commit */
344 u8 hasCorrectReserve; /* File has the correct reserve size */
345 u8 inCkpt; /* True if in a checkpoint */
346 TmstmpLog *pLog; /* Log file */
347 TmstmpFile *pPartner; /* DB->WAL or WAL->DB mapping */
348 sqlite3_int64 iOfst; /* Offset of last WAL frame header */
349 sqlite3_vfs *pSubVfs; /* Underlying VFS */
350};
351
352/*
353** Event log opcodes
354*/
355#define ELOG_OPEN_DB 0x01
356#define ELOG_OPEN_WAL 0x02
357#define ELOG_WAL_PAGE 0x03
358#define ELOG_DB_PAGE 0x04
359#define ELOG_CKPT_START 0x05
360#define ELOG_CKPT_PAGE 0x06
361#define ELOG_CKPT_DONE 0x07
362#define ELOG_WAL_RESET 0x08
363#define ELOG_CLOSE_WAL 0x0e
364#define ELOG_CLOSE_DB 0x0f
365
366/*
367** Methods for TmstmpFile
368*/
369static int tmstmpClose(sqlite3_file*);
370static int tmstmpRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
371static int tmstmpWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
372static int tmstmpTruncate(sqlite3_file*, sqlite3_int64 size);
373static int tmstmpSync(sqlite3_file*, int flags);
374static int tmstmpFileSize(sqlite3_file*, sqlite3_int64 *pSize);
375static int tmstmpLock(sqlite3_file*, int);
376static int tmstmpUnlock(sqlite3_file*, int);
377static int tmstmpCheckReservedLock(sqlite3_file*, int *pResOut);
378static int tmstmpFileControl(sqlite3_file*, int op, void *pArg);
379static int tmstmpSectorSize(sqlite3_file*);
380static int tmstmpDeviceCharacteristics(sqlite3_file*);
381static int tmstmpShmMap(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
382static int tmstmpShmLock(sqlite3_file*, int offset, int n, int flags);
383static void tmstmpShmBarrier(sqlite3_file*);
384static int tmstmpShmUnmap(sqlite3_file*, int deleteFlag);
385static int tmstmpFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
386static int tmstmpUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
387
388/*
389** Methods for TmstmpVfs
390*/
391static int tmstmpOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
392static int tmstmpDelete(sqlite3_vfs*, const char *zName, int syncDir);
393static int tmstmpAccess(sqlite3_vfs*, const char *zName, int flags, int *);
394static int tmstmpFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
395static void *tmstmpDlOpen(sqlite3_vfs*, const char *zFilename);
396static void tmstmpDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
397static void (*tmstmpDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
398static void tmstmpDlClose(sqlite3_vfs*, void*);
399static int tmstmpRandomness(sqlite3_vfs*, int nByte, char *zOut);
400static int tmstmpSleep(sqlite3_vfs*, int microseconds);
401static int tmstmpCurrentTime(sqlite3_vfs*, double*);
402static int tmstmpGetLastError(sqlite3_vfs*, int, char *);
403static int tmstmpCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
404static int tmstmpSetSystemCall(sqlite3_vfs*, const char*,sqlite3_syscall_ptr);
405static sqlite3_syscall_ptr tmstmpGetSystemCall(sqlite3_vfs*, const char *z);
406static const char *tmstmpNextSystemCall(sqlite3_vfs*, const char *zName);
407
408static sqlite3_vfs tmstmp_vfs = {
409 3, /* iVersion (set when registered) */
410 0, /* szOsFile (set when registered) */
411 1024, /* mxPathname */
412 0, /* pNext */
413 "tmstmpvfs", /* zName */
414 0, /* pAppData (set when registered) */
415 tmstmpOpen, /* xOpen */
416 tmstmpDelete, /* xDelete */
417 tmstmpAccess, /* xAccess */
418 tmstmpFullPathname, /* xFullPathname */
419 tmstmpDlOpen, /* xDlOpen */
420 tmstmpDlError, /* xDlError */
421 tmstmpDlSym, /* xDlSym */
422 tmstmpDlClose, /* xDlClose */
423 tmstmpRandomness, /* xRandomness */
424 tmstmpSleep, /* xSleep */
425 tmstmpCurrentTime, /* xCurrentTime */
426 tmstmpGetLastError, /* xGetLastError */
427 tmstmpCurrentTimeInt64, /* xCurrentTimeInt64 */
428 tmstmpSetSystemCall, /* xSetSystemCall */
429 tmstmpGetSystemCall, /* xGetSystemCall */
430 tmstmpNextSystemCall /* xNextSystemCall */
431};
432
433static const sqlite3_io_methods tmstmp_io_methods = {
434 3, /* iVersion */
435 tmstmpClose, /* xClose */
436 tmstmpRead, /* xRead */
437 tmstmpWrite, /* xWrite */
438 tmstmpTruncate, /* xTruncate */
439 tmstmpSync, /* xSync */
440 tmstmpFileSize, /* xFileSize */
441 tmstmpLock, /* xLock */
442 tmstmpUnlock, /* xUnlock */
443 tmstmpCheckReservedLock, /* xCheckReservedLock */
444 tmstmpFileControl, /* xFileControl */
445 tmstmpSectorSize, /* xSectorSize */
446 tmstmpDeviceCharacteristics, /* xDeviceCharacteristics */
447 tmstmpShmMap, /* xShmMap */
448 tmstmpShmLock, /* xShmLock */
449 tmstmpShmBarrier, /* xShmBarrier */
450 tmstmpShmUnmap, /* xShmUnmap */
451 tmstmpFetch, /* xFetch */
452 tmstmpUnfetch /* xUnfetch */
453};
454
455/*
456** Write a 6-byte millisecond timestamp into aOut[]
457*/
458static void tmstmpPutTS(TmstmpFile *p, unsigned char *aOut){
459 sqlite3_uint64 tm = 0;
460 p->pSubVfs->xCurrentTimeInt64(p->pSubVfs, (sqlite3_int64*)&tm);
461 tm -= 210866760000000LL;
462 aOut[0] = (tm>>40)&0xff;
463 aOut[1] = (tm>>32)&0xff;
464 aOut[2] = (tm>>24)&0xff;
465 aOut[3] = (tm>>16)&0xff;
466 aOut[4] = (tm>>8)&0xff;
467 aOut[5] = tm&0xff;
468}
469
470/*
471** Read a 32-bit big-endian unsigned integer and return it.
472*/
473static u32 tmstmpGetU32(const unsigned char *a){
474 return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3];
475}
476
477/* Write a 32-bit integer as big-ending into a[]
478*/
479static void tmstmpPutU32(u32 v, unsigned char *a){
480 a[0] = (v>>24) & 0xff;
481 a[1] = (v>>16) & 0xff;
482 a[2] = (v>>8) & 0xff;
483 a[3] = v & 0xff;
484}
485
486/* Free a TmstmpLog object */
487static void tmstmpLogFree(TmstmpLog *pLog){
488 if( pLog==0 ) return;
489 if( pLog->log ) fclose(pLog->log);
490 sqlite3_free(pLog->zLogname);
491 sqlite3_free(pLog);
492}
493
494/* Flush log content. Open the file if necessary. Return the
495** number of errors. */
496static int tmstmpLogFlush(TmstmpFile *p){
497 TmstmpLog *pLog = p->pLog;
498 assert( pLog!=0 );
499 if( pLog->log==0 ){
500 pLog->log = fopen(pLog->zLogname, "wb");
501 if( pLog->log==0 ){
502 tmstmpLogFree(pLog);
503 p->pLog = 0;
504 return 1;
505 }
506 }
507 (void)fwrite(pLog->a, pLog->n, 1, pLog->log);
508 fflush(pLog->log);
509 pLog->n = 0;
510 return 0;
511}
512
513/*
514** Write a record onto the event log
515*/
516static void tmstmpEvent(
517 TmstmpFile *p,
518 u8 op,
519 u8 a1,
520 u32 a2,
521 u32 a3,
522 u8 *pTS
523){
524 unsigned char *a;
525 TmstmpLog *pLog;
526 if( p->isWal ){
527 p = p->pPartner;
528 assert( p!=0 );
529 assert( p->isDb );
530 }
531 pLog = p->pLog;
532 if( pLog==0 ) return;
533 if( pLog->n >= (int)sizeof(pLog->a) ){
534 if( tmstmpLogFlush(p) ) return;
535 }
536 a = pLog->a + pLog->n;
537 a[0] = op;
538 a[1] = a1;
539 if( pTS ){
540 memcpy(a+2, pTS, 6);
541 }else{
542 tmstmpPutTS(p, a+2);
543 }
544 tmstmpPutU32(a2, a+8);
545 tmstmpPutU32(a3, a+12);
546 pLog->n += 16;
547 if( pLog->log || (op>=ELOG_WAL_PAGE && op<=ELOG_WAL_RESET) ){
548 (void)tmstmpLogFlush(p);
549 }
550}
551
552/*
553** Close a connection
554*/
555static int tmstmpClose(sqlite3_file *pFile){
556 TmstmpFile *p = (TmstmpFile *)pFile;
557 if( p->hasCorrectReserve ){
558 tmstmpEvent(p, p->isDb ? ELOG_CLOSE_DB : ELOG_CLOSE_WAL, 0, 0, 0, 0);
559 }
560 tmstmpLogFree(p->pLog);
561 if( p->pPartner ){
562 assert( p->pPartner->pPartner==p );
563 p->pPartner->pPartner = 0;
564 p->pPartner = 0;
565 }
566 pFile = ORIGFILE(pFile);
567 return pFile->pMethods->xClose(pFile);
568}
569
570/*
571** Read bytes from a file
572*/
573static int tmstmpRead(
574 sqlite3_file *pFile,
575 void *zBuf,
576 int iAmt,
577 sqlite_int64 iOfst
578){
579 int rc;
580 TmstmpFile *p = (TmstmpFile*)pFile;
581 pFile = ORIGFILE(pFile);
582 rc = pFile->pMethods->xRead(pFile, zBuf, iAmt, iOfst);
583 if( rc!=SQLITE_OK ) return rc;
584 if( p->isDb
585 && iOfst==0
586 && iAmt>=100
587 ){
588 const unsigned char *a = (unsigned char*)zBuf;
589 p->hasCorrectReserve = (a[20]==TMSTMP_RESERVE);
590 p->pgsz = (a[16]<<8) + a[17];
591 if( p->pgsz==1 ) p->pgsz = 65536;
592 if( p->pPartner ){
593 p->pPartner->hasCorrectReserve = p->hasCorrectReserve;
594 p->pPartner->pgsz = p->pgsz;
595 }
596 }
597 if( p->isWal
598 && p->inCkpt
599 && iAmt>=512 && iAmt<=65535 && (iAmt&(iAmt-1))==0
600 ){
601 p->pPartner->iFrame = (iOfst-56)/(p->pgsz+24) + 1;
602 }
603 return rc;
604}
605
606/*
607** Return 0x02 if all bytes of zBuf are zero. Return 0x00 if one
608** or more bytes are non-zero.
609*/
610static u8 tmstmpAllZero(const void *zBuf, int n){
611 const u8 *a = (const u8*)zBuf;
612 int i;
613 for(i=0; i<n; i++){ if( a[i] ) return 0x00; }
614 return 0x02;
615}
616
617/*
618** Write data to a tmstmp-file.
619*/
620static int tmstmpWrite(
621 sqlite3_file *pFile,
622 const void *zBuf,
623 int iAmt,
624 sqlite_int64 iOfst
625){
626 TmstmpFile *p = (TmstmpFile*)pFile;
627 sqlite3_file *pSub = ORIGFILE(pFile);
628 if( !p->hasCorrectReserve ){
629 /* The database does not have the correct reserve size. No-op */
630 }else if( p->isWal ){
631 /* Writing into a WAL file */
632 if( iAmt==24 ){
633 /* A frame header */
634 u32 x = 0;
635 p->iFrame = (iOfst - 32)/(p->pgsz+24)+1;
636 p->pgno = tmstmpGetU32((const u8*)zBuf);
637 p->salt1 = tmstmpGetU32(((const u8*)zBuf)+8);
638 memcpy(&x, ((const u8*)zBuf)+4, 4);
639 p->isCommit = (x!=0);
640 p->iOfst = iOfst;
641 }else if( iAmt>=512 && iOfst==p->iOfst+24 ){
642 unsigned char s[TMSTMP_RESERVE];
643 u8 a1 = tmstmpAllZero(zBuf,iAmt-TMSTMP_RESERVE);
644 memset(s, 0, TMSTMP_RESERVE);
645 tmstmpPutTS(p, s+2);
646 tmstmpEvent(p, ELOG_WAL_PAGE, p->isCommit|a1, p->pgno, p->iFrame, s+2);
647 }else if( iAmt==32 && iOfst==0 ){
648 p->salt1 = tmstmpGetU32(((const u8*)zBuf)+16);
649 tmstmpEvent(p, ELOG_WAL_RESET, 0, 0, p->salt1, 0);
650 }
651 }else if( p->inCkpt ){
652 unsigned char *s = (unsigned char*)zBuf+iAmt-TMSTMP_RESERVE;
653 u8 a1 = tmstmpAllZero(zBuf,iAmt-TMSTMP_RESERVE);
654 memset(s, 0, TMSTMP_RESERVE);
655 tmstmpPutTS(p, s+2);
656 tmstmpPutU32(p->iFrame, s+8);
657 tmstmpPutU32(p->pPartner->salt1 & 0xffffff, s+12);
658 assert( p->pgsz>0 );
659 tmstmpEvent(p, ELOG_CKPT_PAGE, a1, (iOfst/p->pgsz)+1, p->iFrame, 0);
660 }else if( p->pPartner==0 ){
661 /* Writing into a database in rollback mode */
662 unsigned char *s = (unsigned char*)zBuf+iAmt-TMSTMP_RESERVE;
663 u8 a1 = tmstmpAllZero(zBuf,iAmt-TMSTMP_RESERVE);
664 memset(s, 0, TMSTMP_RESERVE);
665 tmstmpPutTS(p, s+2);
666 s[12] = 2;
667 assert( p->pgsz>0 );
668 tmstmpEvent(p, ELOG_DB_PAGE, a1, (u32)(iOfst/p->pgsz)+1, 0, s+2);
669 }
670 return pSub->pMethods->xWrite(pSub,zBuf,iAmt,iOfst);
671}
672
673/*
674** Truncate a tmstmp-file.
675*/
676static int tmstmpTruncate(sqlite3_file *pFile, sqlite_int64 size){
677 pFile = ORIGFILE(pFile);
678 return pFile->pMethods->xTruncate(pFile, size);
679}
680
681/*
682** Sync a tmstmp-file.
683*/
684static int tmstmpSync(sqlite3_file *pFile, int flags){
685 pFile = ORIGFILE(pFile);
686 return pFile->pMethods->xSync(pFile, flags);
687}
688
689/*
690** Return the current file-size of a tmstmp-file.
691*/
692static int tmstmpFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
693 TmstmpFile *p = (TmstmpFile *)pFile;
694 pFile = ORIGFILE(p);
695 return pFile->pMethods->xFileSize(pFile, pSize);
696}
697
698/*
699** Lock a tmstmp-file.
700*/
701static int tmstmpLock(sqlite3_file *pFile, int eLock){
702 pFile = ORIGFILE(pFile);
703 return pFile->pMethods->xLock(pFile, eLock);
704}
705
706/*
707** Unlock a tmstmp-file.
708*/
709static int tmstmpUnlock(sqlite3_file *pFile, int eLock){
710 pFile = ORIGFILE(pFile);
711 return pFile->pMethods->xUnlock(pFile, eLock);
712}
713
714/*
715** Check if another file-handle holds a RESERVED lock on a tmstmp-file.
716*/
717static int tmstmpCheckReservedLock(sqlite3_file *pFile, int *pResOut){
718 pFile = ORIGFILE(pFile);
719 return pFile->pMethods->xCheckReservedLock(pFile, pResOut);
720}
721
722/*
723** File control method. For custom operations on a tmstmp-file.
724*/
725static int tmstmpFileControl(sqlite3_file *pFile, int op, void *pArg){
726 int rc;
727 TmstmpFile *p = (TmstmpFile*)pFile;
728 pFile = ORIGFILE(pFile);
729 rc = pFile->pMethods->xFileControl(pFile, op, pArg);
730 switch( op ){
731 case SQLITE_FCNTL_VFSNAME: {
732 if( p->hasCorrectReserve && rc==SQLITE_OK ){
733 *(char**)pArg = sqlite3_mprintf("tmstmp/%z", *(char**)pArg);
734 }
735 break;
736 }
737 case SQLITE_FCNTL_CKPT_START: {
738 p->inCkpt = 1;
739 assert( p->isDb );
740 assert( p->pPartner!=0 );
741 p->pPartner->inCkpt = 1;
742 if( p->hasCorrectReserve ){
743 tmstmpEvent(p, ELOG_CKPT_START, 0, 0, 0, 0);
744 }
745 rc = SQLITE_OK;
746 break;
747 }
748 case SQLITE_FCNTL_CKPT_DONE: {
749 p->inCkpt = 0;
750 assert( p->isDb );
751 assert( p->pPartner!=0 );
752 p->pPartner->inCkpt = 0;
753 if( p->hasCorrectReserve ){
754 tmstmpEvent(p, ELOG_CKPT_DONE, 0, 0, 0, 0);
755 }
756 rc = SQLITE_OK;
757 break;
758 }
759 }
760 return rc;
761}
762
763/*
764** Return the sector-size in bytes for a tmstmp-file.
765*/
766static int tmstmpSectorSize(sqlite3_file *pFile){
767 pFile = ORIGFILE(pFile);
768 return pFile->pMethods->xSectorSize(pFile);
769}
770
771/*
772** Return the device characteristic flags supported by a tmstmp-file.
773*/
774static int tmstmpDeviceCharacteristics(sqlite3_file *pFile){
775 int devchar = 0;
776 pFile = ORIGFILE(pFile);
777 devchar = pFile->pMethods->xDeviceCharacteristics(pFile);
778 return (devchar & ~SQLITE_IOCAP_SUBPAGE_READ);
779}
780
781/* Create a shared memory file mapping */
782static int tmstmpShmMap(
783 sqlite3_file *pFile,
784 int iPg,
785 int pgsz,
786 int bExtend,
787 void volatile **pp
788){
789 pFile = ORIGFILE(pFile);
790 return pFile->pMethods->xShmMap(pFile,iPg,pgsz,bExtend,pp);
791}
792
793/* Perform locking on a shared-memory segment */
794static int tmstmpShmLock(sqlite3_file *pFile, int offset, int n, int flags){
795 pFile = ORIGFILE(pFile);
796 return pFile->pMethods->xShmLock(pFile,offset,n,flags);
797}
798
799/* Memory barrier operation on shared memory */
800static void tmstmpShmBarrier(sqlite3_file *pFile){
801 pFile = ORIGFILE(pFile);
802 pFile->pMethods->xShmBarrier(pFile);
803}
804
805/* Unmap a shared memory segment */
806static int tmstmpShmUnmap(sqlite3_file *pFile, int deleteFlag){
807 pFile = ORIGFILE(pFile);
808 return pFile->pMethods->xShmUnmap(pFile,deleteFlag);
809}
810
811/* Fetch a page of a memory-mapped file */
812static int tmstmpFetch(
813 sqlite3_file *pFile,
814 sqlite3_int64 iOfst,
815 int iAmt,
816 void **pp
817){
818 pFile = ORIGFILE(pFile);
819 return pFile->pMethods->xFetch(pFile, iOfst, iAmt, pp);
820}
821
822/* Release a memory-mapped page */
823static int tmstmpUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
824 pFile = ORIGFILE(pFile);
825 return pFile->pMethods->xUnfetch(pFile, iOfst, pPage);
826}
827
828
829/*
830** Open a tmstmp file handle.
831*/
832static int tmstmpOpen(
833 sqlite3_vfs *pVfs,
834 const char *zName,
835 sqlite3_file *pFile,
836 int flags,
837 int *pOutFlags
838){
839 TmstmpFile *p, *pDb;
840 sqlite3_file *pSubFile;
841 sqlite3_vfs *pSubVfs;
842 int rc;
843
844 pSubVfs = ORIGVFS(pVfs);
845 if( (flags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_WAL))==0 ){
846 /* If the file is not a persistent database or a WAL file, then
847 ** bypass the timestamp logic all together */
848 return pSubVfs->xOpen(pSubVfs, zName, pFile, flags, pOutFlags);
849 }
850 if( (flags & SQLITE_OPEN_WAL)!=0 ){
851 pDb = (TmstmpFile*)sqlite3_database_file_object(zName);
852 if( pDb==0
853 || pDb->uMagic!=TMSTMP_MAGIC
854 || !pDb->isDb
855 || pDb->pPartner!=0
856 ){
857 return pSubVfs->xOpen(pSubVfs, zName, pFile, flags, pOutFlags);
858 }
859 }else{
860 pDb = 0;
861 }
862 p = (TmstmpFile*)pFile;
863 memset(p, 0, sizeof(*p));
864 pSubFile = ORIGFILE(pFile);
865 pFile->pMethods = &tmstmp_io_methods;
866 p->pSubVfs = pSubVfs;
867 p->uMagic = TMSTMP_MAGIC;
868 rc = pSubVfs->xOpen(pSubVfs, zName, pSubFile, flags, pOutFlags);
869 if( rc ) goto tmstmp_open_done;
870 if( pDb!=0 ){
871 p->isWal = 1;
872 p->pPartner = pDb;
873 pDb->pPartner = p;
874 }else{
875 u32 r2;
876 u32 pid;
877 TmstmpLog *pLog;
878 sqlite3_uint64 r1; /* Milliseconds since 1970-01-01 */
879 sqlite3_uint64 days; /* Days since 1970-01-01 */
880 sqlite3_uint64 sod; /* Start of date specified by r1 */
881 sqlite3_uint64 z; /* Days since 0000-03-01 */
882 sqlite3_uint64 era; /* 400-year era */
883 int h; /* hour */
884 int m; /* minute */
885 int s; /* second */
886 int f; /* millisecond */
887 int Y; /* year */
888 int M; /* month */
889 int D; /* day */
890 int y; /* year assuming March is first month */
891 unsigned int doe; /* day of 400-year era */
892 unsigned int yoe; /* year of 400-year era */
893 unsigned int doy; /* day of year */
894 unsigned int mp; /* month with March==0 */
895
896 p->isDb = 1;
897 r1 = 0;
898 pLog = sqlite3_malloc64( sizeof(TmstmpLog) );
899 if( pLog==0 ){
900 pSubFile->pMethods->xClose(pSubFile);
901 rc = SQLITE_NOMEM;
902 goto tmstmp_open_done;
903 }
904 memset(pLog, 0, sizeof(pLog[0]));
905 p->pLog = pLog;
906 p->pSubVfs->xCurrentTimeInt64(p->pSubVfs, (sqlite3_int64*)&r1);
907 r1 -= 210866760000000LL;
908 days = r1/86400000;
909 sod = (r1%86400000)/1000;
910 f = (int)(r1%1000);
911
912 h = sod/3600;
913 m = (sod%3600)/60;
914 s = sod%60;
915 z = days + 719468;
916 era = z/146097;
917 doe = (unsigned)(z - era*146097);
918 yoe = (doe - doe/1460 + doe/36524 - doe/146096)/365;
919 y = (int)yoe + era*400;
920 doy = doe - (365*yoe + yoe/4 - yoe/100);
921 mp = (5*doy + 2)/153;
922 D = doy - (153*mp + 2)/5 + 1;
923 M = mp + (mp<10 ? 3 : -9);
924 Y = y + (M <=2);
925 sqlite3_randomness(sizeof(r2), &r2);
926 pid = GETPID;
927 pLog->zLogname = sqlite3_mprintf(
928 "%s-tmstmp/%04d%02d%02dT%02d%02d%02d%03d-%08d-%08x",
929 zName, Y, M, D, h, m, s, f, pid, r2);
930 }
931 tmstmpEvent(p, p->isWal ? ELOG_OPEN_WAL : ELOG_OPEN_DB, 0, GETPID, 0, 0);
932
933tmstmp_open_done:
934 if( rc ) pFile->pMethods = 0;
935 return rc;
936}
937
938/*
939** All VFS interfaces other than xOpen are passed down into the Sub-VFS.
940*/
941static int tmstmpDelete(sqlite3_vfs *p, const char *zName, int syncDir){
942 sqlite3_vfs *pSub = ORIGVFS(p);
943 return pSub->xDelete(pSub,zName,syncDir);
944}
945static int tmstmpAccess(sqlite3_vfs *p, const char *zName, int flags, int *pR){
946 sqlite3_vfs *pSub = ORIGVFS(p);
947 return pSub->xAccess(pSub,zName,flags,pR);
948}
949static int tmstmpFullPathname(sqlite3_vfs*p,const char *zName,int n,char *zOut){
950 sqlite3_vfs *pSub = ORIGVFS(p);
951 return pSub->xFullPathname(pSub,zName,n,zOut);
952}
953static void *tmstmpDlOpen(sqlite3_vfs *p, const char *zFilename){
954 sqlite3_vfs *pSub = ORIGVFS(p);
955 return pSub->xDlOpen(pSub,zFilename);
956}
957static void tmstmpDlError(sqlite3_vfs *p, int nByte, char *zErrMsg){
958 sqlite3_vfs *pSub = ORIGVFS(p);
959 return pSub->xDlError(pSub,nByte,zErrMsg);
960}
961static void(*tmstmpDlSym(sqlite3_vfs *p, void *pDl, const char *zSym))(void){
962 sqlite3_vfs *pSub = ORIGVFS(p);
963 return pSub->xDlSym(pSub,pDl,zSym);
964}
965static void tmstmpDlClose(sqlite3_vfs *p, void *pDl){
966 sqlite3_vfs *pSub = ORIGVFS(p);
967 return pSub->xDlClose(pSub,pDl);
968}
969static int tmstmpRandomness(sqlite3_vfs *p, int nByte, char *zOut){
970 sqlite3_vfs *pSub = ORIGVFS(p);
971 return pSub->xRandomness(pSub,nByte,zOut);
972}
973static int tmstmpSleep(sqlite3_vfs *p, int microseconds){
974 sqlite3_vfs *pSub = ORIGVFS(p);
975 return pSub->xSleep(pSub,microseconds);
976}
977static int tmstmpCurrentTime(sqlite3_vfs *p, double *prNow){
978 sqlite3_vfs *pSub = ORIGVFS(p);
979 return pSub->xCurrentTime(pSub,prNow);
980}
981static int tmstmpGetLastError(sqlite3_vfs *p, int a, char *b){
982 sqlite3_vfs *pSub = ORIGVFS(p);
983 return pSub->xGetLastError(pSub,a,b);
984}
985static int tmstmpCurrentTimeInt64(sqlite3_vfs *p, sqlite3_int64 *piNow){
986 sqlite3_vfs *pSub = ORIGVFS(p);
987 return pSub->xCurrentTimeInt64(pSub,piNow);
988}
989static int tmstmpSetSystemCall(sqlite3_vfs *p, const char *zName,
990 sqlite3_syscall_ptr x){
991 sqlite3_vfs *pSub = ORIGVFS(p);
992 return pSub->xSetSystemCall(pSub,zName,x);
993}
994static sqlite3_syscall_ptr tmstmpGetSystemCall(sqlite3_vfs *p, const char *z){
995 sqlite3_vfs *pSub = ORIGVFS(p);
996 return pSub->xGetSystemCall(pSub,z);
997}
998static const char *tmstmpNextSystemCall(sqlite3_vfs *p, const char *zName){
999 sqlite3_vfs *pSub = ORIGVFS(p);
1000 return pSub->xNextSystemCall(pSub,zName);
1001}
1002
1003/*
1004** Register the tmstmp VFS as the default VFS for the system.
1005*/
1006static int tmstmpRegisterVfs(void){
1007 int rc = SQLITE_OK;
1008 sqlite3_vfs *pOrig = sqlite3_vfs_find(0);
1009 if( pOrig==0 ) return SQLITE_ERROR;
1010 if( pOrig==&tmstmp_vfs ) return SQLITE_OK;
1011 tmstmp_vfs.iVersion = pOrig->iVersion;
1012 tmstmp_vfs.pAppData = pOrig;
1013 tmstmp_vfs.szOsFile = pOrig->szOsFile + sizeof(TmstmpFile);
1014 rc = sqlite3_vfs_register(&tmstmp_vfs, 1);
1015 return rc;
1016}
1017
1018#if defined(SQLITE_TMSTMPVFS_STATIC)
1019/* This variant of the initializer runs when the extension is
1020** statically linked.
1021*/
1022int sqlite3_register_tmstmpvfs(const char *NotUsed){
1023 (void)NotUsed;
1024 return tmstmpRegisterVfs();
1025}
1026int sqlite3_unregister_tmstmpvfs(void){
1027 if( sqlite3_vfs_find("tmstmpvfs") ){
1028 sqlite3_vfs_unregister(&tmstmp_vfs);
1029 }
1030 return SQLITE_OK;
1031}
1032#endif /* defined(SQLITE_TMSTMPVFS_STATIC */
1033
1034#if !defined(SQLITE_TMSTMPVFS_STATIC)
1035/* This variant of the initializer function is used when the
1036** extension is shared library to be loaded at run-time.
1037*/
1038#ifdef _WIN32
1039__declspec(dllexport)
1040#endif
1041/*
1042** This routine is called by sqlite3_load_extension() when the
1043** extension is first loaded.
1044***/
1045int sqlite3_tmstmpvfs_init(
1046 sqlite3 *db,
1047 char **pzErrMsg,
1048 const sqlite3_api_routines *pApi
1049){
1050 int rc;
1051 SQLITE_EXTENSION_INIT2(pApi);
1052 (void)pzErrMsg; /* not used */
1053 (void)db; /* not used */
1054 rc = tmstmpRegisterVfs();
1055 if( rc==SQLITE_OK ) rc = SQLITE_OK_LOAD_PERMANENTLY;
1056 return rc;
1057}
1058#endif /* !defined(SQLITE_TMSTMPVFS_STATIC) */