Fossil SCM

Added powerloss/pkill simulation system to test for data corruption bugs on every potentially vulnerable write operation SQLite makes.

danshearer 2026-11-22 21:12 UTC test-suite-new
Commit 730cdfc18f6843f2662858a53ede0d7d8ab95a7bdd9138d7d994a6c315dc1476
+35 -16
--- test/README.md
+++ test/README.md
@@ -1,11 +1,23 @@
11
# Fossil test suite
22
3
-This is an extensible test suite written in Tcl, where a runner executes all the test files it finds in the test/ directory. Some of the tests derive their
4
-cases and expecations at runtime, including from the Fossil source code (when checking to see if the Fossil binary agrees with the source) and from
5
-testing the behaviour of the filesystem the binary is running on (when checking unicode pathname case folding.) There is also some degree of checking for
6
-platforms (eg is_windows) but that is kept to a minimum.
3
+Test a given fossil binary for correct behaviour, either explicitly or in some
4
+cases computed from the binary in question and the OS context it is running on.
5
+
6
+This is an extensible test suite written in Tcl, where a runner executes all
7
+the test files it finds in the test/ directory. Tests do not necessarily have
8
+to pass, because the optional status *knownBug* constrains a test to merely
9
+report a bug that hasn't yet been fixed. knownBug enables a useful pattern,
10
+where tests are written first and the code is improved to reduce the knownBug
11
+count to zero over time.
12
+
13
+Some of the tests derive their cases and expecations (even some knownBugs) at
14
+runtime by examining the running system and its configuration; many others have
15
+test cases hardcoded. Other tests check for particular platforms (eg
16
+`is_windows`) but we wish to keep that to a minimum because of the myriad of
17
+different system configurations that exist within any given operating system
18
+platform.
719
820
## Running the tests
921
1022
From a build directory:
1123
@@ -32,14 +44,14 @@
3244
* `-prot` also writes the output to the file `prot`.
3345
* `-trials N` sets how many random trials fuzz tests (delta1, merge2, …)
3446
run per input kind. The default is 20 (5 for expensive `large` /
3547
`repeats` inputs). Use `-trials 100` for the historical full fuzz.
3648
This flag is only the fuzz loop count; it does not select
37
- `-utf-assurance` cases.
38
-* `-utf-assurance smoke|ci|stress` selects how thoroughly the Unicode
39
- tests run. The default is `smoke`. It applies to both
40
- `unicode-pathnames` and `utf`:
49
+ `-assurance` cases.
50
+* `-assurance smoke|ci|stress` selects how thoroughly the tests run.
51
+ The default is `smoke`, which skips `powerloss`. It also sets the
52
+ cases that `unicode-pathnames` and `utf` run:
4153
- `unicode-pathnames`: `smoke` is one pair per fold-behavior class;
4254
`ci` is the full hand-written lists; `stress` adds generated pairs.
4355
At startup the harness classifies the temporary filesystem once
4456
(ASCII case, NFC/NFD, and sharp-s versus `ss`). Predictions use
4557
that classification with Fossil's `case-sensitive` setting
@@ -50,40 +62,46 @@
5062
for both yes and no.
5163
Unmet predictions fail the run.
5264
5365
`make test TESTFLAGS="-quiet update"` passes options and names via `make`.
5466
55
-Unicode assurance recipes:
67
+Assurance recipes:
5668
5769
```sh
5870
make test # smoke (default)
59
-make test TESTFLAGS="-utf-assurance ci" # full current coverage
60
-make test TESTFLAGS="-utf-assurance stress" # ci plus generated cases
71
+make test TESTFLAGS="-assurance ci" # full current coverage
72
+make test TESTFLAGS="-assurance stress" # ci plus generated cases
6173
```
6274
63
-A full run normally takes a few minutes. `tester.tcl` exits with status 0 when all tests pass, 1 when one or more tests fail. Failed tests are reported with
64
-what it expected vs what it got. The summary lists skipped files with a reason, and all known bugs reported as `FAILED (knownBug)`. Skips and known bugs do not
65
-change the exit status unless `-strict` is given.
75
+`tester.tcl` exits with status 0 when all tests pass, 1 when one or more tests
76
+fail. Failed tests are reported with what it expected vs what it got. The
77
+summary lists skipped files with a reason, and all known bugs reported as
78
+`FAILED (knownBug)`. Skips and known bugs do not change the exit status unless
79
+`-strict` is given.
6680
6781
A new test should only require adding another `.test` file.
6882
6983
## Requirements
7084
7185
* Tcl 8.6 or later, we also test with Tcl 9.0 which is now common. `configure` finds `tclsh`, and `make test` fails if it finds none.
7286
* A writable temporary directory, from `TMPDIR`, `TEMP` or `TMP`, falling back to `/tmp`. All writes are made to the temporary directory, except with `-prot`
7387
which writes a session log to wherever it was started from.
74
-* `src/` which must be next to `test/`, just as it is in the source tree. Otherwise `settings.test` and `settings-repo.test` can't read the settings from the source.
88
+* `src/` which must be at the same level in the same directory as `test/`, reflecting the source tree layout. The tests (at least) `settings.test` and `settings-repo.test` need the source to do their job.
7589
7690
The following tests are skipped when their requirements are missing:
7791
7892
| Needs | Test files |
7993
| --- | --- |
80
-| a TCP connection over the loopback interface | `unversioned` |
94
+| a TCP connection over the loopback interface | `unversioned`, and the HTTP clone in `powerloss` |
95
+| `-assurance ci` or `stress` | `powerloss` |
96
+| a C compiler (`cc`, or `CC`), `LD_PRELOAD`, `tools/powerloss/powerloss.c` from the source tree, and a Fossil that isn't statically linked | `powerloss` |
8197
| `configure --json` | `json` |
8298
| `configure --with-th1-docs` | `th1-docs` |
8399
| `configure --with-th1-hooks` | `th1-hooks` |
84100
| `configure --with-tcl` | `th1-tcl` |
101
+
102
+[`tools/powerloss/README-POWERLOSS.md`](../tools/powerloss/README-POWERLOSS.md) describes the `powerloss` library dependency.
85103
86104
None of the tests need network access. That doesn't mean all network-related tests will work, because some isolated environments don't even have loopback and
87105
the test suite detects this.
88106
89107
## Coverage
@@ -91,10 +109,11 @@
91109
| Area | Test files |
92110
| --- | --- |
93111
| Check-ins and the working tree | `amend`, `clean`, `commit-warning`, `mv-rm`, `revert`, `stash`, `symlinks`, `unicode-pathnames`, `update` |
94112
| Branches and tags | `branch-tag` |
95113
| Merges, cherrypicks, backouts, and annotate and blame after them | `merge1` to `merge6`, `merge-history`, `merge_exe`, `merge_renames`, `merge_renames_2`, `merge_warn` |
114
+| Commands interrupted by a power loss or a killed process | `powerloss` |
96115
| Git export and import, bundles, patches, ZIP and tarball archives | `roundtrip` |
97116
| Diffs and deltas | `delta1`, `diff` |
98117
| Settings | `settings`, `settings-repo`, `set-manifest` |
99118
| Wiki, attachments and unversioned files | `wiki`, `unversioned` |
100119
| TH1 scripting | `th1`, `th1-docs`, `th1-hooks`, `th1-repo`, `th1-taint`, `th1-tcl` |
101120
102121
ADDED test/powerloss.test
103122
ADDED tools/powerloss/README-POWERLOSS.md
104123
ADDED tools/powerloss/powerloss.c
105124
ADDED tools/powerloss/powerloss.sh
--- test/README.md
+++ test/README.md
@@ -1,11 +1,23 @@
1 # Fossil test suite
2
3 This is an extensible test suite written in Tcl, where a runner executes all the test files it finds in the test/ directory. Some of the tests derive their
4 cases and expecations at runtime, including from the Fossil source code (when checking to see if the Fossil binary agrees with the source) and from
5 testing the behaviour of the filesystem the binary is running on (when checking unicode pathname case folding.) There is also some degree of checking for
6 platforms (eg is_windows) but that is kept to a minimum.
 
 
 
 
 
 
 
 
 
 
 
 
7
8 ## Running the tests
9
10 From a build directory:
11
@@ -32,14 +44,14 @@
32 * `-prot` also writes the output to the file `prot`.
33 * `-trials N` sets how many random trials fuzz tests (delta1, merge2, …)
34 run per input kind. The default is 20 (5 for expensive `large` /
35 `repeats` inputs). Use `-trials 100` for the historical full fuzz.
36 This flag is only the fuzz loop count; it does not select
37 `-utf-assurance` cases.
38 * `-utf-assurance smoke|ci|stress` selects how thoroughly the Unicode
39 tests run. The default is `smoke`. It applies to both
40 `unicode-pathnames` and `utf`:
41 - `unicode-pathnames`: `smoke` is one pair per fold-behavior class;
42 `ci` is the full hand-written lists; `stress` adds generated pairs.
43 At startup the harness classifies the temporary filesystem once
44 (ASCII case, NFC/NFD, and sharp-s versus `ss`). Predictions use
45 that classification with Fossil's `case-sensitive` setting
@@ -50,40 +62,46 @@
50 for both yes and no.
51 Unmet predictions fail the run.
52
53 `make test TESTFLAGS="-quiet update"` passes options and names via `make`.
54
55 Unicode assurance recipes:
56
57 ```sh
58 make test # smoke (default)
59 make test TESTFLAGS="-utf-assurance ci" # full current coverage
60 make test TESTFLAGS="-utf-assurance stress" # ci plus generated cases
61 ```
62
63 A full run normally takes a few minutes. `tester.tcl` exits with status 0 when all tests pass, 1 when one or more tests fail. Failed tests are reported with
64 what it expected vs what it got. The summary lists skipped files with a reason, and all known bugs reported as `FAILED (knownBug)`. Skips and known bugs do not
65 change the exit status unless `-strict` is given.
 
 
66
67 A new test should only require adding another `.test` file.
68
69 ## Requirements
70
71 * Tcl 8.6 or later, we also test with Tcl 9.0 which is now common. `configure` finds `tclsh`, and `make test` fails if it finds none.
72 * A writable temporary directory, from `TMPDIR`, `TEMP` or `TMP`, falling back to `/tmp`. All writes are made to the temporary directory, except with `-prot`
73 which writes a session log to wherever it was started from.
74 * `src/` which must be next to `test/`, just as it is in the source tree. Otherwise `settings.test` and `settings-repo.test` can't read the settings from the source.
75
76 The following tests are skipped when their requirements are missing:
77
78 | Needs | Test files |
79 | --- | --- |
80 | a TCP connection over the loopback interface | `unversioned` |
 
 
81 | `configure --json` | `json` |
82 | `configure --with-th1-docs` | `th1-docs` |
83 | `configure --with-th1-hooks` | `th1-hooks` |
84 | `configure --with-tcl` | `th1-tcl` |
 
 
85
86 None of the tests need network access. That doesn't mean all network-related tests will work, because some isolated environments don't even have loopback and
87 the test suite detects this.
88
89 ## Coverage
@@ -91,10 +109,11 @@
91 | Area | Test files |
92 | --- | --- |
93 | Check-ins and the working tree | `amend`, `clean`, `commit-warning`, `mv-rm`, `revert`, `stash`, `symlinks`, `unicode-pathnames`, `update` |
94 | Branches and tags | `branch-tag` |
95 | Merges, cherrypicks, backouts, and annotate and blame after them | `merge1` to `merge6`, `merge-history`, `merge_exe`, `merge_renames`, `merge_renames_2`, `merge_warn` |
 
96 | Git export and import, bundles, patches, ZIP and tarball archives | `roundtrip` |
97 | Diffs and deltas | `delta1`, `diff` |
98 | Settings | `settings`, `settings-repo`, `set-manifest` |
99 | Wiki, attachments and unversioned files | `wiki`, `unversioned` |
100 | TH1 scripting | `th1`, `th1-docs`, `th1-hooks`, `th1-repo`, `th1-taint`, `th1-tcl` |
101
102 DDED test/powerloss.test
103 DDED tools/powerloss/README-POWERLOSS.md
104 DDED tools/powerloss/powerloss.c
105 DDED tools/powerloss/powerloss.sh
--- test/README.md
+++ test/README.md
@@ -1,11 +1,23 @@
1 # Fossil test suite
2
3 Test a given fossil binary for correct behaviour, either explicitly or in some
4 cases computed from the binary in question and the OS context it is running on.
5
6 This is an extensible test suite written in Tcl, where a runner executes all
7 the test files it finds in the test/ directory. Tests do not necessarily have
8 to pass, because the optional status *knownBug* constrains a test to merely
9 report a bug that hasn't yet been fixed. knownBug enables a useful pattern,
10 where tests are written first and the code is improved to reduce the knownBug
11 count to zero over time.
12
13 Some of the tests derive their cases and expecations (even some knownBugs) at
14 runtime by examining the running system and its configuration; many others have
15 test cases hardcoded. Other tests check for particular platforms (eg
16 `is_windows`) but we wish to keep that to a minimum because of the myriad of
17 different system configurations that exist within any given operating system
18 platform.
19
20 ## Running the tests
21
22 From a build directory:
23
@@ -32,14 +44,14 @@
44 * `-prot` also writes the output to the file `prot`.
45 * `-trials N` sets how many random trials fuzz tests (delta1, merge2, …)
46 run per input kind. The default is 20 (5 for expensive `large` /
47 `repeats` inputs). Use `-trials 100` for the historical full fuzz.
48 This flag is only the fuzz loop count; it does not select
49 `-assurance` cases.
50 * `-assurance smoke|ci|stress` selects how thoroughly the tests run.
51 The default is `smoke`, which skips `powerloss`. It also sets the
52 cases that `unicode-pathnames` and `utf` run:
53 - `unicode-pathnames`: `smoke` is one pair per fold-behavior class;
54 `ci` is the full hand-written lists; `stress` adds generated pairs.
55 At startup the harness classifies the temporary filesystem once
56 (ASCII case, NFC/NFD, and sharp-s versus `ss`). Predictions use
57 that classification with Fossil's `case-sensitive` setting
@@ -50,40 +62,46 @@
62 for both yes and no.
63 Unmet predictions fail the run.
64
65 `make test TESTFLAGS="-quiet update"` passes options and names via `make`.
66
67 Assurance recipes:
68
69 ```sh
70 make test # smoke (default)
71 make test TESTFLAGS="-assurance ci" # full current coverage
72 make test TESTFLAGS="-assurance stress" # ci plus generated cases
73 ```
74
75 `tester.tcl` exits with status 0 when all tests pass, 1 when one or more tests
76 fail. Failed tests are reported with what it expected vs what it got. The
77 summary lists skipped files with a reason, and all known bugs reported as
78 `FAILED (knownBug)`. Skips and known bugs do not change the exit status unless
79 `-strict` is given.
80
81 A new test should only require adding another `.test` file.
82
83 ## Requirements
84
85 * Tcl 8.6 or later, we also test with Tcl 9.0 which is now common. `configure` finds `tclsh`, and `make test` fails if it finds none.
86 * A writable temporary directory, from `TMPDIR`, `TEMP` or `TMP`, falling back to `/tmp`. All writes are made to the temporary directory, except with `-prot`
87 which writes a session log to wherever it was started from.
88 * `src/` which must be at the same level in the same directory as `test/`, reflecting the source tree layout. The tests (at least) `settings.test` and `settings-repo.test` need the source to do their job.
89
90 The following tests are skipped when their requirements are missing:
91
92 | Needs | Test files |
93 | --- | --- |
94 | a TCP connection over the loopback interface | `unversioned`, and the HTTP clone in `powerloss` |
95 | `-assurance ci` or `stress` | `powerloss` |
96 | a C compiler (`cc`, or `CC`), `LD_PRELOAD`, `tools/powerloss/powerloss.c` from the source tree, and a Fossil that isn't statically linked | `powerloss` |
97 | `configure --json` | `json` |
98 | `configure --with-th1-docs` | `th1-docs` |
99 | `configure --with-th1-hooks` | `th1-hooks` |
100 | `configure --with-tcl` | `th1-tcl` |
101
102 [`tools/powerloss/README-POWERLOSS.md`](../tools/powerloss/README-POWERLOSS.md) describes the `powerloss` library dependency.
103
104 None of the tests need network access. That doesn't mean all network-related tests will work, because some isolated environments don't even have loopback and
105 the test suite detects this.
106
107 ## Coverage
@@ -91,10 +109,11 @@
109 | Area | Test files |
110 | --- | --- |
111 | Check-ins and the working tree | `amend`, `clean`, `commit-warning`, `mv-rm`, `revert`, `stash`, `symlinks`, `unicode-pathnames`, `update` |
112 | Branches and tags | `branch-tag` |
113 | Merges, cherrypicks, backouts, and annotate and blame after them | `merge1` to `merge6`, `merge-history`, `merge_exe`, `merge_renames`, `merge_renames_2`, `merge_warn` |
114 | Commands interrupted by a power loss or a killed process | `powerloss` |
115 | Git export and import, bundles, patches, ZIP and tarball archives | `roundtrip` |
116 | Diffs and deltas | `delta1`, `diff` |
117 | Settings | `settings`, `settings-repo`, `set-manifest` |
118 | Wiki, attachments and unversioned files | `wiki`, `unversioned` |
119 | TH1 scripting | `th1`, `th1-docs`, `th1-hooks`, `th1-repo`, `th1-taint`, `th1-tcl` |
120
121 DDED test/powerloss.test
122 DDED tools/powerloss/README-POWERLOSS.md
123 DDED tools/powerloss/powerloss.c
124 DDED tools/powerloss/powerloss.sh
--- a/test/powerloss.test
+++ b/test/powerloss.test
@@ -0,0 +1,783 @@
1
+#
2
+# Tests that a fossil command interrupted by a power loss or a killed
3
+# process leaves repositories and check-outs that fossil can use, and
4
+# does not lose the user's work.
5
+#
6
+# tools/powerloss/powerloss.c is a library that fossil loads with
7
+# LD_PRELOAD. It stops the command at its Nth stop point, and leaves the
8
+# repository and check-out database files as a power loss or a killed
9
+# process would at that moment. tools/powerloss/README-POWERLOSS.md
10
+# describes it. For each command, and each of its stop points in turn,
11
+# these tests run the command from a fresh copy of the files, stop it
12
+# there, and check what the user would find. Each check is reported
13
+# once, with the stop points where it failed.
14
+#
15
+# The tests run for a repository in DELETE mode, Fossil's default, and in
16
+# WAL mode, except the clones, which make a repository in DELETE mode.
17
+# With a WAL repository, SQLite commits the repository and the check-out
18
+# database one after the other, so an interrupted command can leave the
19
+# check-out database one check-in behind the repository, which "fossil
20
+# update" repairs, or ahead of it, where the check-out can't be used
21
+# until its database is deleted and it is opened again.
22
+#
23
+
24
+require_no_open_checkout
25
+
26
+if {[test_assurance] eq "smoke"} {
27
+ test_skip "powerloss runs only with -assurance ci or stress"
28
+}
29
+if {$::tcl_platform(os) ni {Linux FreeBSD NetBSD OpenBSD DragonFly}} {
30
+ test_skip "the power loss library needs LD_PRELOAD, which\
31
+$::tcl_platform(os) does not have"
32
+}
33
+set shimSource [file join $::testfiledir .. tools powerloss powerloss.c]
34
+if {![file exists $shimSource]} {
35
+ test_skip "the source tree has no tools/powerloss/powerloss.c"
36
+}
37
+set workDir [test_setup ""]
38
+set cc [expr {[info exists ::env(CC)] ? $::env(CC) : ""}]
39
+if {$cc eq ""} {set cc cc}
40
+set shim [file join $workDir powerloss.so]
41
+if {[catch {exec {*}$cc -shared -fPIC -o $shim $shimSource} err] &&
42
+ [catch {exec {*}$cc -shared -fPIC -o $shim $shimSource -ldl} err]} {
43
+ test_skip "$cc cannot build tools/powerloss/powerloss.c: $err"
44
+}
45
+
46
+# Runs fossil with ARGS in directory DIR, with the NAME=VALUE settings of
47
+# the list ENV added to its environment, and returns a list of its exit
48
+# status and its output. A stopped command exits with status 77.
49
+#
50
+proc pl_exec {env dir args} {
51
+ protOut [list fossil {*}$args]
52
+ set saved [pwd]
53
+ cd $dir
54
+ set rc [catch {
55
+ exec env {*}$env $::fossilexe {*}$args << "" 2>@1
56
+ } result options]
57
+ cd $saved
58
+ set status 0
59
+ if {$rc} {
60
+ set status [lindex [dict get $options -errorcode] 2]
61
+ }
62
+ return [list $status [string trim $result]]
63
+}
64
+
65
+# Runs fossil without the power loss library, for set-up and checks.
66
+#
67
+proc pl_fossil {dir args} {
68
+ return [pl_exec {} $dir {*}$args]
69
+}
70
+
71
+# Returns what fossil's sqlite3 command prints for SQL on database FILE,
72
+# which is the error message if the SQL fails.
73
+#
74
+proc pl_sql {file sql} {
75
+ return [lindex [pl_fossil . sqlite3 --no-repository -list $file $sql] 1]
76
+}
77
+
78
+# Runs a fossil command that builds a template. A failure is an error.
79
+#
80
+proc pl_setup {dir args} {
81
+ set r [pl_fossil $dir {*}$args]
82
+ if {[lindex $r 0] != 0} {
83
+ error "fossil $args: [lindex $r 1]"
84
+ }
85
+}
86
+
87
+# Returns a list of two lines for repository REPO: the hashes, in order,
88
+# of its artifacts that are neither phantoms nor private, and of its
89
+# check-ins that are not private.
90
+#
91
+proc pl_content {repo} {
92
+ return [split [pl_sql $repo "SELECT 'artifacts', group_concat(uuid, ' ')\
93
+ FROM (SELECT uuid FROM blob WHERE size>=0 AND rid NOT IN private\
94
+ ORDER BY uuid);\
95
+ SELECT 'check-ins', group_concat(uuid, ' ')\
96
+ FROM (SELECT uuid FROM blob JOIN event ON objid=rid\
97
+ WHERE type='ci' AND rid NOT IN private ORDER BY uuid)"] \n]
98
+}
99
+
100
+# SQL for the record ID of the latest check-in in a repository.
101
+#
102
+set plTipSql "SELECT objid FROM event WHERE type='ci'\
103
+ ORDER BY mtime DESC, objid DESC LIMIT 1"
104
+
105
+# Returns the record ID of the latest check-in in repository REPO.
106
+#
107
+proc pl_tip {repo} {
108
+ return [pl_sql $repo $::plTipSql]
109
+}
110
+
111
+# Returns the number of parents of the latest check-in in repository REPO.
112
+#
113
+proc pl_tip_parents {repo} {
114
+ return [pl_sql $repo "SELECT count(*) FROM plink WHERE cid=($::plTipSql)"]
115
+}
116
+
117
+# Returns the number of check-ins in repository REPO.
118
+#
119
+proc pl_checkins {repo} {
120
+ return [pl_sql $repo "SELECT count(*) FROM event WHERE type='ci'"]
121
+}
122
+
123
+# Makes WORK/template/r.fossil, a repository in journal mode JOURNAL
124
+# with one check-in of a.txt, b.txt and c.txt, and its check-out
125
+# WORK/template/ck, and returns the check-out's directory.
126
+#
127
+proc pl_template_base {work journal} {
128
+ set run [file join $work template]
129
+ set ck [file join $run ck]
130
+ file delete -force $run
131
+ file mkdir $ck
132
+ pl_setup $run new r.fossil
133
+ if {$journal eq "wal"} {
134
+ pl_setup $run rebuild --wal r.fossil
135
+ }
136
+ pl_setup $ck open ../r.fossil
137
+ write_file [file join $ck a.txt] "one\ntwo\nthree\n"
138
+ write_file [file join $ck b.txt] "bee\n"
139
+ write_file [file join $ck c.txt] "sea\n"
140
+ pl_setup $ck add a.txt b.txt c.txt
141
+ pl_setup $ck commit -m one
142
+ return $ck
143
+}
144
+
145
+# In the check-out, a.txt is edited, d.txt added, b.txt removed and
146
+# c.txt renamed to e.txt.
147
+#
148
+proc pl_template_commit {work journal} {
149
+ set ck [pl_template_base $work $journal]
150
+ write_file [file join $ck a.txt] "second version\n"
151
+ write_file [file join $ck d.txt] "new\n"
152
+ pl_setup $ck add d.txt
153
+ pl_setup $ck rm b.txt
154
+ pl_setup $ck mv --hard c.txt e.txt
155
+}
156
+
157
+# Branch "side" edits b.txt and adds f.txt, trunk edits a.txt, and the
158
+# check-out is of trunk.
159
+#
160
+proc pl_template_merge {work journal} {
161
+ set ck [pl_template_base $work $journal]
162
+ write_file [file join $ck b.txt] "side\n"
163
+ write_file [file join $ck f.txt] "side file\n"
164
+ pl_setup $ck add f.txt
165
+ pl_setup $ck commit -m side --branch side
166
+ pl_setup $ck update trunk
167
+ write_file [file join $ck a.txt] "trunk\n"
168
+ pl_setup $ck commit -m two
169
+}
170
+
171
+# The check-out of the merge template has merged "side".
172
+#
173
+proc pl_template_commit_merge {work journal} {
174
+ pl_template_merge $work $journal
175
+ pl_setup [file join $work template ck] merge side
176
+}
177
+
178
+# The merge of the commit_merge template is committed.
179
+#
180
+proc pl_template_merged {work journal} {
181
+ pl_template_commit_merge $work $journal
182
+ pl_setup [file join $work template ck] commit -m merged
183
+}
184
+
185
+# The merged template, made in an earlier second than the first run.
186
+# "fossil rebuild" writes the time in seconds to config rows, and SQLite
187
+# skips the page if the time is the same as when the template was made.
188
+#
189
+proc pl_template_rebuild {work journal} {
190
+ pl_template_merged $work $journal
191
+ set made [clock seconds]
192
+ while {[clock seconds] == $made} {after 50}
193
+}
194
+
195
+# WORK/source.fossil, outside the files that the power loss library
196
+# tracks, is a copy of the repository with two more check-ins.
197
+#
198
+proc pl_template_pull {work journal} {
199
+ pl_template_base $work $journal
200
+ set source [file join $work source.fossil]
201
+ file copy [file join $work template r.fossil] $source
202
+ set ck [file join $work source-ck]
203
+ file mkdir $ck
204
+ pl_setup $ck open $source
205
+ write_file [file join $ck a.txt] "pulled\n"
206
+ pl_setup $ck commit -m pulled
207
+ write_file [file join $ck g.txt] "new in source\n"
208
+ pl_setup $ck add g.txt
209
+ pl_setup $ck commit -m "add g.txt"
210
+ pl_setup $ck close
211
+ file delete -force $ck
212
+}
213
+
214
+# WORK/template/l.fossil is a clone of r.fossil in journal mode JOURNAL,
215
+# and the check-out is of l.fossil, with two check-ins that r.fossil
216
+# lacks.
217
+#
218
+proc pl_template_push {work journal} {
219
+ set ck [pl_template_base $work $journal]
220
+ set run [file join $work template]
221
+ pl_setup $ck close
222
+ file delete -force $ck
223
+ file mkdir $ck
224
+ pl_setup $run clone r.fossil l.fossil
225
+ if {$journal eq "wal"} {
226
+ pl_setup $run rebuild --wal l.fossil
227
+ }
228
+ pl_setup $ck open ../l.fossil
229
+ pl_setup $ck settings autosync off
230
+ write_file [file join $ck a.txt] "pushed\n"
231
+ pl_setup $ck commit -m pushed
232
+ write_file [file join $ck g.txt] "new in clone\n"
233
+ pl_setup $ck add g.txt
234
+ pl_setup $ck commit -m "add g.txt"
235
+}
236
+
237
+# The second check-in changes the first line of a.txt, adds d.txt,
238
+# removes b.txt and renames c.txt to e.txt. The check-out is at the
239
+# first check-in, and the user has added a line to a.txt.
240
+#
241
+proc pl_template_update {work journal} {
242
+ set ck [pl_template_base $work $journal]
243
+ write_file [file join $ck a.txt] "ONE TWO\ntwo\nthree\n"
244
+ write_file [file join $ck d.txt] "new\n"
245
+ pl_setup $ck add d.txt
246
+ pl_setup $ck rm --hard b.txt
247
+ pl_setup $ck mv --hard c.txt e.txt
248
+ pl_setup $ck commit -m two
249
+ pl_setup $ck update prev
250
+ write_file [file join $ck a.txt] "one\ntwo\nthree\nlocal\n"
251
+}
252
+
253
+# The user has added a line to a.txt.
254
+#
255
+proc pl_template_edit {work journal} {
256
+ set ck [pl_template_base $work $journal]
257
+ write_file [file join $ck a.txt] "one\ntwo\nthree\nlocal\n"
258
+}
259
+
260
+# The user's edit to a.txt is in the stash.
261
+#
262
+proc pl_template_stash {work journal} {
263
+ pl_template_edit $work $journal
264
+ pl_setup [file join $work template ck] stash save -m local
265
+}
266
+
267
+# The user's edit to a.txt is reverted, and "fossil undo" can restore it.
268
+#
269
+proc pl_template_reverted {work journal} {
270
+ pl_template_edit $work $journal
271
+ pl_setup [file join $work template ck] revert
272
+}
273
+
274
+# The check-out directory is empty.
275
+#
276
+proc pl_template_open {work journal} {
277
+ set ck [pl_template_base $work $journal]
278
+ pl_setup $ck close
279
+ file delete -force $ck
280
+ file mkdir $ck
281
+}
282
+
283
+# WORK/source.fossil, outside the files that the power loss library
284
+# tracks, has the check-ins of the merged template and a private
285
+# check-in. WORK/template is empty.
286
+#
287
+proc pl_template_clone {work journal} {
288
+ pl_template_merged $work $journal
289
+ set ck [file join $work template ck]
290
+ write_file [file join $ck a.txt] "secret\n"
291
+ pl_setup $ck commit -m secret --branch hidden --private
292
+ pl_setup $ck close
293
+ file rename -force [file join $work template r.fossil] \
294
+ [file join $work source.fossil]
295
+ file delete -force [file join $work template]
296
+ file mkdir [file join $work template]
297
+}
298
+
299
+# Copies WORK/template to WORK/run and runs the fossil command CMD in
300
+# directory DIR of the copy. powerloss.so stops the command at stop
301
+# point AT, or never if AT is 0, in MODE, which is "power" or "kill".
302
+# Returns the stop points that powerloss.so logged, and sets ::plRun to
303
+# fossil's exit status and output.
304
+#
305
+proc pl_run {work dir cmd at mode} {
306
+ set run [file join $work run]
307
+ set log [file join $work log]
308
+ file delete -force $run [file join $work shadow] $log
309
+ file copy [file join $work template] $run
310
+ set preload $::shim
311
+ if {[info exists ::env(LD_PRELOAD)]} {
312
+ append preload : $::env(LD_PRELOAD)
313
+ }
314
+ set ::plRun [pl_exec [list STOP_DIR=$work STOP_AT=$at STOP_MODE=$mode \
315
+ LD_PRELOAD=$preload] [file join $run $dir] {*}$cmd]
316
+ if {![file exists $log]} {return {}}
317
+ return [split [string trim [read_file $log]] \n]
318
+}
319
+
320
+# Checks that the last pl_run stopped where it was told to. STOPPED is
321
+# the stop points that run logged, AT is the stop point it was given,
322
+# and POINT is the log line for AT from the counting run. Returns
323
+# "stopped", or else what was seen. A run that does not stop would pass
324
+# every other check, because it leaves the files of a finished command.
325
+#
326
+# The stop point must be logged, and the process that logged it must not
327
+# have logged anything after it. In power mode the other processes must
328
+# not have logged anything after it either.
329
+#
330
+# When one process logged every stop point, the stop point must also be
331
+# the same call on the same file as in the counting run, and the command
332
+# must exit with status 77. SQLite gives a super-journal a random name,
333
+# which differs from run to run, so the end of such a name is not
334
+# compared.
335
+#
336
+# When several processes logged stop points, their order can differ from
337
+# one run to the next, and the process that stopped may be a child, whose
338
+# parent can still succeed: "fossil push" exits with status 0 when
339
+# "fossil http" is killed in its second transaction. So the call, the
340
+# file and the exit status are not compared.
341
+#
342
+proc pl_stop_seen {stopped at point mode} {
343
+ set status [lindex $::plRun 0]
344
+ set last [lindex $stopped [expr {$at-1}]]
345
+ set later [lrange $stopped $at end]
346
+ if {$mode eq "kill"} {
347
+ set later [lsearch -all -inline -exact -index 3 $later [lindex $last 3]]
348
+ }
349
+ if {$last eq "" || [llength $later] > 0} {
350
+ return "[llength $stopped] stop points logged, exit status $status"
351
+ }
352
+ if {[llength [lsort -unique [lmap line $stopped {lindex $line 3}]]] > 1} {
353
+ return stopped
354
+ }
355
+ set seen [regsub -- {-mj[0-9A-F]+$} [lrange $last 1 2] -mj]
356
+ set wanted [regsub -- {-mj[0-9A-F]+$} [lrange $point 1 2] -mj]
357
+ if {$seen ne $wanted} {
358
+ return "stop point $at was [lrange $last 1 2]"
359
+ }
360
+ if {$status != 77} {
361
+ return "exit status $status"
362
+ }
363
+ return stopped
364
+}
365
+
366
+# Records the result of the check CHECK at the current stop point,
367
+# ::plPoint, of the run ::plName. pl_report reports each check once,
368
+# with the stop points where it failed. With "knownBug" in CONSTRAINTS,
369
+# a failure at this stop point is a known bug. ::plResults has two lists
370
+# for each check, the failures that are known bugs and those that are
371
+# not. A failure is its stop point and the expected and actual values.
372
+#
373
+proc pl_expect {check actual expected {constraints ""}} {
374
+ set key $::plName-$check
375
+ if {![dict exists $::plResults $key]} {
376
+ dict set ::plResults $key {marked 0 failed {} known {}}
377
+ }
378
+ set kind failed
379
+ if {"knownBug" in $constraints} {
380
+ set kind known
381
+ dict set ::plResults $key marked 1
382
+ }
383
+ if {$actual ne $expected} {
384
+ set failures [dict get $::plResults $key $kind]
385
+ lappend failures [list $::plPoint $expected $actual]
386
+ dict set ::plResults $key $kind $failures
387
+ }
388
+}
389
+
390
+# Reports each check recorded since the last report as one test. The
391
+# test fails with the stop points where the check failed, and the
392
+# expected and actual values at the first of them. The failure is a
393
+# known bug if it is one at every stop point where the check failed.
394
+#
395
+proc pl_report {} {
396
+ dict for {key result} $::plResults {
397
+ set failures [dict get $result failed]
398
+ set isKnown [expr {[dict get $result marked] && [llength $failures] == 0}]
399
+ if {$isKnown} {set failures [dict get $result known]}
400
+ set actual ""
401
+ if {[llength $failures] > 0} {
402
+ set points [lmap failure $failures {lindex $failure 0}]
403
+ lassign [lindex $failures 0] at expected got
404
+ set actual "stop points $points; at $at, expected \"$expected\",\
405
+got \"$got\""
406
+ }
407
+ test_eq $key $actual "" [expr {$isKnown ? "knownBug" : ""}]
408
+ }
409
+ set ::plResults [dict create]
410
+}
411
+set plResults [dict create]
412
+
413
+# Checks that the repository and check-out databases of WORK/run pass
414
+# PRAGMA integrity_check, that the check-out database does not record a
415
+# check-in missing from the repository, and that "fossil status" works.
416
+# Returns 1 when "fossil status" works. CONSTRAINTS apply to the check
417
+# that the check-out is not ahead of the repository, and to "fossil
418
+# status" where it is ahead.
419
+#
420
+proc pl_check_databases {work {constraints ""}} {
421
+ set run [file join $work run]
422
+ set ck [file join $run ck]
423
+ set found [split [pl_sql [file join $run r.fossil] \
424
+ "ATTACH '[file join $ck .fslckout]' AS ck;\
425
+ SELECT count(*) FROM blob WHERE rid=\
426
+ (SELECT 0+value FROM ck.vvar WHERE name='checkout');\
427
+ PRAGMA main.integrity_check; PRAGMA ck.integrity_check"] \n]
428
+ pl_expect integrity [lrange $found 1 end] {ok ok}
429
+ set ahead [expr {[lindex $found 0] != 1}]
430
+ pl_expect not-ahead [lindex $found 0] 1 $constraints
431
+ set r [pl_fossil $ck status]
432
+ pl_expect status [lindex $r 0] 0 [expr {$ahead ? $constraints : ""}]
433
+ return [expr {[lindex $r 0] == 0}]
434
+}
435
+
436
+# Checks that repository REPO has the artifacts and check-ins of
437
+# repository WANTED. CONSTRAINTS apply to the check of the check-ins
438
+# where REPO has none.
439
+#
440
+proc pl_expect_artifacts {repo wanted {constraints ""}} {
441
+ lassign [pl_content $repo] artifacts checkins
442
+ lassign [pl_content $wanted] wantedArtifacts wantedCheckins
443
+ if {$checkins ne "check-ins|"} {set constraints ""}
444
+ pl_expect artifacts $artifacts $wantedArtifacts
445
+ pl_expect checkins $checkins $wantedCheckins $constraints
446
+}
447
+
448
+# Returns "knownBug" for a WAL repository stopped by a power loss, which
449
+# is where a stopped commit can leave a check-out that cannot be used, and
450
+# "" otherwise. A power loss just after the check-out database commits
451
+# loses the repository's unsynced commit, which leaves the check-out
452
+# ahead of the repository.
453
+#
454
+proc pl_wal_commit_bug {} {
455
+ set lost [expr {$::plJournal eq "wal" && $::plMode eq "power"}]
456
+ return [expr {$lost ? "knownBug" : ""}]
457
+}
458
+
459
+# Finishes the check-in that a stopped commit was making, as the user
460
+# would: "fossil update", then "fossil commit" if changes are pending.
461
+# Returns the changes that were pending.
462
+#
463
+proc pl_finish_commit {ck} {
464
+ pl_fossil $ck update
465
+ set pending [lindex [pl_fossil $ck changes] 1]
466
+ if {$pending ne ""} {
467
+ pl_fossil $ck commit -m retry
468
+ }
469
+ return $pending
470
+}
471
+
472
+# The databases are usable, and once the user finishes the check-in, the
473
+# latest check-in has the files the user committed, and the repository
474
+# has one new check-in.
475
+#
476
+proc pl_check_commit {work} {
477
+ set ck [file join $work run ck]
478
+ if {![pl_check_databases $work [pl_wal_commit_bug]]} return
479
+ pl_finish_commit $ck
480
+ pl_expect checkin-count [pl_checkins [file join $work run r.fossil]] 3
481
+ pl_expect tip-files [lindex [pl_fossil $ck ls -r tip] 1] \
482
+ "a.txt\nd.txt\ne.txt"
483
+ pl_expect content [lindex [pl_fossil $ck cat a.txt -r tip] 1] \
484
+ "second version"
485
+}
486
+
487
+# The same as pl_check_commit, and the check-in has both parents.
488
+#
489
+proc pl_check_commit_merge {work} {
490
+ set ck [file join $work run ck]
491
+ if {![pl_check_databases $work [pl_wal_commit_bug]]} return
492
+ # Where the repository has the merge check-in and the check-out lacks
493
+ # it, "fossil update" leaves the merge pending, and the next commit
494
+ # checks in the same merge again.
495
+ set remerged [regexp {^MERGED_WITH \S+$} [pl_finish_commit $ck]]
496
+ pl_expect checkin-count [pl_checkins [file join $work run r.fossil]] 5 \
497
+ [expr {$remerged ? "knownBug" : ""}]
498
+ pl_expect parents [pl_tip_parents [file join $work run r.fossil]] 2
499
+ pl_expect content \
500
+ [lindex [pl_fossil $ck cat a.txt -r tip] 1]/[lindex \
501
+ [pl_fossil $ck cat b.txt -r tip] 1] trunk/side
502
+}
503
+
504
+# Checks the files in check-out CK against the list EXPECTED. A command
505
+# that follows an interrupted one finds the files that the interrupted
506
+# command wrote, and backs each one up as NAME-original. That is a known
507
+# bug, which has its own check.
508
+#
509
+proc pl_expect_files {ck expected} {
510
+ set files [lsort [glob -nocomplain -tails -directory $ck *]]
511
+ pl_expect backups [lsearch -all -inline -glob $files *-original] {} knownBug
512
+ pl_expect files [lsearch -all -inline -not -glob $files *-original] $expected
513
+}
514
+
515
+# The databases are usable, and after "fossil update" the check-out is at
516
+# the latest check-in, with the user's edit merged into a.txt.
517
+#
518
+proc pl_check_update {work} {
519
+ set ck [file join $work run ck]
520
+ if {![pl_check_databases $work]} return
521
+ pl_expect update [lindex [pl_fossil $ck update] 0] 0
522
+ set rid [pl_sql [file join $ck .fslckout] \
523
+ "SELECT value FROM vvar WHERE name='checkout'"]
524
+ pl_expect at-tip $rid [pl_tip [file join $work run r.fossil]]
525
+ pl_expect_files $ck {a.txt d.txt e.txt}
526
+ pl_expect content [read_file [file join $ck a.txt]] \
527
+ "ONE TWO\ntwo\nthree\nlocal\n"
528
+}
529
+
530
+# The databases are usable, and after "fossil merge" again if the merge
531
+# is not pending, the check-out has the merged files and nothing else,
532
+# and the commit has both parents.
533
+#
534
+proc pl_check_merge {work} {
535
+ set ck [file join $work run ck]
536
+ if {![pl_check_databases $work]} return
537
+ set pending [pl_sql [file join $ck .fslckout] "SELECT count(*) FROM vmerge"]
538
+ if {$pending == 0} {
539
+ pl_expect merge [lindex [pl_fossil $ck merge side] 0] 0
540
+ }
541
+ pl_expect_files $ck {a.txt b.txt c.txt f.txt}
542
+ pl_expect content [read_file [file join $ck a.txt]]/[read_file \
543
+ [file join $ck b.txt]]/[read_file [file join $ck f.txt]] \
544
+ "trunk\n/side\n/side file\n"
545
+ pl_fossil $ck commit -m merged
546
+ pl_expect parents [pl_tip_parents [file join $work run r.fossil]] 2
547
+}
548
+
549
+# The databases are usable, and after "fossil pull" again the repository
550
+# has the artifacts and check-ins of WORK/source.fossil.
551
+#
552
+proc pl_check_pull {work} {
553
+ set ck [file join $work run ck]
554
+ set repo [file join $work run r.fossil]
555
+ set source [file join $work source.fossil]
556
+ if {![pl_check_databases $work]} return
557
+ pl_expect pull [lindex [pl_fossil $ck pull $source] 0] 0
558
+ pl_expect_artifacts $repo $source
559
+ pl_fossil $ck update
560
+ pl_expect content [read_file [file join $ck a.txt]] "pulled\n"
561
+}
562
+
563
+# Both repositories pass PRAGMA integrity_check, and after "fossil push"
564
+# again r.fossil has the artifacts and check-ins of l.fossil.
565
+#
566
+proc pl_check_push {work} {
567
+ set ck [file join $work run ck]
568
+ set remote [file join $work run r.fossil]
569
+ set clone [file join $work run l.fossil]
570
+ pl_expect integrity [pl_sql $remote "ATTACH '$clone' AS l;\
571
+ PRAGMA main.integrity_check; PRAGMA l.integrity_check"] "ok\nok"
572
+ pl_expect push [lindex [pl_fossil $ck push ../r.fossil] 0] 0
573
+ pl_expect_artifacts $remote $clone
574
+}
575
+
576
+# For "stash save" and "stash pop": the user's edit is in a.txt or in
577
+# the stash, and is in a.txt after "fossil stash pop".
578
+#
579
+proc pl_check_stash {work} {
580
+ set ck [file join $work run ck]
581
+ if {![pl_check_databases $work]} return
582
+ if {[lindex [pl_fossil $ck stash list] 1] ne "empty stash"} {
583
+ pl_fossil $ck stash pop
584
+ }
585
+ pl_expect content [read_file [file join $ck a.txt]] \
586
+ "one\ntwo\nthree\nlocal\n"
587
+}
588
+
589
+# Returns the content of FILE, or "" if it does not exist.
590
+#
591
+proc pl_read {file} {
592
+ if {![file exists $file]} {return ""}
593
+ return [read_file $file]
594
+}
595
+
596
+# Checks that the user's edit to a.txt is in the file, or that "fossil
597
+# undo" puts it back. CONSTRAINTS apply where a.txt is left with the
598
+# content of the check-in.
599
+#
600
+proc pl_check_edit_kept {ck {constraints ""}} {
601
+ set edit "one\ntwo\nthree\nlocal\n"
602
+ if {[pl_read [file join $ck a.txt]] ne $edit} {
603
+ pl_fossil $ck undo
604
+ }
605
+ set found [pl_read [file join $ck a.txt]]
606
+ if {$found ne "one\ntwo\nthree\n"} {set constraints ""}
607
+ pl_expect edit $found $edit $constraints
608
+}
609
+
610
+# The databases are usable, and the edit is in a.txt or "fossil undo"
611
+# puts it back.
612
+#
613
+proc pl_check_revert {work} {
614
+ if {![pl_check_databases $work]} return
615
+ # A revert overwrites the files before it commits their undo
616
+ # information, so an interrupted revert loses the user's edits.
617
+ pl_check_edit_kept [file join $work run ck] knownBug
618
+}
619
+
620
+# The databases are usable, and the edit is in a.txt or "fossil undo"
621
+# again puts it back.
622
+#
623
+proc pl_check_undo {work} {
624
+ if {![pl_check_databases $work]} return
625
+ pl_check_edit_kept [file join $work run ck]
626
+}
627
+
628
+# The check-out database is missing or passes PRAGMA integrity_check,
629
+# and after "fossil open" again where "fossil status" fails, or "fossil
630
+# update" where it works, the check-out has every file of the check-in,
631
+# unchanged.
632
+#
633
+proc pl_check_open {work} {
634
+ set ck [file join $work run ck]
635
+ set ckout [file join $ck .fslckout]
636
+ if {[file exists $ckout]} {
637
+ pl_expect integrity [pl_sql $ckout {PRAGMA integrity_check}] ok
638
+ }
639
+ if {[lindex [pl_fossil $ck status] 0] == 0} {
640
+ pl_fossil $ck update
641
+ } else {
642
+ # An open interrupted before it records the name of the repository
643
+ # leaves a check-out database that every command rejects.
644
+ lassign [pl_fossil $ck open ../r.fossil] status output
645
+ set unnamed [string match "*unable to find the name of a repo*" $output]
646
+ pl_expect open $status 0 [expr {$unnamed ? "knownBug" : ""}]
647
+ if {$status != 0} return
648
+ }
649
+ pl_expect_files $ck {a.txt b.txt c.txt}
650
+ pl_expect changes [pl_fossil $ck changes] {0 {}}
651
+ pl_expect content [pl_read [file join $ck a.txt]] "one\ntwo\nthree\n"
652
+}
653
+
654
+# The databases are usable, and the repository has the same artifacts
655
+# and check-ins as before.
656
+#
657
+proc pl_check_rebuild {work} {
658
+ set repo [file join $work run r.fossil]
659
+ set original [file join $work template r.fossil]
660
+ if {![pl_check_databases $work]} return
661
+ pl_expect_artifacts $repo $original
662
+}
663
+
664
+# The new repository is missing, or fossil refuses to use it, or it has
665
+# every public artifact and check-in of the original and no private one.
666
+# An interrupted clone over a file: URL can leave the private content of
667
+# the original, and one over HTTP a repository without its check-ins.
668
+#
669
+proc pl_check_clone {work} {
670
+ set clone [file join $work run c.fossil]
671
+ set source [file join $work source.fossil]
672
+ if {![file exists $clone] ||
673
+ [lindex [pl_fossil [file join $work run] info -R $clone] 0] != 0} {
674
+ return
675
+ }
676
+ set found [split [pl_sql $clone "SELECT count(*) FROM private;\
677
+ PRAGMA integrity_check"] \n]
678
+ pl_expect integrity [lrange $found 1 end] ok
679
+ set http [expr {$::plTest eq "clone-http"}]
680
+ pl_expect private [lindex $found 0] 0 [expr {$http ? "" : "knownBug"}]
681
+ pl_expect_artifacts $clone $source [expr {$http ? "knownBug" : ""}]
682
+}
683
+
684
+# Runs TEST for a repository in journal mode JOURNAL, from the template
685
+# TEMPLATE, uninterrupted and then stopped at each stop point in each
686
+# mode, and reports each check of the procedure CHECK once for each mode.
687
+# The command CMD runs in directory DIR of the copy of the template. In
688
+# CMD, SOURCE stands for WORK/source.fossil and PORT for the port of a
689
+# server of it, which is started for a CMD that has PORT in it.
690
+#
691
+proc pl_test {test journal template dir check cmd} {
692
+ set ::plTest $test
693
+ set ::plJournal $journal
694
+ set work [file join $::workDir $test-$journal]
695
+ file mkdir $work
696
+ pl_template_$template $work $journal
697
+ set source [file join $work source.fossil]
698
+ set port ""
699
+ set server ""
700
+ if {[string match *PORT* $cmd]} {
701
+ set server [test_start_server $source stopArg]
702
+ set port [lindex $server 1]
703
+ }
704
+ try {
705
+ set cmd [lmap a $cmd {string map [list SOURCE $source PORT $port] $a}]
706
+ foreach mode {power kill} {
707
+ set ::plMode $mode
708
+ set ::plName powerloss-$test-$journal-$mode
709
+ set points [pl_run $work $dir $cmd 0 $mode]
710
+ test $::plName-points {[llength $points] > 0}
711
+ set ::plPoint none
712
+ $check $work
713
+ foreach point $points {
714
+ set at [lindex $point 0]
715
+ set stopped [pl_run $work $dir $cmd $at $mode]
716
+ protOut "$test stop point $at: [lrange $point 1 end]"
717
+ set ::plPoint $at
718
+ pl_expect stopped [pl_stop_seen $stopped $at $point $mode] stopped
719
+ $check $work
720
+ }
721
+ pl_report
722
+ }
723
+ } finally {
724
+ if {$server ne ""} {
725
+ test_stop_server $stopArg [lindex $server 0] [lindex $server 2]
726
+ }
727
+ file delete -force $work
728
+ }
729
+}
730
+
731
+# A fossil that is statically linked does not load the library.
732
+file mkdir [file join $workDir probe template]
733
+if {[pl_run [file join $workDir probe] . {new r.fossil} 0 power] eq ""} {
734
+ test_skip "LD_PRELOAD of powerloss.so has no effect on fossil,\
735
+which may be statically linked"
736
+}
737
+
738
+set env(FOSSIL_USER) tester
739
+# Each row is a test, its template, the directory the command runs in, its
740
+# check procedure, the journal modes it runs for, and the command. The
741
+# check procedures mark the known bugs.
742
+#
743
+foreach {test template dir check journals cmd} {
744
+ commit commit ck pl_check_commit {delete wal}
745
+ {commit -m two}
746
+ commit-merge commit_merge ck pl_check_commit_merge {delete wal}
747
+ {commit -m merged}
748
+ merge merge ck pl_check_merge {delete wal}
749
+ {merge side}
750
+ update update ck pl_check_update {delete wal}
751
+ {update}
752
+ stash-save edit ck pl_check_stash {delete wal}
753
+ {stash save -m local}
754
+ stash-pop stash ck pl_check_stash {delete wal}
755
+ {stash pop}
756
+ revert edit ck pl_check_revert {delete wal}
757
+ {revert}
758
+ undo reverted ck pl_check_undo {delete wal}
759
+ {undo}
760
+ open open ck pl_check_open {delete wal}
761
+ {open ../r.fossil}
762
+ rebuild rebuild ck pl_check_rebuild {delete wal}
763
+ {rebuild}
764
+ pull pull ck pl_check_pull {delete wal}
765
+ {pull SOURCE}
766
+ push push ck pl_check_push {delete wal}
767
+ {push ../r.fossil}
768
+ clone-file clone . pl_check_clone delete
769
+ {clone SOURCE c.fossil}
770
+ clone-http clone . pl_check_clone delete
771
+ {clone --proxy off http://127.0.0.1:PORT/ c.fossil}
772
+} {
773
+ if {[string match *PORT* $cmd] && ![loopback_available]} {
774
+ test_skip_part "powerloss-$test needs a loopback interface"
775
+ continue
776
+ }
777
+ foreach journal $journals {
778
+ pl_test $test $journal $template $dir $check $cmd
779
+ }
780
+}
781
+unset env(FOSSIL_USER)
782
+
783
+test_cleanup
--- a/test/powerloss.test
+++ b/test/powerloss.test
@@ -0,0 +1,783 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
--- a/test/powerloss.test
+++ b/test/powerloss.test
@@ -0,0 +1,783 @@
1 #
2 # Tests that a fossil command interrupted by a power loss or a killed
3 # process leaves repositories and check-outs that fossil can use, and
4 # does not lose the user's work.
5 #
6 # tools/powerloss/powerloss.c is a library that fossil loads with
7 # LD_PRELOAD. It stops the command at its Nth stop point, and leaves the
8 # repository and check-out database files as a power loss or a killed
9 # process would at that moment. tools/powerloss/README-POWERLOSS.md
10 # describes it. For each command, and each of its stop points in turn,
11 # these tests run the command from a fresh copy of the files, stop it
12 # there, and check what the user would find. Each check is reported
13 # once, with the stop points where it failed.
14 #
15 # The tests run for a repository in DELETE mode, Fossil's default, and in
16 # WAL mode, except the clones, which make a repository in DELETE mode.
17 # With a WAL repository, SQLite commits the repository and the check-out
18 # database one after the other, so an interrupted command can leave the
19 # check-out database one check-in behind the repository, which "fossil
20 # update" repairs, or ahead of it, where the check-out can't be used
21 # until its database is deleted and it is opened again.
22 #
23
24 require_no_open_checkout
25
26 if {[test_assurance] eq "smoke"} {
27 test_skip "powerloss runs only with -assurance ci or stress"
28 }
29 if {$::tcl_platform(os) ni {Linux FreeBSD NetBSD OpenBSD DragonFly}} {
30 test_skip "the power loss library needs LD_PRELOAD, which\
31 $::tcl_platform(os) does not have"
32 }
33 set shimSource [file join $::testfiledir .. tools powerloss powerloss.c]
34 if {![file exists $shimSource]} {
35 test_skip "the source tree has no tools/powerloss/powerloss.c"
36 }
37 set workDir [test_setup ""]
38 set cc [expr {[info exists ::env(CC)] ? $::env(CC) : ""}]
39 if {$cc eq ""} {set cc cc}
40 set shim [file join $workDir powerloss.so]
41 if {[catch {exec {*}$cc -shared -fPIC -o $shim $shimSource} err] &&
42 [catch {exec {*}$cc -shared -fPIC -o $shim $shimSource -ldl} err]} {
43 test_skip "$cc cannot build tools/powerloss/powerloss.c: $err"
44 }
45
46 # Runs fossil with ARGS in directory DIR, with the NAME=VALUE settings of
47 # the list ENV added to its environment, and returns a list of its exit
48 # status and its output. A stopped command exits with status 77.
49 #
50 proc pl_exec {env dir args} {
51 protOut [list fossil {*}$args]
52 set saved [pwd]
53 cd $dir
54 set rc [catch {
55 exec env {*}$env $::fossilexe {*}$args << "" 2>@1
56 } result options]
57 cd $saved
58 set status 0
59 if {$rc} {
60 set status [lindex [dict get $options -errorcode] 2]
61 }
62 return [list $status [string trim $result]]
63 }
64
65 # Runs fossil without the power loss library, for set-up and checks.
66 #
67 proc pl_fossil {dir args} {
68 return [pl_exec {} $dir {*}$args]
69 }
70
71 # Returns what fossil's sqlite3 command prints for SQL on database FILE,
72 # which is the error message if the SQL fails.
73 #
74 proc pl_sql {file sql} {
75 return [lindex [pl_fossil . sqlite3 --no-repository -list $file $sql] 1]
76 }
77
78 # Runs a fossil command that builds a template. A failure is an error.
79 #
80 proc pl_setup {dir args} {
81 set r [pl_fossil $dir {*}$args]
82 if {[lindex $r 0] != 0} {
83 error "fossil $args: [lindex $r 1]"
84 }
85 }
86
87 # Returns a list of two lines for repository REPO: the hashes, in order,
88 # of its artifacts that are neither phantoms nor private, and of its
89 # check-ins that are not private.
90 #
91 proc pl_content {repo} {
92 return [split [pl_sql $repo "SELECT 'artifacts', group_concat(uuid, ' ')\
93 FROM (SELECT uuid FROM blob WHERE size>=0 AND rid NOT IN private\
94 ORDER BY uuid);\
95 SELECT 'check-ins', group_concat(uuid, ' ')\
96 FROM (SELECT uuid FROM blob JOIN event ON objid=rid\
97 WHERE type='ci' AND rid NOT IN private ORDER BY uuid)"] \n]
98 }
99
100 # SQL for the record ID of the latest check-in in a repository.
101 #
102 set plTipSql "SELECT objid FROM event WHERE type='ci'\
103 ORDER BY mtime DESC, objid DESC LIMIT 1"
104
105 # Returns the record ID of the latest check-in in repository REPO.
106 #
107 proc pl_tip {repo} {
108 return [pl_sql $repo $::plTipSql]
109 }
110
111 # Returns the number of parents of the latest check-in in repository REPO.
112 #
113 proc pl_tip_parents {repo} {
114 return [pl_sql $repo "SELECT count(*) FROM plink WHERE cid=($::plTipSql)"]
115 }
116
117 # Returns the number of check-ins in repository REPO.
118 #
119 proc pl_checkins {repo} {
120 return [pl_sql $repo "SELECT count(*) FROM event WHERE type='ci'"]
121 }
122
123 # Makes WORK/template/r.fossil, a repository in journal mode JOURNAL
124 # with one check-in of a.txt, b.txt and c.txt, and its check-out
125 # WORK/template/ck, and returns the check-out's directory.
126 #
127 proc pl_template_base {work journal} {
128 set run [file join $work template]
129 set ck [file join $run ck]
130 file delete -force $run
131 file mkdir $ck
132 pl_setup $run new r.fossil
133 if {$journal eq "wal"} {
134 pl_setup $run rebuild --wal r.fossil
135 }
136 pl_setup $ck open ../r.fossil
137 write_file [file join $ck a.txt] "one\ntwo\nthree\n"
138 write_file [file join $ck b.txt] "bee\n"
139 write_file [file join $ck c.txt] "sea\n"
140 pl_setup $ck add a.txt b.txt c.txt
141 pl_setup $ck commit -m one
142 return $ck
143 }
144
145 # In the check-out, a.txt is edited, d.txt added, b.txt removed and
146 # c.txt renamed to e.txt.
147 #
148 proc pl_template_commit {work journal} {
149 set ck [pl_template_base $work $journal]
150 write_file [file join $ck a.txt] "second version\n"
151 write_file [file join $ck d.txt] "new\n"
152 pl_setup $ck add d.txt
153 pl_setup $ck rm b.txt
154 pl_setup $ck mv --hard c.txt e.txt
155 }
156
157 # Branch "side" edits b.txt and adds f.txt, trunk edits a.txt, and the
158 # check-out is of trunk.
159 #
160 proc pl_template_merge {work journal} {
161 set ck [pl_template_base $work $journal]
162 write_file [file join $ck b.txt] "side\n"
163 write_file [file join $ck f.txt] "side file\n"
164 pl_setup $ck add f.txt
165 pl_setup $ck commit -m side --branch side
166 pl_setup $ck update trunk
167 write_file [file join $ck a.txt] "trunk\n"
168 pl_setup $ck commit -m two
169 }
170
171 # The check-out of the merge template has merged "side".
172 #
173 proc pl_template_commit_merge {work journal} {
174 pl_template_merge $work $journal
175 pl_setup [file join $work template ck] merge side
176 }
177
178 # The merge of the commit_merge template is committed.
179 #
180 proc pl_template_merged {work journal} {
181 pl_template_commit_merge $work $journal
182 pl_setup [file join $work template ck] commit -m merged
183 }
184
185 # The merged template, made in an earlier second than the first run.
186 # "fossil rebuild" writes the time in seconds to config rows, and SQLite
187 # skips the page if the time is the same as when the template was made.
188 #
189 proc pl_template_rebuild {work journal} {
190 pl_template_merged $work $journal
191 set made [clock seconds]
192 while {[clock seconds] == $made} {after 50}
193 }
194
195 # WORK/source.fossil, outside the files that the power loss library
196 # tracks, is a copy of the repository with two more check-ins.
197 #
198 proc pl_template_pull {work journal} {
199 pl_template_base $work $journal
200 set source [file join $work source.fossil]
201 file copy [file join $work template r.fossil] $source
202 set ck [file join $work source-ck]
203 file mkdir $ck
204 pl_setup $ck open $source
205 write_file [file join $ck a.txt] "pulled\n"
206 pl_setup $ck commit -m pulled
207 write_file [file join $ck g.txt] "new in source\n"
208 pl_setup $ck add g.txt
209 pl_setup $ck commit -m "add g.txt"
210 pl_setup $ck close
211 file delete -force $ck
212 }
213
214 # WORK/template/l.fossil is a clone of r.fossil in journal mode JOURNAL,
215 # and the check-out is of l.fossil, with two check-ins that r.fossil
216 # lacks.
217 #
218 proc pl_template_push {work journal} {
219 set ck [pl_template_base $work $journal]
220 set run [file join $work template]
221 pl_setup $ck close
222 file delete -force $ck
223 file mkdir $ck
224 pl_setup $run clone r.fossil l.fossil
225 if {$journal eq "wal"} {
226 pl_setup $run rebuild --wal l.fossil
227 }
228 pl_setup $ck open ../l.fossil
229 pl_setup $ck settings autosync off
230 write_file [file join $ck a.txt] "pushed\n"
231 pl_setup $ck commit -m pushed
232 write_file [file join $ck g.txt] "new in clone\n"
233 pl_setup $ck add g.txt
234 pl_setup $ck commit -m "add g.txt"
235 }
236
237 # The second check-in changes the first line of a.txt, adds d.txt,
238 # removes b.txt and renames c.txt to e.txt. The check-out is at the
239 # first check-in, and the user has added a line to a.txt.
240 #
241 proc pl_template_update {work journal} {
242 set ck [pl_template_base $work $journal]
243 write_file [file join $ck a.txt] "ONE TWO\ntwo\nthree\n"
244 write_file [file join $ck d.txt] "new\n"
245 pl_setup $ck add d.txt
246 pl_setup $ck rm --hard b.txt
247 pl_setup $ck mv --hard c.txt e.txt
248 pl_setup $ck commit -m two
249 pl_setup $ck update prev
250 write_file [file join $ck a.txt] "one\ntwo\nthree\nlocal\n"
251 }
252
253 # The user has added a line to a.txt.
254 #
255 proc pl_template_edit {work journal} {
256 set ck [pl_template_base $work $journal]
257 write_file [file join $ck a.txt] "one\ntwo\nthree\nlocal\n"
258 }
259
260 # The user's edit to a.txt is in the stash.
261 #
262 proc pl_template_stash {work journal} {
263 pl_template_edit $work $journal
264 pl_setup [file join $work template ck] stash save -m local
265 }
266
267 # The user's edit to a.txt is reverted, and "fossil undo" can restore it.
268 #
269 proc pl_template_reverted {work journal} {
270 pl_template_edit $work $journal
271 pl_setup [file join $work template ck] revert
272 }
273
274 # The check-out directory is empty.
275 #
276 proc pl_template_open {work journal} {
277 set ck [pl_template_base $work $journal]
278 pl_setup $ck close
279 file delete -force $ck
280 file mkdir $ck
281 }
282
283 # WORK/source.fossil, outside the files that the power loss library
284 # tracks, has the check-ins of the merged template and a private
285 # check-in. WORK/template is empty.
286 #
287 proc pl_template_clone {work journal} {
288 pl_template_merged $work $journal
289 set ck [file join $work template ck]
290 write_file [file join $ck a.txt] "secret\n"
291 pl_setup $ck commit -m secret --branch hidden --private
292 pl_setup $ck close
293 file rename -force [file join $work template r.fossil] \
294 [file join $work source.fossil]
295 file delete -force [file join $work template]
296 file mkdir [file join $work template]
297 }
298
299 # Copies WORK/template to WORK/run and runs the fossil command CMD in
300 # directory DIR of the copy. powerloss.so stops the command at stop
301 # point AT, or never if AT is 0, in MODE, which is "power" or "kill".
302 # Returns the stop points that powerloss.so logged, and sets ::plRun to
303 # fossil's exit status and output.
304 #
305 proc pl_run {work dir cmd at mode} {
306 set run [file join $work run]
307 set log [file join $work log]
308 file delete -force $run [file join $work shadow] $log
309 file copy [file join $work template] $run
310 set preload $::shim
311 if {[info exists ::env(LD_PRELOAD)]} {
312 append preload : $::env(LD_PRELOAD)
313 }
314 set ::plRun [pl_exec [list STOP_DIR=$work STOP_AT=$at STOP_MODE=$mode \
315 LD_PRELOAD=$preload] [file join $run $dir] {*}$cmd]
316 if {![file exists $log]} {return {}}
317 return [split [string trim [read_file $log]] \n]
318 }
319
320 # Checks that the last pl_run stopped where it was told to. STOPPED is
321 # the stop points that run logged, AT is the stop point it was given,
322 # and POINT is the log line for AT from the counting run. Returns
323 # "stopped", or else what was seen. A run that does not stop would pass
324 # every other check, because it leaves the files of a finished command.
325 #
326 # The stop point must be logged, and the process that logged it must not
327 # have logged anything after it. In power mode the other processes must
328 # not have logged anything after it either.
329 #
330 # When one process logged every stop point, the stop point must also be
331 # the same call on the same file as in the counting run, and the command
332 # must exit with status 77. SQLite gives a super-journal a random name,
333 # which differs from run to run, so the end of such a name is not
334 # compared.
335 #
336 # When several processes logged stop points, their order can differ from
337 # one run to the next, and the process that stopped may be a child, whose
338 # parent can still succeed: "fossil push" exits with status 0 when
339 # "fossil http" is killed in its second transaction. So the call, the
340 # file and the exit status are not compared.
341 #
342 proc pl_stop_seen {stopped at point mode} {
343 set status [lindex $::plRun 0]
344 set last [lindex $stopped [expr {$at-1}]]
345 set later [lrange $stopped $at end]
346 if {$mode eq "kill"} {
347 set later [lsearch -all -inline -exact -index 3 $later [lindex $last 3]]
348 }
349 if {$last eq "" || [llength $later] > 0} {
350 return "[llength $stopped] stop points logged, exit status $status"
351 }
352 if {[llength [lsort -unique [lmap line $stopped {lindex $line 3}]]] > 1} {
353 return stopped
354 }
355 set seen [regsub -- {-mj[0-9A-F]+$} [lrange $last 1 2] -mj]
356 set wanted [regsub -- {-mj[0-9A-F]+$} [lrange $point 1 2] -mj]
357 if {$seen ne $wanted} {
358 return "stop point $at was [lrange $last 1 2]"
359 }
360 if {$status != 77} {
361 return "exit status $status"
362 }
363 return stopped
364 }
365
366 # Records the result of the check CHECK at the current stop point,
367 # ::plPoint, of the run ::plName. pl_report reports each check once,
368 # with the stop points where it failed. With "knownBug" in CONSTRAINTS,
369 # a failure at this stop point is a known bug. ::plResults has two lists
370 # for each check, the failures that are known bugs and those that are
371 # not. A failure is its stop point and the expected and actual values.
372 #
373 proc pl_expect {check actual expected {constraints ""}} {
374 set key $::plName-$check
375 if {![dict exists $::plResults $key]} {
376 dict set ::plResults $key {marked 0 failed {} known {}}
377 }
378 set kind failed
379 if {"knownBug" in $constraints} {
380 set kind known
381 dict set ::plResults $key marked 1
382 }
383 if {$actual ne $expected} {
384 set failures [dict get $::plResults $key $kind]
385 lappend failures [list $::plPoint $expected $actual]
386 dict set ::plResults $key $kind $failures
387 }
388 }
389
390 # Reports each check recorded since the last report as one test. The
391 # test fails with the stop points where the check failed, and the
392 # expected and actual values at the first of them. The failure is a
393 # known bug if it is one at every stop point where the check failed.
394 #
395 proc pl_report {} {
396 dict for {key result} $::plResults {
397 set failures [dict get $result failed]
398 set isKnown [expr {[dict get $result marked] && [llength $failures] == 0}]
399 if {$isKnown} {set failures [dict get $result known]}
400 set actual ""
401 if {[llength $failures] > 0} {
402 set points [lmap failure $failures {lindex $failure 0}]
403 lassign [lindex $failures 0] at expected got
404 set actual "stop points $points; at $at, expected \"$expected\",\
405 got \"$got\""
406 }
407 test_eq $key $actual "" [expr {$isKnown ? "knownBug" : ""}]
408 }
409 set ::plResults [dict create]
410 }
411 set plResults [dict create]
412
413 # Checks that the repository and check-out databases of WORK/run pass
414 # PRAGMA integrity_check, that the check-out database does not record a
415 # check-in missing from the repository, and that "fossil status" works.
416 # Returns 1 when "fossil status" works. CONSTRAINTS apply to the check
417 # that the check-out is not ahead of the repository, and to "fossil
418 # status" where it is ahead.
419 #
420 proc pl_check_databases {work {constraints ""}} {
421 set run [file join $work run]
422 set ck [file join $run ck]
423 set found [split [pl_sql [file join $run r.fossil] \
424 "ATTACH '[file join $ck .fslckout]' AS ck;\
425 SELECT count(*) FROM blob WHERE rid=\
426 (SELECT 0+value FROM ck.vvar WHERE name='checkout');\
427 PRAGMA main.integrity_check; PRAGMA ck.integrity_check"] \n]
428 pl_expect integrity [lrange $found 1 end] {ok ok}
429 set ahead [expr {[lindex $found 0] != 1}]
430 pl_expect not-ahead [lindex $found 0] 1 $constraints
431 set r [pl_fossil $ck status]
432 pl_expect status [lindex $r 0] 0 [expr {$ahead ? $constraints : ""}]
433 return [expr {[lindex $r 0] == 0}]
434 }
435
436 # Checks that repository REPO has the artifacts and check-ins of
437 # repository WANTED. CONSTRAINTS apply to the check of the check-ins
438 # where REPO has none.
439 #
440 proc pl_expect_artifacts {repo wanted {constraints ""}} {
441 lassign [pl_content $repo] artifacts checkins
442 lassign [pl_content $wanted] wantedArtifacts wantedCheckins
443 if {$checkins ne "check-ins|"} {set constraints ""}
444 pl_expect artifacts $artifacts $wantedArtifacts
445 pl_expect checkins $checkins $wantedCheckins $constraints
446 }
447
448 # Returns "knownBug" for a WAL repository stopped by a power loss, which
449 # is where a stopped commit can leave a check-out that cannot be used, and
450 # "" otherwise. A power loss just after the check-out database commits
451 # loses the repository's unsynced commit, which leaves the check-out
452 # ahead of the repository.
453 #
454 proc pl_wal_commit_bug {} {
455 set lost [expr {$::plJournal eq "wal" && $::plMode eq "power"}]
456 return [expr {$lost ? "knownBug" : ""}]
457 }
458
459 # Finishes the check-in that a stopped commit was making, as the user
460 # would: "fossil update", then "fossil commit" if changes are pending.
461 # Returns the changes that were pending.
462 #
463 proc pl_finish_commit {ck} {
464 pl_fossil $ck update
465 set pending [lindex [pl_fossil $ck changes] 1]
466 if {$pending ne ""} {
467 pl_fossil $ck commit -m retry
468 }
469 return $pending
470 }
471
472 # The databases are usable, and once the user finishes the check-in, the
473 # latest check-in has the files the user committed, and the repository
474 # has one new check-in.
475 #
476 proc pl_check_commit {work} {
477 set ck [file join $work run ck]
478 if {![pl_check_databases $work [pl_wal_commit_bug]]} return
479 pl_finish_commit $ck
480 pl_expect checkin-count [pl_checkins [file join $work run r.fossil]] 3
481 pl_expect tip-files [lindex [pl_fossil $ck ls -r tip] 1] \
482 "a.txt\nd.txt\ne.txt"
483 pl_expect content [lindex [pl_fossil $ck cat a.txt -r tip] 1] \
484 "second version"
485 }
486
487 # The same as pl_check_commit, and the check-in has both parents.
488 #
489 proc pl_check_commit_merge {work} {
490 set ck [file join $work run ck]
491 if {![pl_check_databases $work [pl_wal_commit_bug]]} return
492 # Where the repository has the merge check-in and the check-out lacks
493 # it, "fossil update" leaves the merge pending, and the next commit
494 # checks in the same merge again.
495 set remerged [regexp {^MERGED_WITH \S+$} [pl_finish_commit $ck]]
496 pl_expect checkin-count [pl_checkins [file join $work run r.fossil]] 5 \
497 [expr {$remerged ? "knownBug" : ""}]
498 pl_expect parents [pl_tip_parents [file join $work run r.fossil]] 2
499 pl_expect content \
500 [lindex [pl_fossil $ck cat a.txt -r tip] 1]/[lindex \
501 [pl_fossil $ck cat b.txt -r tip] 1] trunk/side
502 }
503
504 # Checks the files in check-out CK against the list EXPECTED. A command
505 # that follows an interrupted one finds the files that the interrupted
506 # command wrote, and backs each one up as NAME-original. That is a known
507 # bug, which has its own check.
508 #
509 proc pl_expect_files {ck expected} {
510 set files [lsort [glob -nocomplain -tails -directory $ck *]]
511 pl_expect backups [lsearch -all -inline -glob $files *-original] {} knownBug
512 pl_expect files [lsearch -all -inline -not -glob $files *-original] $expected
513 }
514
515 # The databases are usable, and after "fossil update" the check-out is at
516 # the latest check-in, with the user's edit merged into a.txt.
517 #
518 proc pl_check_update {work} {
519 set ck [file join $work run ck]
520 if {![pl_check_databases $work]} return
521 pl_expect update [lindex [pl_fossil $ck update] 0] 0
522 set rid [pl_sql [file join $ck .fslckout] \
523 "SELECT value FROM vvar WHERE name='checkout'"]
524 pl_expect at-tip $rid [pl_tip [file join $work run r.fossil]]
525 pl_expect_files $ck {a.txt d.txt e.txt}
526 pl_expect content [read_file [file join $ck a.txt]] \
527 "ONE TWO\ntwo\nthree\nlocal\n"
528 }
529
530 # The databases are usable, and after "fossil merge" again if the merge
531 # is not pending, the check-out has the merged files and nothing else,
532 # and the commit has both parents.
533 #
534 proc pl_check_merge {work} {
535 set ck [file join $work run ck]
536 if {![pl_check_databases $work]} return
537 set pending [pl_sql [file join $ck .fslckout] "SELECT count(*) FROM vmerge"]
538 if {$pending == 0} {
539 pl_expect merge [lindex [pl_fossil $ck merge side] 0] 0
540 }
541 pl_expect_files $ck {a.txt b.txt c.txt f.txt}
542 pl_expect content [read_file [file join $ck a.txt]]/[read_file \
543 [file join $ck b.txt]]/[read_file [file join $ck f.txt]] \
544 "trunk\n/side\n/side file\n"
545 pl_fossil $ck commit -m merged
546 pl_expect parents [pl_tip_parents [file join $work run r.fossil]] 2
547 }
548
549 # The databases are usable, and after "fossil pull" again the repository
550 # has the artifacts and check-ins of WORK/source.fossil.
551 #
552 proc pl_check_pull {work} {
553 set ck [file join $work run ck]
554 set repo [file join $work run r.fossil]
555 set source [file join $work source.fossil]
556 if {![pl_check_databases $work]} return
557 pl_expect pull [lindex [pl_fossil $ck pull $source] 0] 0
558 pl_expect_artifacts $repo $source
559 pl_fossil $ck update
560 pl_expect content [read_file [file join $ck a.txt]] "pulled\n"
561 }
562
563 # Both repositories pass PRAGMA integrity_check, and after "fossil push"
564 # again r.fossil has the artifacts and check-ins of l.fossil.
565 #
566 proc pl_check_push {work} {
567 set ck [file join $work run ck]
568 set remote [file join $work run r.fossil]
569 set clone [file join $work run l.fossil]
570 pl_expect integrity [pl_sql $remote "ATTACH '$clone' AS l;\
571 PRAGMA main.integrity_check; PRAGMA l.integrity_check"] "ok\nok"
572 pl_expect push [lindex [pl_fossil $ck push ../r.fossil] 0] 0
573 pl_expect_artifacts $remote $clone
574 }
575
576 # For "stash save" and "stash pop": the user's edit is in a.txt or in
577 # the stash, and is in a.txt after "fossil stash pop".
578 #
579 proc pl_check_stash {work} {
580 set ck [file join $work run ck]
581 if {![pl_check_databases $work]} return
582 if {[lindex [pl_fossil $ck stash list] 1] ne "empty stash"} {
583 pl_fossil $ck stash pop
584 }
585 pl_expect content [read_file [file join $ck a.txt]] \
586 "one\ntwo\nthree\nlocal\n"
587 }
588
589 # Returns the content of FILE, or "" if it does not exist.
590 #
591 proc pl_read {file} {
592 if {![file exists $file]} {return ""}
593 return [read_file $file]
594 }
595
596 # Checks that the user's edit to a.txt is in the file, or that "fossil
597 # undo" puts it back. CONSTRAINTS apply where a.txt is left with the
598 # content of the check-in.
599 #
600 proc pl_check_edit_kept {ck {constraints ""}} {
601 set edit "one\ntwo\nthree\nlocal\n"
602 if {[pl_read [file join $ck a.txt]] ne $edit} {
603 pl_fossil $ck undo
604 }
605 set found [pl_read [file join $ck a.txt]]
606 if {$found ne "one\ntwo\nthree\n"} {set constraints ""}
607 pl_expect edit $found $edit $constraints
608 }
609
610 # The databases are usable, and the edit is in a.txt or "fossil undo"
611 # puts it back.
612 #
613 proc pl_check_revert {work} {
614 if {![pl_check_databases $work]} return
615 # A revert overwrites the files before it commits their undo
616 # information, so an interrupted revert loses the user's edits.
617 pl_check_edit_kept [file join $work run ck] knownBug
618 }
619
620 # The databases are usable, and the edit is in a.txt or "fossil undo"
621 # again puts it back.
622 #
623 proc pl_check_undo {work} {
624 if {![pl_check_databases $work]} return
625 pl_check_edit_kept [file join $work run ck]
626 }
627
628 # The check-out database is missing or passes PRAGMA integrity_check,
629 # and after "fossil open" again where "fossil status" fails, or "fossil
630 # update" where it works, the check-out has every file of the check-in,
631 # unchanged.
632 #
633 proc pl_check_open {work} {
634 set ck [file join $work run ck]
635 set ckout [file join $ck .fslckout]
636 if {[file exists $ckout]} {
637 pl_expect integrity [pl_sql $ckout {PRAGMA integrity_check}] ok
638 }
639 if {[lindex [pl_fossil $ck status] 0] == 0} {
640 pl_fossil $ck update
641 } else {
642 # An open interrupted before it records the name of the repository
643 # leaves a check-out database that every command rejects.
644 lassign [pl_fossil $ck open ../r.fossil] status output
645 set unnamed [string match "*unable to find the name of a repo*" $output]
646 pl_expect open $status 0 [expr {$unnamed ? "knownBug" : ""}]
647 if {$status != 0} return
648 }
649 pl_expect_files $ck {a.txt b.txt c.txt}
650 pl_expect changes [pl_fossil $ck changes] {0 {}}
651 pl_expect content [pl_read [file join $ck a.txt]] "one\ntwo\nthree\n"
652 }
653
654 # The databases are usable, and the repository has the same artifacts
655 # and check-ins as before.
656 #
657 proc pl_check_rebuild {work} {
658 set repo [file join $work run r.fossil]
659 set original [file join $work template r.fossil]
660 if {![pl_check_databases $work]} return
661 pl_expect_artifacts $repo $original
662 }
663
664 # The new repository is missing, or fossil refuses to use it, or it has
665 # every public artifact and check-in of the original and no private one.
666 # An interrupted clone over a file: URL can leave the private content of
667 # the original, and one over HTTP a repository without its check-ins.
668 #
669 proc pl_check_clone {work} {
670 set clone [file join $work run c.fossil]
671 set source [file join $work source.fossil]
672 if {![file exists $clone] ||
673 [lindex [pl_fossil [file join $work run] info -R $clone] 0] != 0} {
674 return
675 }
676 set found [split [pl_sql $clone "SELECT count(*) FROM private;\
677 PRAGMA integrity_check"] \n]
678 pl_expect integrity [lrange $found 1 end] ok
679 set http [expr {$::plTest eq "clone-http"}]
680 pl_expect private [lindex $found 0] 0 [expr {$http ? "" : "knownBug"}]
681 pl_expect_artifacts $clone $source [expr {$http ? "knownBug" : ""}]
682 }
683
684 # Runs TEST for a repository in journal mode JOURNAL, from the template
685 # TEMPLATE, uninterrupted and then stopped at each stop point in each
686 # mode, and reports each check of the procedure CHECK once for each mode.
687 # The command CMD runs in directory DIR of the copy of the template. In
688 # CMD, SOURCE stands for WORK/source.fossil and PORT for the port of a
689 # server of it, which is started for a CMD that has PORT in it.
690 #
691 proc pl_test {test journal template dir check cmd} {
692 set ::plTest $test
693 set ::plJournal $journal
694 set work [file join $::workDir $test-$journal]
695 file mkdir $work
696 pl_template_$template $work $journal
697 set source [file join $work source.fossil]
698 set port ""
699 set server ""
700 if {[string match *PORT* $cmd]} {
701 set server [test_start_server $source stopArg]
702 set port [lindex $server 1]
703 }
704 try {
705 set cmd [lmap a $cmd {string map [list SOURCE $source PORT $port] $a}]
706 foreach mode {power kill} {
707 set ::plMode $mode
708 set ::plName powerloss-$test-$journal-$mode
709 set points [pl_run $work $dir $cmd 0 $mode]
710 test $::plName-points {[llength $points] > 0}
711 set ::plPoint none
712 $check $work
713 foreach point $points {
714 set at [lindex $point 0]
715 set stopped [pl_run $work $dir $cmd $at $mode]
716 protOut "$test stop point $at: [lrange $point 1 end]"
717 set ::plPoint $at
718 pl_expect stopped [pl_stop_seen $stopped $at $point $mode] stopped
719 $check $work
720 }
721 pl_report
722 }
723 } finally {
724 if {$server ne ""} {
725 test_stop_server $stopArg [lindex $server 0] [lindex $server 2]
726 }
727 file delete -force $work
728 }
729 }
730
731 # A fossil that is statically linked does not load the library.
732 file mkdir [file join $workDir probe template]
733 if {[pl_run [file join $workDir probe] . {new r.fossil} 0 power] eq ""} {
734 test_skip "LD_PRELOAD of powerloss.so has no effect on fossil,\
735 which may be statically linked"
736 }
737
738 set env(FOSSIL_USER) tester
739 # Each row is a test, its template, the directory the command runs in, its
740 # check procedure, the journal modes it runs for, and the command. The
741 # check procedures mark the known bugs.
742 #
743 foreach {test template dir check journals cmd} {
744 commit commit ck pl_check_commit {delete wal}
745 {commit -m two}
746 commit-merge commit_merge ck pl_check_commit_merge {delete wal}
747 {commit -m merged}
748 merge merge ck pl_check_merge {delete wal}
749 {merge side}
750 update update ck pl_check_update {delete wal}
751 {update}
752 stash-save edit ck pl_check_stash {delete wal}
753 {stash save -m local}
754 stash-pop stash ck pl_check_stash {delete wal}
755 {stash pop}
756 revert edit ck pl_check_revert {delete wal}
757 {revert}
758 undo reverted ck pl_check_undo {delete wal}
759 {undo}
760 open open ck pl_check_open {delete wal}
761 {open ../r.fossil}
762 rebuild rebuild ck pl_check_rebuild {delete wal}
763 {rebuild}
764 pull pull ck pl_check_pull {delete wal}
765 {pull SOURCE}
766 push push ck pl_check_push {delete wal}
767 {push ../r.fossil}
768 clone-file clone . pl_check_clone delete
769 {clone SOURCE c.fossil}
770 clone-http clone . pl_check_clone delete
771 {clone --proxy off http://127.0.0.1:PORT/ c.fossil}
772 } {
773 if {[string match *PORT* $cmd] && ![loopback_available]} {
774 test_skip_part "powerloss-$test needs a loopback interface"
775 continue
776 }
777 foreach journal $journals {
778 pl_test $test $journal $template $dir $check $cmd
779 }
780 }
781 unset env(FOSSIL_USER)
782
783 test_cleanup
--- a/tools/powerloss/README-POWERLOSS.md
+++ b/tools/powerloss/README-POWERLOSS.md
@@ -0,0 +1,218 @@
1
+# Power loss and killed-process tests for SQLite programs
2
+
3
+Dan Shearer, November 2026
4
+
5
+`powerloss.so` is an `LD_PRELOAD` library for Linux and BSD that stops a
6
+program wherever its SQLite database files could reach the disk, and leaves the
7
+files as a power loss or a killed process would. You can use it with any
8
+program that links SQLite. In the example the driver is `powerloss.sh`, and
9
+we're asking the question *what happens to Fossil repo and checkout databases
10
+when bad things happen during `fossil commit`?* There are different cases for
11
+WAL and DELETE mode repo dbs. `test/powerloss.test` in Fossil's test suite uses
12
+the same library to interrupt other Fossil commands, such as merge, update,
13
+push and clone.
14
+
15
+## The point in power loss testing
16
+
17
+One transaction committed across two SQLite database files can leave the
18
+checkout database and the repo database out of step if the transaction is
19
+interrupted, although both files pass an integrity check. The cause is that
20
+SQLite can only do an atomic commit across both files via a *super-journal*,
21
+and SQLite only makes a super-journal for databases in a rollback journal mode.
22
+If one of the databases is in WAL, MEMORY or OFF journal mode, or at
23
+`synchronous=OFF`, SQLite commits each file in turn (that is, not atomically).
24
+The [SQLite ATTACH documentation](https://sqlite.org/lang_attach.html) says:
25
+
26
+> If the main database is ":memory:" or if the journal_mode is WAL, then
27
+> transactions continue to be atomic within each individual database file. But
28
+> if the host computer crashes in the middle of a COMMIT where two or more
29
+> database files are updated, some of those files might get the changes where
30
+> others might not.
31
+
32
+The Fossil data model commits across multiple databases, and there are good
33
+reasons why a user might switch the repository database to [WAL
34
+mode](https://sqlite.org/wal.html). This test tool was written to verify that
35
+multi-database commits are safe.
36
+
37
+A single database in WAL mode can lose a committed transaction too. The [PRAGMA
38
+documentation](https://sqlite.org/pragma.html#pragma_synchronous) says:
39
+
40
+> A transaction committed in WAL mode with synchronous=NORMAL might roll back
41
+> following a power loss or system crash.
42
+
43
+Whether a program survives an interruption depends on its journal modes, its
44
+`synchronous` settings and the order in which it commits its databases. This
45
+tool stops the program at every point where the outcome could differ, and
46
+records the state of the databases after each stop.
47
+
48
+These problems are less likely to occur when using LMDB as the SQLite backing
49
+store via [LumoSQL](https://lumosql.org/src/lumosql), because LMDB syncs new
50
+pages before writing the meta page that refers to them, so a power loss does
51
+not lose a committed transaction from one database. A commit across two
52
+databases still needs this test to check that failures are graceful.
53
+
54
+## How it works
55
+
56
+There are two ways to interrupt a program. When the process is killed, the
57
+operating system retains everything the process wrote. When the operating
58
+system crashes or the power fails, the disk has only what the process synced.
59
+
60
+* **Power loss** (the default): the stop points are at every `fsync()`,
61
+ `fdatasync()` and `unlink()` of a database or journal file. The library saves
62
+ a copy of each database file when the first process of the run starts and
63
+ whenever a process syncs it. At the stop point it restores the saved copies,
64
+ deletes the files that were never synced and every `-shm` file, and exits
65
+ with status 77.
66
+* **Killed process** (`STOP_MODE=kill`): each `pwrite()` or `write()` to those
67
+ files is also a stop point, and so is each `fwrite()` to one that was opened
68
+ with `fopen()`. The C library's own write from inside `fwrite()` cannot be
69
+ intercepted, so without this a file written through stdio, such as the
70
+ repository that `fossil clone` copies from a file, would have no stop points.
71
+ At the stop point the library exits with status 77 and leaves every file as
72
+ it is. The other processes continue, and see the stopped process disappear,
73
+ as a client sees a server that is killed during a request.
74
+
75
+A transfer between two repositories writes them in two processes. A `fossil
76
+push` over a `file:` URL runs `fossil http` to write the remote repository,
77
+while `fossil server` writes its repository in the answering process. A power
78
+loss stops every process on the machine at the same moment, and a killed
79
+process stops only itself.
80
+
81
+Every process that loads the library during a run counts its stop points in the
82
+same sequence, including the programs that a program runs with `system()`. A
83
+process locks the library's state file around each write, sync and unlink of a
84
+tracked file, so a restore does not overlap another process's write, and a
85
+process that locks the state file after a power loss exits with status 77.
86
+
87
+The library reads its settings from the environment:
88
+
89
+* `STOP_DIR`: a working directory. The library tracks files under
90
+ `STOP_DIR/run`, saves copies in `STOP_DIR/shadow` and appends one line per
91
+ stop point to `STOP_DIR/log`, with the number, the call, the file and the
92
+ process ID. A file's copy has its path under `STOP_DIR/run`, with each `/`
93
+ replaced by `%`, so the `.fslckout` files of two checkouts have separate
94
+ copies. `STOP_DIR/shadow` also has the stop-point count, so a driver deletes
95
+ it before each run.
96
+* `STOP_AT`: the stop point to stop at, counting from 1. `0` runs the program
97
+ to the end and only records the stop points.
98
+* `STOP_MODE`: `kill` for the killed-process mode.
99
+
100
+A driver runs the program once with `STOP_AT=0` to count the stop points, then
101
+once for each one from a fresh copy of the files, and examines the files after
102
+each run. It should also check that each run stopped where it was told to,
103
+because a run that does not stop leaves the files of a finished command, which
104
+pass every other check. `powerloss.sh` requires that the run logged its stop
105
+point, that in power mode it logged nothing after it, and that the exit status
106
+isn't 0. `pl_stop_seen` in `test/powerloss.test` is stricter: for a command of
107
+one process it also requires the same call on the same file as in the counting
108
+run, and exit status 77.
109
+
110
+## Running the Fossil check-in test
111
+
112
+`powerloss.sh` uses `fossil` to create a repository and a check-out with an
113
+edit, an add, a remove and a rename pending. It then runs the check-in once for
114
+each stop point, and stops it there, using the command in `PL_COMMIT`, which
115
+defaults to `fossil commit -m two`. After each run the script reads the
116
+check-in that `.fslckout` says was just made and the repo database's latest
117
+check-in, and runs `PRAGMA integrity_check` on both files. The third argument
118
+sets the repo to WAL or DELETE mode.
119
+
120
+From the root of the Fossil source tree, with the `fossil` you want to test:
121
+
122
+```sh
123
+cc -shared -fPIC -o tools/powerloss/powerloss.so tools/powerloss/powerloss.c
124
+sh tools/powerloss/powerloss.sh "$(command -v fossil)" /tmp/pl wal
125
+```
126
+
127
+Give the `fossil` binary as an absolute path, because the script runs it from
128
+other directories. A statically linked `fossil` doesn't load the library, so
129
+the script finds no stop points.
130
+
131
+Set `STOP_MODE=kill` in the environment of `powerloss.sh` for the
132
+killed-process test.
133
+
134
+Output from Fossil 2.29 with a WAL repository:
135
+
136
+```text
137
+repository journal mode: wal
138
+check-out journal mode: delete
139
+commit without a stop: exit 0, 13 stop points
140
+1 unlink /r.fossil-wal checkout=5 repo-latest=5 integrity=ok/ok consistent
141
+2 fsync /ck/.fslckout-journal checkout=5 repo-latest=5 integrity=ok/ok consistent
142
+3 fsync /ck/.fslckout-journal checkout=5 repo-latest=5 integrity=ok/ok consistent
143
+4 fsync /ck/.fslckout checkout=5 repo-latest=5 integrity=ok/ok consistent
144
+5 unlink /ck/.fslckout-journal checkout=5 repo-latest=5 integrity=ok/ok consistent
145
+6 fsync /ck/.fslckout-journal checkout=5 repo-latest=5 integrity=ok/ok consistent
146
+7 fsync /ck/.fslckout-journal checkout=5 repo-latest=5 integrity=ok/ok consistent
147
+8 fsync /ck/.fslckout checkout=5 repo-latest=5 integrity=ok/ok consistent
148
+9 fsync /r.fossil-wal checkout=5 repo-latest=5 integrity=ok/ok consistent
149
+10 unlink /ck/.fslckout-journal checkout=8 repo-latest=5 integrity=ok/ok AHEAD
150
+11 fsync /r.fossil-wal checkout=8 repo-latest=8 integrity=ok/ok consistent
151
+12 fsync /r.fossil checkout=8 repo-latest=8 integrity=ok/ok consistent
152
+13 unlink /r.fossil-wal checkout=8 repo-latest=8 integrity=ok/ok consistent
153
+```
154
+
155
+Each line gives the verdict:
156
+
157
+* **consistent:** the checkout db records the repository's latest check-in.
158
+* **BEHIND:** the repository has a later check-in than the checkout db records.
159
+ `fossil status` works and still lists the changes as pending, and `fossil
160
+ commit` stops with "Would fork". `fossil update` moves the checkout to the
161
+ new check-in, warning of merge conflicts on the way, and after it nothing is
162
+ pending.
163
+* **AHEAD:** the checkout db records a check-in that the repository does not
164
+ have. `fossil status`, `changes`, `commit`, `update` and `ls` all fail with
165
+ "Local check-out database is out of sync with repository file".
166
+
167
+At point 10 above, the checkout db has committed, and the repository's commit
168
+is in the WAL but SQLite has not synced it. Fossil builds SQLite with
169
+`-DSQLITE_DEFAULT_WAL_SYNCHRONOUS=1` (see `tools/makemake.tcl`), so a WAL
170
+repository runs at `synchronous=NORMAL`, where SQLite syncs the WAL at a
171
+checkpoint and not at each commit. The checkout db is in DELETE mode at
172
+`synchronous=FULL`, so its commit is synced. A power loss there loses the
173
+repository's commit and leaves the checkout db ahead of the repository. `fossil
174
+close` and `fossil open --force` fail there with the same message, so the way
175
+out is to delete `.fslckout` and run `fossil open --force --keep`. That keeps
176
+your edits, and you redo the pending adds, removes and renames. With a DELETE
177
+repository the same run has 14 stop points and is consistent at every one. In
178
+kill mode a WAL repository has 122 stop points, with one BEHIND and no AHEAD.
179
+
180
+## Testing SQLite programs other than Fossil
181
+
182
+Only `is_db()` in `powerloss.c` and all of `powerloss.sh` are specific to
183
+Fossil. The rest of the C program is generic:
184
+
185
+* `is_db()` decides which files to track, matching names that contain `.fossil`
186
+ or `.fslckout`. Change it to match the program's database files.
187
+* The library intercepts `open()`, `open64()`, `close()`, `fsync()`,
188
+ `fdatasync()`, `unlink()`, `pwrite()`, `pwrite64()`, `write()`, `fopen()`,
189
+ `fopen64()`, `fclose()` and `fwrite()`. Other programs and other operating
190
+ systems may write through other calls. Check your binary or library that
191
+ contains SQLite with `nm -D FILE | grep -E ' U
192
+ (f?open|f?close|f(data)?sync|unlink|[fp]?write|lseek|ftruncate|rename)'`.
193
+* Write a driver for the program to replace `powerloss.sh`.
194
+
195
+## Stuff it doesn't do
196
+
197
+* At a power loss, every write since a file's last sync is lost. A real disk
198
+ may retain some unsynced writes, in any order, or a partly written page; the
199
+ library does not test those cases.
200
+* The library treats an `unlink()` as reaching the disk at once and ignores
201
+ directory syncs.
202
+* The library tracks file descriptors below 4096 and at most 64 stdio streams.
203
+ `MAXFD` and `MAXFILE` in `powerloss.c` set those limits.
204
+* A process that does not load the library, such as one started with
205
+ `LD_PRELOAD` removed from its environment, is neither counted nor stopped.
206
+* At a power loss, the other processes of the run aren't killed. Each one exits
207
+ with status 77 at its next write, sync or unlink of a tracked file, and can
208
+ write other files until then.
209
+* The library tracks only the database files. The other files under
210
+ `STOP_DIR/run`, such as the files of a check-out, stay as the program wrote
211
+ them. A real power loss can lose what was written to a file that was never
212
+ synced, and Fossil doesn't sync the files it writes into a check-out.
213
+* The library doesn't intercept `ftruncate()` or `rename()`. A truncate isn't a
214
+ stop point, and a tracked file that the program renames has no saved copy
215
+ under its new name, so a power loss deletes it.
216
+* The library is for a single-threaded program such as Fossil. It locks its
217
+ state file with `fcntl()`, which doesn't stop two threads of one process from
218
+ writing at the same time.
--- a/tools/powerloss/README-POWERLOSS.md
+++ b/tools/powerloss/README-POWERLOSS.md
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
--- a/tools/powerloss/README-POWERLOSS.md
+++ b/tools/powerloss/README-POWERLOSS.md
@@ -0,0 +1,218 @@
1 # Power loss and killed-process tests for SQLite programs
2
3 Dan Shearer, November 2026
4
5 `powerloss.so` is an `LD_PRELOAD` library for Linux and BSD that stops a
6 program wherever its SQLite database files could reach the disk, and leaves the
7 files as a power loss or a killed process would. You can use it with any
8 program that links SQLite. In the example the driver is `powerloss.sh`, and
9 we're asking the question *what happens to Fossil repo and checkout databases
10 when bad things happen during `fossil commit`?* There are different cases for
11 WAL and DELETE mode repo dbs. `test/powerloss.test` in Fossil's test suite uses
12 the same library to interrupt other Fossil commands, such as merge, update,
13 push and clone.
14
15 ## The point in power loss testing
16
17 One transaction committed across two SQLite database files can leave the
18 checkout database and the repo database out of step if the transaction is
19 interrupted, although both files pass an integrity check. The cause is that
20 SQLite can only do an atomic commit across both files via a *super-journal*,
21 and SQLite only makes a super-journal for databases in a rollback journal mode.
22 If one of the databases is in WAL, MEMORY or OFF journal mode, or at
23 `synchronous=OFF`, SQLite commits each file in turn (that is, not atomically).
24 The [SQLite ATTACH documentation](https://sqlite.org/lang_attach.html) says:
25
26 > If the main database is ":memory:" or if the journal_mode is WAL, then
27 > transactions continue to be atomic within each individual database file. But
28 > if the host computer crashes in the middle of a COMMIT where two or more
29 > database files are updated, some of those files might get the changes where
30 > others might not.
31
32 The Fossil data model commits across multiple databases, and there are good
33 reasons why a user might switch the repository database to [WAL
34 mode](https://sqlite.org/wal.html). This test tool was written to verify that
35 multi-database commits are safe.
36
37 A single database in WAL mode can lose a committed transaction too. The [PRAGMA
38 documentation](https://sqlite.org/pragma.html#pragma_synchronous) says:
39
40 > A transaction committed in WAL mode with synchronous=NORMAL might roll back
41 > following a power loss or system crash.
42
43 Whether a program survives an interruption depends on its journal modes, its
44 `synchronous` settings and the order in which it commits its databases. This
45 tool stops the program at every point where the outcome could differ, and
46 records the state of the databases after each stop.
47
48 These problems are less likely to occur when using LMDB as the SQLite backing
49 store via [LumoSQL](https://lumosql.org/src/lumosql), because LMDB syncs new
50 pages before writing the meta page that refers to them, so a power loss does
51 not lose a committed transaction from one database. A commit across two
52 databases still needs this test to check that failures are graceful.
53
54 ## How it works
55
56 There are two ways to interrupt a program. When the process is killed, the
57 operating system retains everything the process wrote. When the operating
58 system crashes or the power fails, the disk has only what the process synced.
59
60 * **Power loss** (the default): the stop points are at every `fsync()`,
61 `fdatasync()` and `unlink()` of a database or journal file. The library saves
62 a copy of each database file when the first process of the run starts and
63 whenever a process syncs it. At the stop point it restores the saved copies,
64 deletes the files that were never synced and every `-shm` file, and exits
65 with status 77.
66 * **Killed process** (`STOP_MODE=kill`): each `pwrite()` or `write()` to those
67 files is also a stop point, and so is each `fwrite()` to one that was opened
68 with `fopen()`. The C library's own write from inside `fwrite()` cannot be
69 intercepted, so without this a file written through stdio, such as the
70 repository that `fossil clone` copies from a file, would have no stop points.
71 At the stop point the library exits with status 77 and leaves every file as
72 it is. The other processes continue, and see the stopped process disappear,
73 as a client sees a server that is killed during a request.
74
75 A transfer between two repositories writes them in two processes. A `fossil
76 push` over a `file:` URL runs `fossil http` to write the remote repository,
77 while `fossil server` writes its repository in the answering process. A power
78 loss stops every process on the machine at the same moment, and a killed
79 process stops only itself.
80
81 Every process that loads the library during a run counts its stop points in the
82 same sequence, including the programs that a program runs with `system()`. A
83 process locks the library's state file around each write, sync and unlink of a
84 tracked file, so a restore does not overlap another process's write, and a
85 process that locks the state file after a power loss exits with status 77.
86
87 The library reads its settings from the environment:
88
89 * `STOP_DIR`: a working directory. The library tracks files under
90 `STOP_DIR/run`, saves copies in `STOP_DIR/shadow` and appends one line per
91 stop point to `STOP_DIR/log`, with the number, the call, the file and the
92 process ID. A file's copy has its path under `STOP_DIR/run`, with each `/`
93 replaced by `%`, so the `.fslckout` files of two checkouts have separate
94 copies. `STOP_DIR/shadow` also has the stop-point count, so a driver deletes
95 it before each run.
96 * `STOP_AT`: the stop point to stop at, counting from 1. `0` runs the program
97 to the end and only records the stop points.
98 * `STOP_MODE`: `kill` for the killed-process mode.
99
100 A driver runs the program once with `STOP_AT=0` to count the stop points, then
101 once for each one from a fresh copy of the files, and examines the files after
102 each run. It should also check that each run stopped where it was told to,
103 because a run that does not stop leaves the files of a finished command, which
104 pass every other check. `powerloss.sh` requires that the run logged its stop
105 point, that in power mode it logged nothing after it, and that the exit status
106 isn't 0. `pl_stop_seen` in `test/powerloss.test` is stricter: for a command of
107 one process it also requires the same call on the same file as in the counting
108 run, and exit status 77.
109
110 ## Running the Fossil check-in test
111
112 `powerloss.sh` uses `fossil` to create a repository and a check-out with an
113 edit, an add, a remove and a rename pending. It then runs the check-in once for
114 each stop point, and stops it there, using the command in `PL_COMMIT`, which
115 defaults to `fossil commit -m two`. After each run the script reads the
116 check-in that `.fslckout` says was just made and the repo database's latest
117 check-in, and runs `PRAGMA integrity_check` on both files. The third argument
118 sets the repo to WAL or DELETE mode.
119
120 From the root of the Fossil source tree, with the `fossil` you want to test:
121
122 ```sh
123 cc -shared -fPIC -o tools/powerloss/powerloss.so tools/powerloss/powerloss.c
124 sh tools/powerloss/powerloss.sh "$(command -v fossil)" /tmp/pl wal
125 ```
126
127 Give the `fossil` binary as an absolute path, because the script runs it from
128 other directories. A statically linked `fossil` doesn't load the library, so
129 the script finds no stop points.
130
131 Set `STOP_MODE=kill` in the environment of `powerloss.sh` for the
132 killed-process test.
133
134 Output from Fossil 2.29 with a WAL repository:
135
136 ```text
137 repository journal mode: wal
138 check-out journal mode: delete
139 commit without a stop: exit 0, 13 stop points
140 1 unlink /r.fossil-wal checkout=5 repo-latest=5 integrity=ok/ok consistent
141 2 fsync /ck/.fslckout-journal checkout=5 repo-latest=5 integrity=ok/ok consistent
142 3 fsync /ck/.fslckout-journal checkout=5 repo-latest=5 integrity=ok/ok consistent
143 4 fsync /ck/.fslckout checkout=5 repo-latest=5 integrity=ok/ok consistent
144 5 unlink /ck/.fslckout-journal checkout=5 repo-latest=5 integrity=ok/ok consistent
145 6 fsync /ck/.fslckout-journal checkout=5 repo-latest=5 integrity=ok/ok consistent
146 7 fsync /ck/.fslckout-journal checkout=5 repo-latest=5 integrity=ok/ok consistent
147 8 fsync /ck/.fslckout checkout=5 repo-latest=5 integrity=ok/ok consistent
148 9 fsync /r.fossil-wal checkout=5 repo-latest=5 integrity=ok/ok consistent
149 10 unlink /ck/.fslckout-journal checkout=8 repo-latest=5 integrity=ok/ok AHEAD
150 11 fsync /r.fossil-wal checkout=8 repo-latest=8 integrity=ok/ok consistent
151 12 fsync /r.fossil checkout=8 repo-latest=8 integrity=ok/ok consistent
152 13 unlink /r.fossil-wal checkout=8 repo-latest=8 integrity=ok/ok consistent
153 ```
154
155 Each line gives the verdict:
156
157 * **consistent:** the checkout db records the repository's latest check-in.
158 * **BEHIND:** the repository has a later check-in than the checkout db records.
159 `fossil status` works and still lists the changes as pending, and `fossil
160 commit` stops with "Would fork". `fossil update` moves the checkout to the
161 new check-in, warning of merge conflicts on the way, and after it nothing is
162 pending.
163 * **AHEAD:** the checkout db records a check-in that the repository does not
164 have. `fossil status`, `changes`, `commit`, `update` and `ls` all fail with
165 "Local check-out database is out of sync with repository file".
166
167 At point 10 above, the checkout db has committed, and the repository's commit
168 is in the WAL but SQLite has not synced it. Fossil builds SQLite with
169 `-DSQLITE_DEFAULT_WAL_SYNCHRONOUS=1` (see `tools/makemake.tcl`), so a WAL
170 repository runs at `synchronous=NORMAL`, where SQLite syncs the WAL at a
171 checkpoint and not at each commit. The checkout db is in DELETE mode at
172 `synchronous=FULL`, so its commit is synced. A power loss there loses the
173 repository's commit and leaves the checkout db ahead of the repository. `fossil
174 close` and `fossil open --force` fail there with the same message, so the way
175 out is to delete `.fslckout` and run `fossil open --force --keep`. That keeps
176 your edits, and you redo the pending adds, removes and renames. With a DELETE
177 repository the same run has 14 stop points and is consistent at every one. In
178 kill mode a WAL repository has 122 stop points, with one BEHIND and no AHEAD.
179
180 ## Testing SQLite programs other than Fossil
181
182 Only `is_db()` in `powerloss.c` and all of `powerloss.sh` are specific to
183 Fossil. The rest of the C program is generic:
184
185 * `is_db()` decides which files to track, matching names that contain `.fossil`
186 or `.fslckout`. Change it to match the program's database files.
187 * The library intercepts `open()`, `open64()`, `close()`, `fsync()`,
188 `fdatasync()`, `unlink()`, `pwrite()`, `pwrite64()`, `write()`, `fopen()`,
189 `fopen64()`, `fclose()` and `fwrite()`. Other programs and other operating
190 systems may write through other calls. Check your binary or library that
191 contains SQLite with `nm -D FILE | grep -E ' U
192 (f?open|f?close|f(data)?sync|unlink|[fp]?write|lseek|ftruncate|rename)'`.
193 * Write a driver for the program to replace `powerloss.sh`.
194
195 ## Stuff it doesn't do
196
197 * At a power loss, every write since a file's last sync is lost. A real disk
198 may retain some unsynced writes, in any order, or a partly written page; the
199 library does not test those cases.
200 * The library treats an `unlink()` as reaching the disk at once and ignores
201 directory syncs.
202 * The library tracks file descriptors below 4096 and at most 64 stdio streams.
203 `MAXFD` and `MAXFILE` in `powerloss.c` set those limits.
204 * A process that does not load the library, such as one started with
205 `LD_PRELOAD` removed from its environment, is neither counted nor stopped.
206 * At a power loss, the other processes of the run aren't killed. Each one exits
207 with status 77 at its next write, sync or unlink of a tracked file, and can
208 write other files until then.
209 * The library tracks only the database files. The other files under
210 `STOP_DIR/run`, such as the files of a check-out, stay as the program wrote
211 them. A real power loss can lose what was written to a file that was never
212 synced, and Fossil doesn't sync the files it writes into a check-out.
213 * The library doesn't intercept `ftruncate()` or `rename()`. A truncate isn't a
214 stop point, and a tracked file that the program renames has no saved copy
215 under its new name, so a power loss deletes it.
216 * The library is for a single-threaded program such as Fossil. It locks its
217 state file with `fcntl()`, which doesn't stop two threads of one process from
218 writing at the same time.
--- a/tools/powerloss/powerloss.c
+++ b/tools/powerloss/powerloss.c
@@ -0,0 +1,625 @@
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
+}
--- a/tools/powerloss/powerloss.c
+++ b/tools/powerloss/powerloss.c
@@ -0,0 +1,625 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
--- a/tools/powerloss/powerloss.c
+++ b/tools/powerloss/powerloss.c
@@ -0,0 +1,625 @@
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 }
--- a/tools/powerloss/powerloss.sh
+++ b/tools/powerloss/powerloss.sh
@@ -0,0 +1,144 @@
1
+#!/bin/sh
2
+#
3
+# Usage: powerloss.sh FOSSIL-BINARY WORKDIR ?REPO-MODE?
4
+#
5
+# Dan Shearer, November 2026
6
+#
7
+# A standalone driver for powerloss.so, and the worked example in
8
+# README-POWERLOSS.md. test/powerloss.test in Fossil's test suite
9
+# interrupts the same check-in with more checks, and other commands too.
10
+#
11
+# Runs a check-in once for each point where powerloss.so will stop it.
12
+# After each stop, prints the integrity_check result of the repository and
13
+# the check-out database, and whether the two agree on the latest check-in.
14
+#
15
+# FOSSIL-BINARY creates the repository and check-out, and reads both
16
+# databases with its sqlite3 command. Give it as an absolute path, because
17
+# the script runs it from other directories. WORKDIR is deleted and
18
+# recreated. REPO-MODE is "wal" (the default) or "delete".
19
+#
20
+# PL_COMMIT is the shell command that makes the check-in. It defaults to
21
+# "FOSSIL-BINARY commit -m two", and lets you test another check-in
22
+# program against the same repository.
23
+#
24
+# With STOP_MODE=kill in the environment, powerloss.so also stops at each
25
+# pwrite and write, and leaves the files as the program wrote them, as a
26
+# killed process would.
27
+#
28
+# Exits with status 0, with 1 if a run did not stop at its stop point, or
29
+# with 2 if the set-up failed.
30
+
31
+usage(){ echo "usage: $0 FOSSIL-BINARY WORKDIR ?wal|delete?" >&2; exit 2; }
32
+[ $# -ge 2 ] || usage
33
+fossil=$1
34
+work=$2
35
+case ${3:-wal} in
36
+ wal) walopt=--wal ;;
37
+ delete) walopt= ;;
38
+ *) usage ;;
39
+esac
40
+shim=$(cd "$(dirname "$0")" && pwd)/powerloss.so
41
+if [ ! -f "$shim" ]; then
42
+ echo "$0: build $shim from powerloss.c first" >&2
43
+ exit 2
44
+fi
45
+repo=$work/run/r.fossil
46
+ckout=$work/run/ck/.fslckout
47
+
48
+sql(){ "$fossil" sqlite3 --no-repository -list "$@" 2>&1; }
49
+
50
+rm -rf "$work"
51
+mkdir -p "$work/home" "$work/run/ck"
52
+export FOSSIL_HOME="$work/home" FOSSIL_USER=tester
53
+
54
+(
55
+ set -e
56
+ cd "$work/run"
57
+ "$fossil" new r.fossil
58
+ "$fossil" rebuild $walopt r.fossil
59
+ cd ck
60
+ "$fossil" open ../r.fossil
61
+ echo one >a.txt
62
+ echo bee >b.txt
63
+ echo sea >c.txt
64
+ "$fossil" add a.txt b.txt c.txt
65
+ "$fossil" commit -m one
66
+ echo "second version" >a.txt
67
+ echo new >d.txt
68
+ "$fossil" add d.txt
69
+ "$fossil" rm b.txt
70
+ "$fossil" mv --hard c.txt e.txt
71
+) >/dev/null
72
+[ $? -eq 0 ] || exit 2
73
+echo "repository journal mode: $(sql "$repo" 'PRAGMA journal_mode;')"
74
+echo "check-out journal mode: $(sql "$ckout" 'PRAGMA journal_mode;')"
75
+cp -pR "$work/run" "$work/template"
76
+
77
+# Prints the check-in that .fslckout records, the repository's latest
78
+# check-in, the integrity_check result of each database, and a verdict:
79
+# AHEAD when the repository does not have the check-in that .fslckout
80
+# records, BEHIND when the repository has a later one, and otherwise
81
+# consistent.
82
+state(){
83
+ ckin=$(sql "$ckout" "SELECT value FROM vvar WHERE name='checkout';")
84
+ have=$(sql "$repo" "SELECT count(*) FROM blob WHERE rid=0+'$ckin';")
85
+ last=$(sql "$repo" "SELECT objid FROM event WHERE type='ci'
86
+ ORDER BY mtime DESC, objid DESC LIMIT 1;")
87
+ repook=$(sql "$repo" 'PRAGMA integrity_check;')
88
+ ckoutok=$(sql "$ckout" 'PRAGMA integrity_check;')
89
+ if [ "$have" != 1 ]; then verdict=AHEAD
90
+ elif [ "$ckin" != "$last" ]; then verdict=BEHIND
91
+ else verdict=consistent; fi
92
+ echo "checkout=$ckin repo-latest=$last integrity=$repook/$ckoutok $verdict"
93
+}
94
+
95
+# Makes the check-in from a fresh copy of the template. powerloss.so
96
+# stops it at stop point $1, or lets it finish if $1 is 0. Returns the
97
+# exit status of the check-in command.
98
+run(){
99
+ rm -rf "$work/run" "$work/shadow" "$work/log"
100
+ cp -pR "$work/template" "$work/run"
101
+ ( export STOP_DIR="$work" STOP_AT=$1 LD_PRELOAD="$shim"
102
+ cd "$work/run/ck" || exit 2
103
+ if [ -n "$PL_COMMIT" ]; then sh -c "$PL_COMMIT"
104
+ else "$fossil" commit -m two; fi
105
+ ) >/dev/null 2>&1
106
+}
107
+
108
+run 0
109
+rc=$?
110
+if [ ! -s "$work/log" ]; then
111
+ echo "$0: powerloss.so logged no stop points (exit $rc)." \
112
+ "A statically linked fossil does not load it." >&2
113
+ exit 2
114
+fi
115
+n=$(($(wc -l <"$work/log")))
116
+echo "commit without a stop: exit $rc, $n stop points"
117
+
118
+# A run that does not stop at its stop point leaves the files of a
119
+# finished command, and those files pass every check in state(). So the
120
+# loop requires that the run logged the stop point, that in power mode it
121
+# logged nothing after it, and that the exit status is not 0. In kill
122
+# mode the other processes of the command continue, and can log more.
123
+# The status is 77 when the check-in command itself stops, and some other
124
+# status when a process that the command started stops and the command
125
+# then fails. Each line of output has the call and the file that the
126
+# stopped run logged at the stop point.
127
+fail=0
128
+i=0
129
+while [ "$i" -lt "$n" ]; do
130
+ i=$((i+1))
131
+ run "$i"
132
+ rc=$?
133
+ logged=$(($(wc -l <"$work/log")))
134
+ last=$(sed -n "${i}p" "$work/log" | cut -d' ' -f2,3)
135
+ if [ "$rc" = 0 ] || [ -z "$last" ] ||
136
+ { [ "$STOP_MODE" != kill ] && [ "$logged" != "$i" ]; }; then
137
+ echo "$i $last DID NOT STOP THERE: exit $rc," \
138
+ "$logged stop points logged"
139
+ fail=1
140
+ continue
141
+ fi
142
+ echo "$i $last $(state)"
143
+done
144
+exit $fail
--- a/tools/powerloss/powerloss.sh
+++ b/tools/powerloss/powerloss.sh
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
--- a/tools/powerloss/powerloss.sh
+++ b/tools/powerloss/powerloss.sh
@@ -0,0 +1,144 @@
1 #!/bin/sh
2 #
3 # Usage: powerloss.sh FOSSIL-BINARY WORKDIR ?REPO-MODE?
4 #
5 # Dan Shearer, November 2026
6 #
7 # A standalone driver for powerloss.so, and the worked example in
8 # README-POWERLOSS.md. test/powerloss.test in Fossil's test suite
9 # interrupts the same check-in with more checks, and other commands too.
10 #
11 # Runs a check-in once for each point where powerloss.so will stop it.
12 # After each stop, prints the integrity_check result of the repository and
13 # the check-out database, and whether the two agree on the latest check-in.
14 #
15 # FOSSIL-BINARY creates the repository and check-out, and reads both
16 # databases with its sqlite3 command. Give it as an absolute path, because
17 # the script runs it from other directories. WORKDIR is deleted and
18 # recreated. REPO-MODE is "wal" (the default) or "delete".
19 #
20 # PL_COMMIT is the shell command that makes the check-in. It defaults to
21 # "FOSSIL-BINARY commit -m two", and lets you test another check-in
22 # program against the same repository.
23 #
24 # With STOP_MODE=kill in the environment, powerloss.so also stops at each
25 # pwrite and write, and leaves the files as the program wrote them, as a
26 # killed process would.
27 #
28 # Exits with status 0, with 1 if a run did not stop at its stop point, or
29 # with 2 if the set-up failed.
30
31 usage(){ echo "usage: $0 FOSSIL-BINARY WORKDIR ?wal|delete?" >&2; exit 2; }
32 [ $# -ge 2 ] || usage
33 fossil=$1
34 work=$2
35 case ${3:-wal} in
36 wal) walopt=--wal ;;
37 delete) walopt= ;;
38 *) usage ;;
39 esac
40 shim=$(cd "$(dirname "$0")" && pwd)/powerloss.so
41 if [ ! -f "$shim" ]; then
42 echo "$0: build $shim from powerloss.c first" >&2
43 exit 2
44 fi
45 repo=$work/run/r.fossil
46 ckout=$work/run/ck/.fslckout
47
48 sql(){ "$fossil" sqlite3 --no-repository -list "$@" 2>&1; }
49
50 rm -rf "$work"
51 mkdir -p "$work/home" "$work/run/ck"
52 export FOSSIL_HOME="$work/home" FOSSIL_USER=tester
53
54 (
55 set -e
56 cd "$work/run"
57 "$fossil" new r.fossil
58 "$fossil" rebuild $walopt r.fossil
59 cd ck
60 "$fossil" open ../r.fossil
61 echo one >a.txt
62 echo bee >b.txt
63 echo sea >c.txt
64 "$fossil" add a.txt b.txt c.txt
65 "$fossil" commit -m one
66 echo "second version" >a.txt
67 echo new >d.txt
68 "$fossil" add d.txt
69 "$fossil" rm b.txt
70 "$fossil" mv --hard c.txt e.txt
71 ) >/dev/null
72 [ $? -eq 0 ] || exit 2
73 echo "repository journal mode: $(sql "$repo" 'PRAGMA journal_mode;')"
74 echo "check-out journal mode: $(sql "$ckout" 'PRAGMA journal_mode;')"
75 cp -pR "$work/run" "$work/template"
76
77 # Prints the check-in that .fslckout records, the repository's latest
78 # check-in, the integrity_check result of each database, and a verdict:
79 # AHEAD when the repository does not have the check-in that .fslckout
80 # records, BEHIND when the repository has a later one, and otherwise
81 # consistent.
82 state(){
83 ckin=$(sql "$ckout" "SELECT value FROM vvar WHERE name='checkout';")
84 have=$(sql "$repo" "SELECT count(*) FROM blob WHERE rid=0+'$ckin';")
85 last=$(sql "$repo" "SELECT objid FROM event WHERE type='ci'
86 ORDER BY mtime DESC, objid DESC LIMIT 1;")
87 repook=$(sql "$repo" 'PRAGMA integrity_check;')
88 ckoutok=$(sql "$ckout" 'PRAGMA integrity_check;')
89 if [ "$have" != 1 ]; then verdict=AHEAD
90 elif [ "$ckin" != "$last" ]; then verdict=BEHIND
91 else verdict=consistent; fi
92 echo "checkout=$ckin repo-latest=$last integrity=$repook/$ckoutok $verdict"
93 }
94
95 # Makes the check-in from a fresh copy of the template. powerloss.so
96 # stops it at stop point $1, or lets it finish if $1 is 0. Returns the
97 # exit status of the check-in command.
98 run(){
99 rm -rf "$work/run" "$work/shadow" "$work/log"
100 cp -pR "$work/template" "$work/run"
101 ( export STOP_DIR="$work" STOP_AT=$1 LD_PRELOAD="$shim"
102 cd "$work/run/ck" || exit 2
103 if [ -n "$PL_COMMIT" ]; then sh -c "$PL_COMMIT"
104 else "$fossil" commit -m two; fi
105 ) >/dev/null 2>&1
106 }
107
108 run 0
109 rc=$?
110 if [ ! -s "$work/log" ]; then
111 echo "$0: powerloss.so logged no stop points (exit $rc)." \
112 "A statically linked fossil does not load it." >&2
113 exit 2
114 fi
115 n=$(($(wc -l <"$work/log")))
116 echo "commit without a stop: exit $rc, $n stop points"
117
118 # A run that does not stop at its stop point leaves the files of a
119 # finished command, and those files pass every check in state(). So the
120 # loop requires that the run logged the stop point, that in power mode it
121 # logged nothing after it, and that the exit status is not 0. In kill
122 # mode the other processes of the command continue, and can log more.
123 # The status is 77 when the check-in command itself stops, and some other
124 # status when a process that the command started stops and the command
125 # then fails. Each line of output has the call and the file that the
126 # stopped run logged at the stop point.
127 fail=0
128 i=0
129 while [ "$i" -lt "$n" ]; do
130 i=$((i+1))
131 run "$i"
132 rc=$?
133 logged=$(($(wc -l <"$work/log")))
134 last=$(sed -n "${i}p" "$work/log" | cut -d' ' -f2,3)
135 if [ "$rc" = 0 ] || [ -z "$last" ] ||
136 { [ "$STOP_MODE" != kill ] && [ "$logged" != "$i" ]; }; then
137 echo "$i $last DID NOT STOP THERE: exit $rc," \
138 "$logged stop points logged"
139 fail=1
140 continue
141 fi
142 echo "$i $last $(state)"
143 done
144 exit $fail

Keyboard Shortcuts

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