Fossil SCM

fossil-scm / tools / powerloss / powerloss.c
Blame History Raw 626 lines
1
/*
2
** Copyright (c) 2026 Dan Shearer
3
**
4
** This program is free software; you can redistribute it and/or
5
** modify it under the terms of the Simplified BSD License (also
6
** known as the "2-Clause License" or "FreeBSD License".)
7
**
8
** This program is distributed in the hope that it will be useful,
9
** but without any warranty; without even the implied warranty of
10
** merchantability or fitness for a particular purpose.
11
**
12
**
13
*******************************************************************************
14
**
15
** This file is an LD_PRELOAD library for SQLite programs that simulates a
16
** power loss or killed process while writing to the database.
17
**
18
** Environment variables:
19
**
20
** STOP_DIR The working directory. The program's files are under
21
** STOP_DIR/run. Without STOP_DIR no file is tracked.
22
** STOP_AT Which stop point number to stop at, counting from 1.
23
** With 0, or without STOP_AT, the program runs to the
24
** end, and just logs the stop points.
25
** STOP_MODE "kill" for process kill mode, anything else is power mode.
26
**
27
** Tracked files under STOP_DIR/run contain ".fossil" or ".fslckout".
28
** Each tracked file is copied to STOP_DIR/shadow when a run starts,
29
** and again at each fsync() or fdatasync() stop point.
30
**
31
** In kill mode each pwrite() and write() is also a stop point,
32
** plus each fwrite() to a tracked file opened with fopen().
33
**
34
** Every process of a run counts stop points and stores them in
35
** STOP_DIR/shadow/powerloss-state.
36
**
37
** In power mode, at stop point STOP_AT each tracked file is restored, some
38
** housekeeping is done and then it exits status 77. In kill mode it exits
39
** with status 77 without changing any files, and the other processes
40
** continue.
41
**
42
** A process locks powerloss-state around each change to a tracked file.
43
** A process that locks powerloss-state after a power-mode stop exits
44
** with status 77.
45
*/
46
47
#define _GNU_SOURCE
48
#include <dirent.h>
49
#include <dlfcn.h>
50
#include <errno.h>
51
#include <fcntl.h>
52
#include <stdarg.h>
53
#include <stdio.h>
54
#include <stdlib.h>
55
#include <string.h>
56
#include <sys/stat.h>
57
#include <sys/types.h>
58
#include <unistd.h>
59
60
#define MAXFD 4096 /* Size of azFdPath[]. Higher fds are not tracked */
61
#define MAXFILE 64 /* Size of aFile[] */
62
#define MAXPATH 4096 /* Size of a buffer for a file name */
63
#define STOP_STATUS 77 /* Exit status of a process that the library stops */
64
65
static char *azFdPath[MAXFD]; /* Path of the tracked file open as each fd */
66
static char zDir[MAXPATH]; /* STOP_DIR/run, or "" without STOP_DIR */
67
static char zShadow[MAXPATH]; /* STOP_DIR/shadow */
68
static char zLog[MAXPATH]; /* STOP_DIR/log */
69
static char zState[MAXPATH+20]; /* STOP_DIR/shadow/powerloss-state */
70
static long nStopAt; /* STOP_AT, or 0 */
71
static int bKillMode; /* True in kill mode, false in power mode */
72
static char aCopyBuf[65536]; /* Buffer for copy_file() and copy_fd() */
73
74
/*
75
** The tracked files that the program has open as a FILE for writing.
76
** An unused entry has pFile==0.
77
*/
78
static struct {
79
FILE *pFile; /* The open FILE */
80
char *zPath; /* Its path, from strdup() */
81
} aFile[MAXFILE];
82
83
/*
84
** The C library's versions of the functions that this library replaces.
85
** powerloss_init() sets them. fopen(), fopen64(), fclose() and fwrite()
86
** also look up their own on first use, in case the program calls one of
87
** them before powerloss_init() runs.
88
*/
89
static int (*real_open)(const char*, int, ...);
90
static int (*real_open64)(const char*, int, ...);
91
static int (*real_close)(int);
92
static int (*real_fsync)(int);
93
static int (*real_fdatasync)(int);
94
static int (*real_unlink)(const char*);
95
static ssize_t (*real_pwrite)(int, const void*, size_t, off_t);
96
static ssize_t (*real_pwrite64)(int, const void*, size_t, off64_t);
97
static ssize_t (*real_write)(int, const void*, size_t);
98
static FILE *(*real_fopen)(const char*, const char*);
99
static FILE *(*real_fopen64)(const char*, const char*);
100
static int (*real_fclose)(FILE*);
101
static size_t (*real_fwrite)(const void*, size_t, size_t, FILE*);
102
103
/*
104
** Returns true if the file name ends with "-shm".
105
*/
106
static int is_shm(const char *z){
107
size_t n = strlen(z);
108
return n>4 && strcmp(z+n-4, "-shm")==0;
109
}
110
111
/*
112
** This is the procedure to change for testing your specific SQLite program.
113
**
114
** For Fossil, we return true if z is under STOP_DIR/run and the last component
115
** of its name contains ".fossil" or ".fslckout". That includes the
116
** journal, WAL and "-shm" files of a database.
117
**
118
*/
119
static int is_db(const char *z){
120
const char *zBase = strrchr(z, '/');
121
size_t nDir = strlen(zDir);
122
zBase = zBase ? zBase+1 : z;
123
return nDir && strncmp(z, zDir, nDir)==0 && z[nDir]=='/'
124
&& (strstr(zBase, ".fossil") || strstr(zBase, ".fslckout"));
125
}
126
127
/*
128
** Returns true if z is a tracked file.
129
*/
130
static int is_tracked(const char *z){
131
return is_db(z) && !is_shm(z);
132
}
133
134
/*
135
** Returns the absolute path of z with its symbolic links resolved, which
136
** is the path that SQLite opens. Writes the path to zBuf, which has room
137
** for MAXPATH bytes. Returns z itself without STOP_DIR, and for a file
138
** that does not exist.
139
*/
140
static const char *full_path(const char *z, char *zBuf){
141
return zDir[0] && realpath(z, zBuf) ? zBuf : z;
142
}
143
144
/*
145
** Returns the path of the tracked file that is open as fd, or 0 if fd is
146
** not a tracked file.
147
*/
148
static const char *fd_path(int fd){
149
return fd>=0 && fd<MAXFD ? azFdPath[fd] : 0;
150
}
151
152
/*
153
** Returns the index of the entry of aFile[] for f, or -1 if it has none.
154
** With f==0, the entry is an unused one, and -1 means that aFile[] is
155
** full.
156
*/
157
static int file_index(FILE *f){
158
int i;
159
for(i=0; i<MAXFILE && aFile[i].pFile!=f; i++){}
160
return i<MAXFILE ? i : -1;
161
}
162
163
/*
164
** Writes the name of the shadow copy of the tracked file z to zOut. The
165
** name is z's path under STOP_DIR/run with each "/" replaced by "%", so
166
** that the ".fslckout" files of two check-outs have separate copies.
167
*/
168
static void shadow_name(const char *z, char *zOut, size_t nOut){
169
char *zSlash;
170
size_t nShadow = strlen(zShadow);
171
snprintf(zOut, nOut, "%s/%s", zShadow, z+strlen(zDir)+1);
172
for(zSlash=strchr(zOut+nShadow+1, '/'); zSlash; zSlash=strchr(zSlash, '/')){
173
*zSlash = '%';
174
}
175
}
176
177
/*
178
** Copies the file zFrom to zTo, replacing zTo. Leaves zTo as it was if
179
** zFrom cannot be opened, and stops at the first write that fails.
180
*/
181
static void copy_file(const char *zFrom, const char *zTo){
182
ssize_t got;
183
int out;
184
int in = real_open(zFrom, O_RDONLY);
185
if( in<0 ) return;
186
out = real_open(zTo, O_WRONLY|O_CREAT|O_TRUNC, 0644);
187
if( out>=0 ){
188
while( (got = read(in, aCopyBuf, sizeof(aCopyBuf)))>0 ){
189
if( real_write(out, aCopyBuf, got)!=got ) break;
190
}
191
real_close(out);
192
}
193
real_close(in);
194
}
195
196
/*
197
** Copies the file that is open as fd to zTo, reading through fd. This is
198
** only for a file that the program has open already.
199
**
200
** Returns 0 if fd cannot be read, otherwise 1.
201
*/
202
static int copy_fd(int fd, const char *zTo){
203
ssize_t got;
204
off64_t off = 0;
205
int out;
206
got = pread64(fd, aCopyBuf, sizeof(aCopyBuf), 0);
207
if( got<0 ) return 0;
208
out = real_open(zTo, O_WRONLY|O_CREAT|O_TRUNC, 0644);
209
if( out<0 ) return 1;
210
while( got>0 ){
211
if( real_write(out, aCopyBuf, got)!=got ) break;
212
off += got;
213
got = pread64(fd, aCopyBuf, sizeof(aCopyBuf), off);
214
}
215
real_close(out);
216
return 1;
217
}
218
219
/*
220
** Visits every file under the directory zD and its subdirectories.
221
**
222
** If bRestore is false, copies each tracked file to its shadow copy.
223
**
224
** If bRestore is true, restores each tracked file from its shadow copy,
225
** deletes each tracked file that has no shadow copy, and deletes each
226
** "-shm" file of a database. This leaves the files as they were at their
227
** last sync.
228
*/
229
static void shadow_walk(const char *zD, int bRestore){
230
DIR *d = opendir(zD);
231
struct dirent *e;
232
char zPath[MAXPATH];
233
char zCopy[MAXPATH];
234
struct stat st;
235
if( d==0 ) return;
236
while( (e = readdir(d))!=0 ){
237
if( strcmp(e->d_name, ".")==0 || strcmp(e->d_name, "..")==0 ) continue;
238
snprintf(zPath, sizeof(zPath), "%s/%s", zD, e->d_name);
239
if( lstat(zPath, &st)!=0 ) continue;
240
if( S_ISDIR(st.st_mode) ){
241
shadow_walk(zPath, bRestore);
242
continue;
243
}
244
if( !is_db(zPath) ) continue;
245
shadow_name(zPath, zCopy, sizeof(zCopy));
246
if( is_shm(zPath) ){
247
if( bRestore ) real_unlink(zPath);
248
}else if( !bRestore ){
249
copy_file(zPath, zCopy);
250
}else if( access(zCopy, F_OK)==0 ){
251
copy_file(zCopy, zPath);
252
}else{
253
real_unlink(zPath);
254
}
255
}
256
closedir(d);
257
}
258
259
/*
260
** The content of the state file, STOP_DIR/shadow/powerloss-state, and the
261
** descriptor that has it locked. The file is empty until the first
262
** process of the run has copied the tracked files. After that it has the
263
** number of the last stop point and the stopped flag.
264
*/
265
typedef struct State State;
266
struct State {
267
int fd; /* The locked state file, or negative if it did not open */
268
int bStarted; /* True if the state file was not empty */
269
long nPoint; /* Number of the last stop point of the run */
270
int bStopped; /* True after a power-mode stop */
271
};
272
273
/*
274
** Writes p->nPoint and p->bStopped to the state file. The caller has the
275
** lock.
276
*/
277
static void state_write(State *p){
278
char z[64];
279
int n = snprintf(z, sizeof(z), "%ld %d\n", p->nPoint, p->bStopped);
280
if( ftruncate(p->fd, 0)==0 ) real_pwrite(p->fd, z, n, 0);
281
}
282
283
/*
284
** Opens the state file, waits for its lock, and reads the file into p.
285
** Exits with status STOP_STATUS if another process has stopped the run in
286
** power mode.
287
*/
288
static void state_lock(State *p){
289
struct flock lk;
290
char z[64];
291
ssize_t n;
292
memset(p, 0, sizeof(*p));
293
p->fd = real_open(zState, O_RDWR|O_CREAT, 0644);
294
if( p->fd<0 ) return;
295
memset(&lk, 0, sizeof(lk));
296
lk.l_type = F_WRLCK;
297
lk.l_whence = SEEK_SET;
298
while( fcntl(p->fd, F_SETLKW, &lk)!=0 && errno==EINTR ){}
299
n = pread(p->fd, z, sizeof(z)-1, 0);
300
if( n>0 ){
301
z[n] = 0;
302
p->bStarted = sscanf(z, "%ld %d", &p->nPoint, &p->bStopped)==2;
303
}
304
if( p->bStopped ) _exit(STOP_STATUS);
305
}
306
307
/*
308
** Closes the state file, which releases the lock.
309
*/
310
static void state_unlock(State *p){
311
if( p->fd>=0 ) real_close(p->fd);
312
}
313
314
/*
315
** Counts a stop point for the call zOp on the tracked file zPath, and
316
** appends it to the log. The caller has the lock.
317
**
318
** If this is stop point STOP_AT, the process exits with status
319
** STOP_STATUS. In power mode it first sets the stopped flag in the state
320
** file and restores the tracked files.
321
*/
322
static void stop_point(State *p, const char *zOp, const char *zPath){
323
FILE *f = fopen(zLog, "a");
324
int bStop;
325
p->nPoint++;
326
if( f ){
327
fprintf(f, "%ld %s %s %ld\n", p->nPoint, zOp, zPath+strlen(zDir),
328
(long)getpid());
329
fclose(f);
330
}
331
bStop = nStopAt>0 && p->nPoint==nStopAt;
332
p->bStopped = bStop && !bKillMode;
333
state_write(p);
334
if( bStop ){
335
if( !bKillMode ) shadow_walk(zDir, 1);
336
_exit(STOP_STATUS);
337
}
338
}
339
340
/*
341
** Ends the call zOp, which changed the tracked file zPath under the lock.
342
** The call is a stop point if bStop is true. Releases the lock, and
343
** leaves errno as the call set it.
344
*/
345
static void changed(State *p, int bStop, const char *zOp, const char *zPath){
346
int savedErrno = errno;
347
if( bStop ) stop_point(p, zOp, zPath);
348
state_unlock(p);
349
errno = savedErrno;
350
}
351
352
/*
353
** Runs when the program loads the library. Looks up the C library's
354
** functions and reads the environment variables. In the first process of
355
** a run, which finds the state file empty, copies each tracked file to
356
** its shadow copy.
357
*/
358
__attribute__((constructor)) static void powerloss_init(void){
359
const char *zWork;
360
State s;
361
char *zReal;
362
real_open = dlsym(RTLD_NEXT, "open");
363
real_open64 = dlsym(RTLD_NEXT, "open64");
364
real_close = dlsym(RTLD_NEXT, "close");
365
real_fsync = dlsym(RTLD_NEXT, "fsync");
366
real_fdatasync = dlsym(RTLD_NEXT, "fdatasync");
367
real_unlink = dlsym(RTLD_NEXT, "unlink");
368
real_pwrite = dlsym(RTLD_NEXT, "pwrite");
369
real_pwrite64 = dlsym(RTLD_NEXT, "pwrite64");
370
real_write = dlsym(RTLD_NEXT, "write");
371
real_fopen = dlsym(RTLD_NEXT, "fopen");
372
real_fopen64 = dlsym(RTLD_NEXT, "fopen64");
373
real_fclose = dlsym(RTLD_NEXT, "fclose");
374
real_fwrite = dlsym(RTLD_NEXT, "fwrite");
375
zWork = getenv("STOP_DIR");
376
nStopAt = getenv("STOP_AT") ? atol(getenv("STOP_AT")) : 0;
377
bKillMode = getenv("STOP_MODE") && strcmp(getenv("STOP_MODE"), "kill")==0;
378
if( zWork==0 ) return;
379
zReal = realpath(zWork, 0);
380
if( zReal ) zWork = zReal;
381
snprintf(zDir, sizeof(zDir), "%s/run", zWork);
382
snprintf(zShadow, sizeof(zShadow), "%s/shadow", zWork);
383
snprintf(zLog, sizeof(zLog), "%s/log", zWork);
384
snprintf(zState, sizeof(zState), "%s/powerloss-state", zShadow);
385
mkdir(zShadow, 0755);
386
state_lock(&s);
387
if( !s.bStarted ){
388
shadow_walk(zDir, 0);
389
state_write(&s);
390
}
391
state_unlock(&s);
392
}
393
394
/*
395
** Records the absolute path of z as the path of fd if z is a tracked
396
** file, and otherwise records that fd is not a tracked file. Returns fd.
397
** The record of a tracked file is a copy of the path from strdup().
398
*/
399
static int opened(const char *z, int fd){
400
char zAbs[MAXPATH];
401
if( fd>=0 && fd<MAXFD ){
402
z = full_path(z, zAbs);
403
free(azFdPath[fd]);
404
azFdPath[fd] = is_tracked(z) ? strdup(z) : 0;
405
}
406
return fd;
407
}
408
409
/*
410
** Replaces open(). Records the path of a tracked file.
411
*/
412
int open(const char *z, int flags, ...){
413
mode_t m = 0;
414
if( flags & O_CREAT ){
415
va_list ap;
416
va_start(ap, flags);
417
m = (mode_t)va_arg(ap, int);
418
va_end(ap);
419
}
420
return opened(z, real_open(z, flags, m));
421
}
422
423
/*
424
** Replaces open64(). Records the path of a tracked file.
425
*/
426
int open64(const char *z, int flags, ...){
427
mode_t m = 0;
428
if( flags & O_CREAT ){
429
va_list ap;
430
va_start(ap, flags);
431
m = (mode_t)va_arg(ap, int);
432
va_end(ap);
433
}
434
return opened(z, real_open64(z, flags, m));
435
}
436
437
/*
438
** Replaces close(). Deletes the record of a tracked file.
439
*/
440
int close(int fd){
441
if( fd_path(fd) ){
442
free(azFdPath[fd]);
443
azFdPath[fd] = 0;
444
}
445
return real_close(fd);
446
}
447
448
/*
449
** Syncs fd with xSync, which is the C library's fsync() or fdatasync(),
450
** and returns its result. For a tracked file, the sync runs under the
451
** lock, the library then copies the file to its shadow copy, and the call
452
** zOp is a stop point.
453
**
454
** The library reads through fd to make the shadow copy. If fd cannot be
455
** read, because the program opened it for writing only, the library reads
456
** the file by its path.
457
*/
458
static int synced(int fd, int (*xSync)(int), const char *zOp){
459
const char *z = fd_path(fd);
460
State s;
461
char zCopy[MAXPATH];
462
int rc;
463
int savedErrno;
464
if( z==0 ) return xSync(fd);
465
state_lock(&s);
466
rc = xSync(fd);
467
savedErrno = errno;
468
shadow_name(z, zCopy, sizeof(zCopy));
469
if( !copy_fd(fd, zCopy) ) copy_file(z, zCopy);
470
stop_point(&s, zOp, z);
471
state_unlock(&s);
472
errno = savedErrno;
473
return rc;
474
}
475
476
/*
477
** Replaces fsync(). A sync of a tracked file is a stop point.
478
*/
479
int fsync(int fd){
480
return synced(fd, real_fsync, "fsync");
481
}
482
483
/*
484
** Replaces fdatasync(). A sync of a tracked file is a stop point.
485
*/
486
int fdatasync(int fd){
487
return synced(fd, real_fdatasync, "fdatasync");
488
}
489
490
/*
491
** Replaces unlink(). The unlink of a tracked file runs under the lock.
492
** If it succeeds, the library deletes the file's shadow copy, and the
493
** call is a stop point.
494
*/
495
int unlink(const char *z){
496
State s;
497
char zCopy[MAXPATH];
498
char zAbs[MAXPATH];
499
const char *zFull = full_path(z, zAbs);
500
int rc;
501
if( !is_tracked(zFull) ) return real_unlink(z);
502
state_lock(&s);
503
rc = real_unlink(z);
504
if( rc==0 ){
505
shadow_name(zFull, zCopy, sizeof(zCopy));
506
real_unlink(zCopy);
507
}
508
changed(&s, rc==0, "unlink", zFull);
509
return rc;
510
}
511
512
/*
513
** Replaces pwrite(). A write to a tracked file runs under the lock, and
514
** in kill mode it is a stop point.
515
*/
516
ssize_t pwrite(int fd, const void *p, size_t n, off_t off){
517
const char *z = fd_path(fd);
518
State s;
519
ssize_t rc;
520
if( z==0 ) return real_pwrite(fd, p, n, off);
521
state_lock(&s);
522
rc = real_pwrite(fd, p, n, off);
523
changed(&s, bKillMode, "pwrite", z);
524
return rc;
525
}
526
527
/*
528
** Replaces pwrite64(). A write to a tracked file runs under the lock,
529
** and in kill mode it is a stop point, which the log records as "pwrite".
530
*/
531
ssize_t pwrite64(int fd, const void *p, size_t n, off64_t off){
532
const char *z = fd_path(fd);
533
State s;
534
ssize_t rc;
535
if( z==0 ) return real_pwrite64(fd, p, n, off);
536
state_lock(&s);
537
rc = real_pwrite64(fd, p, n, off);
538
changed(&s, bKillMode, "pwrite", z);
539
return rc;
540
}
541
542
/*
543
** Replaces write(). A write to a tracked file runs under the lock, and
544
** in kill mode it is a stop point.
545
*/
546
ssize_t write(int fd, const void *p, size_t n){
547
const char *z = fd_path(fd);
548
State s;
549
ssize_t rc;
550
if( z==0 ) return real_write(fd, p, n);
551
state_lock(&s);
552
rc = real_write(fd, p, n);
553
changed(&s, bKillMode, "write", z);
554
return rc;
555
}
556
557
/*
558
** Records the absolute path of z as the path of f in aFile[] if z is a
559
** tracked file and zMode opens it for writing. The record is a copy of
560
** the path from strdup(). Does not record the file if aFile[] is full.
561
** Returns f.
562
*/
563
static FILE *fopened(const char *z, const char *zMode, FILE *f){
564
char zAbs[MAXPATH];
565
int i;
566
if( f==0 || zDir[0]==0 || strpbrk(zMode, "wa+")==0 ) return f;
567
z = full_path(z, zAbs);
568
if( !is_tracked(z) ) return f;
569
i = file_index(0);
570
if( i>=0 ){
571
aFile[i].pFile = f;
572
aFile[i].zPath = strdup(z);
573
}
574
return f;
575
}
576
577
/*
578
** Replaces fopen(). Records a tracked file that is opened for writing.
579
*/
580
FILE *fopen(const char *z, const char *zMode){
581
if( real_fopen==0 ) real_fopen = dlsym(RTLD_NEXT, "fopen");
582
return fopened(z, zMode, real_fopen(z, zMode));
583
}
584
585
/*
586
** Replaces fopen64(). Records a tracked file that is opened for writing.
587
*/
588
FILE *fopen64(const char *z, const char *zMode){
589
if( real_fopen64==0 ) real_fopen64 = dlsym(RTLD_NEXT, "fopen64");
590
return fopened(z, zMode, real_fopen64(z, zMode));
591
}
592
593
/*
594
** Replaces fclose(). Deletes the record of f from aFile[].
595
*/
596
int fclose(FILE *f){
597
int i = file_index(f);
598
if( real_fclose==0 ) real_fclose = dlsym(RTLD_NEXT, "fclose");
599
if( i>=0 ){
600
free(aFile[i].zPath);
601
aFile[i].zPath = 0;
602
aFile[i].pFile = 0;
603
}
604
return real_fclose(f);
605
}
606
607
/*
608
** Replaces fwrite(). A write to a file in aFile[] runs under the lock,
609
** and in kill mode the call is a stop point.
610
**
611
** After a stop, the file has what the C library had written to it by
612
** then, which can be less than what the program gave to fwrite().
613
*/
614
size_t fwrite(const void *p, size_t sz, size_t n, FILE *f){
615
int i = file_index(f);
616
const char *zPath = i>=0 ? aFile[i].zPath : 0;
617
State s;
618
size_t rc;
619
if( real_fwrite==0 ) real_fwrite = dlsym(RTLD_NEXT, "fwrite");
620
if( zPath==0 ) return real_fwrite(p, sz, n, f);
621
state_lock(&s);
622
rc = real_fwrite(p, sz, n, f);
623
changed(&s, bKillMode, "fwrite", zPath);
624
return rc;
625
}
626

Keyboard Shortcuts

Open search /
Next entry (timeline) j
Previous entry (timeline) k
Open focused entry Enter
Show this help ?
Toggle theme Top nav button