1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
//! Which file on disk each open SQLite connection is actually attached to.
//!
//! SQLite keeps one WAL-index (the `-shm` file) per database file inside a
//! process, and the first connection to win the exclusive dead-man-switch lock
//! on a `-shm` shrinks that file (to three bytes on Darwin, zero on other Unix
//! platforms) before mapping it. POSIX
//! advisory locks never conflict between two descriptors held by the *same*
//! process, so that lock protects nothing once one process holds two
//! connections attached to two *different* database files at the *same* path:
//! the newer connection truncates a `-shm` the older connection has already
//! memory-mapped, and the older connection dies with SIGBUS the next time it
//! reads through the mapping.
//!
//! Nothing in that crash names its cause. The fault surfaces deep inside
//! SQLite, in whichever later query happens to touch the mapping, long after
//! the delete-and-recreate that set it up. So this registry records the
//! identity of the file behind every tracked connection and reports the moment
//! two identities diverge at one path, naming the database and both
//! connections. It also reports a database file that is deleted, renamed, or
//! replaced while this process still has a connection open on it, which is the
//! operation that creates the divergence in the first place.
//!
//! Callgraph file-set mutations also use this registry for enforcement: opening
//! and registering a handle is serialized with checking for live users and
//! removing or renaming its files.
use std::collections::{BTreeMap, HashMap, HashSet};
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock, RwLock};
/// Most recent hazards retained for inspection. Bounded because a process that
/// keeps replacing databases under open connections would otherwise grow this
/// without limit.
const RETAINED_HAZARDS: usize = 64;
/// Identity of the file a connection is attached to, as SQLite keys it: the
/// device and inode, not the path.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FileIdentity {
device: u64,
inode: u64,
}
impl std::fmt::Display for FileIdentity {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(formatter, "dev={}/ino={}", self.device, self.inode)
}
}
/// Read the identity of the file currently at `path`.
///
/// Unix uses device/inode; Windows uses volume serial number/file index from
/// a metadata-only handle. Returns `None` when no identity is available.
pub fn identity_of(path: &Path) -> Option<FileIdentity> {
#[cfg(any(test, feature = "test-support"))]
stat_probe::record(path);
native_identity(crate::file_identity::metadata(path).ok()?.1)
}
fn native_identity(identity: crate::file_identity::FileIdentity) -> Option<FileIdentity> {
match identity {
crate::file_identity::FileIdentity::Known { volume, index } => Some(FileIdentity {
device: volume,
inode: index,
}),
crate::file_identity::FileIdentity::Unavailable => None,
}
}
#[rustfmt::skip]
test_support_visibility! {
fn metadata_identity(metadata: &std::fs::Metadata) -> Option<FileIdentity> {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
Some(FileIdentity {
device: metadata.dev(),
inode: metadata.ino(),
})
}
#[cfg(not(unix))]
{
let _ = metadata;
None
}
}
}
#[rustfmt::skip]
test_support_visibility! {
// Cached sidecar identities outlive unlinks while a database remains open.
// Include birth time where available to distinguish recycled inodes from live
// SQLite aliases. Unlike ctime, birth time survives renames.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct LiveFileIdentity {
#[cfg(any(test, feature = "test-support"))]
pub file: FileIdentity,
#[cfg(not(any(test, feature = "test-support")))]
file: FileIdentity,
#[cfg(any(test, feature = "test-support"))]
pub created: Option<std::time::SystemTime>,
#[cfg(not(any(test, feature = "test-support")))]
created: Option<std::time::SystemTime>,
}
}
impl LiveFileIdentity {
fn from_metadata(metadata: &std::fs::Metadata) -> Option<Self> {
Some(Self {
file: metadata_identity(metadata)?,
// Filesystems without birth times retain inode-only protection.
created: metadata.created().ok(),
})
}
fn of(path: &Path) -> Option<Self> {
#[cfg(any(test, feature = "test-support"))]
stat_probe::record_followed(path);
let (metadata, identity) = crate::file_identity::metadata(path).ok()?;
Some(Self {
file: native_identity(identity)?,
created: metadata.created().ok(),
})
}
}
pub(crate) fn candidate_metadata(path: &Path) -> std::io::Result<std::fs::Metadata> {
#[cfg(any(test, feature = "test-support"))]
stat_probe::record(path);
std::fs::symlink_metadata(path)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HazardKind {
/// Two live connections in this process are attached to two different files
/// at one path. This is the precondition for the WAL-index truncation
/// described at the top of this module.
Replaced,
/// A database file was deleted, renamed, or replaced while this process
/// still had a connection open on it.
MutatedWhileOpen,
}
impl HazardKind {
const fn summary(self) -> &'static str {
match self {
Self::Replaced => "two open connections are attached to different files at one path",
Self::MutatedWhileOpen => "database file changed while connections were open on it",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DatabaseHazard {
pub kind: HazardKind,
pub path: PathBuf,
pub detail: String,
}
impl DatabaseHazard {
pub fn message(&self) -> String {
format!(
"sqlite database hazard ({}): {} — {}",
self.kind.summary(),
self.path.display(),
self.detail
)
}
}
#[derive(Clone, Debug)]
struct Opener {
store: &'static str,
thread: String,
identity: Option<FileIdentity>,
}
impl Opener {
fn describe(&self) -> String {
match self.identity {
Some(identity) => format!("{} on {} attached to {identity}", self.store, self.thread),
None => format!(
"{} on {} (file identity unavailable)",
self.store, self.thread
),
}
}
}
#[rustfmt::skip]
test_support_visibility! {
#[derive(Debug, Default)]
struct OpenDatabase {
openers: Vec<Opener>,
identities: HashSet<LiveFileIdentity>,
}
}
#[rustfmt::skip]
test_support_visibility! {
fn open_databases() -> &'static Mutex<BTreeMap<PathBuf, OpenDatabase>> {
static DATABASES: OnceLock<Mutex<BTreeMap<PathBuf, OpenDatabase>>> = OnceLock::new();
DATABASES.get_or_init(|| Mutex::new(BTreeMap::new()))
}
}
#[derive(Default)]
struct LiveFiles {
names: HashMap<PathBuf, usize>,
identities: HashMap<LiveFileIdentity, usize>,
}
fn live_files() -> &'static RwLock<LiveFiles> {
static FILES: OnceLock<RwLock<LiveFiles>> = OnceLock::new();
FILES.get_or_init(RwLock::default)
}
#[rustfmt::skip]
test_support_visibility! {
fn database_files(key: &Path) -> [PathBuf; 4] {
let sidecar = |suffix| {
let mut path = key.as_os_str().to_os_string();
path.push(suffix);
PathBuf::from(path)
};
[
key.to_path_buf(),
sidecar("-wal"),
sidecar("-shm"),
sidecar("-journal"),
]
}
}
#[rustfmt::skip]
test_support_visibility! {
fn retain_identities(
database: &mut OpenDatabase,
identities: impl IntoIterator<Item = LiveFileIdentity>,
) {
let mut files = live_files().write().unwrap_or_else(|p| p.into_inner());
for identity in identities {
if database.identities.insert(identity) {
*files.identities.entry(identity).or_default() += 1;
}
}
}
}
fn reported() -> &'static Mutex<Vec<DatabaseHazard>> {
static REPORTED: OnceLock<Mutex<Vec<DatabaseHazard>>> = OnceLock::new();
REPORTED.get_or_init(|| Mutex::new(Vec::new()))
}
/// Resolve a path to the key this registry files it under.
///
/// Symlinks are followed so two spellings of one database agree, matching how
/// SQLite itself keys a database by the inode it ends up at. A path that names
/// nothing yet still resolves through its parent directory, so the key a
/// removal computes matches the key its connections registered under.
fn registry_key(path: &Path) -> PathBuf {
if let Ok(resolved) = std::fs::canonicalize(path) {
return resolved;
}
match (path.parent(), path.file_name()) {
(Some(parent), Some(name)) if !parent.as_os_str().is_empty() => {
std::fs::canonicalize(parent).map_or_else(|_| path.to_path_buf(), |dir| dir.join(name))
}
_ => path.to_path_buf(),
}
}
fn thread_label() -> String {
let current = std::thread::current();
match current.name() {
Some(name) => format!("thread {name}"),
None => format!("thread {:?}", current.id()),
}
}
fn crash_diagnostics_armed() -> bool {
static ARMED: OnceLock<bool> = OnceLock::new();
*ARMED.get_or_init(|| {
std::env::var_os("AFT_CAPTURE_CRASH_DIAGNOSTICS").as_deref() == Some(OsStr::new("1"))
})
}
fn report(hazard: DatabaseHazard) {
let message = hazard.message();
crate::slog_warn!("{message}");
if crash_diagnostics_armed() {
// The test run that arms fatal-signal diagnostics collects stderr, and a
// hazard reported here is the earlier event a later SIGBUS is downstream
// of, so the two land in one log next to each other.
write_stderr_line(&format!("\nAFT sqlite database hazard: {message}\n"));
}
let mut reported = reported()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if reported.len() >= RETAINED_HAZARDS {
reported.remove(0);
}
reported.push(hazard);
}
/// Write straight to the standard error descriptor.
///
/// Rust's test harness captures `eprintln!` and discards it for a test that
/// passes, and throws it away entirely when the process dies by signal. A
/// hazard is most valuable in exactly those two cases: a run that did not crash
/// but set the crash up, and the run that crashed. Writing to the descriptor
/// bypasses the capture, which is what the fatal-signal handler already does.
#[cfg(unix)]
fn write_stderr_line(line: &str) {
let bytes = line.as_bytes();
unsafe {
libc::write(
libc::STDERR_FILENO,
bytes.as_ptr().cast::<std::ffi::c_void>(),
bytes.len(),
);
}
}
#[cfg(not(unix))]
fn write_stderr_line(line: &str) {
eprint!("{line}");
}
/// Serialize SQLite opens with AFT file-set mutations. The staging database
/// keeps this gate while checking whether its file exists and calling the open
/// helper; reentrancy permits that nested call. Connection lifetimes do not hold
/// this gate; the registry protects live users.
fn filesystem_gate() -> &'static parking_lot::ReentrantMutex<()> {
static GATE: parking_lot::ReentrantMutex<()> = parking_lot::ReentrantMutex::new(());
&GATE
}
pub fn filesystem_guard() -> parking_lot::ReentrantMutexGuard<'static, ()> {
filesystem_gate().lock()
}
/// Record that a tracked connection has opened `path`, and return the key the
/// matching [`note_close`] must use.
///
/// The key is returned rather than recomputed at close time because the
/// database file may be gone by then, and a path that no longer resolves would
/// otherwise file the close under a different key than the open.
pub fn note_open(path: &Path, store: &'static str) -> PathBuf {
let key = registry_key(path);
let paths = database_files(&key);
let identities = paths.each_ref().map(|path| LiveFileIdentity::of(path));
let opener = Opener {
store,
thread: thread_label(),
identity: identities[0].map(|identity| identity.file),
};
let hazard = {
let mut databases = open_databases()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let entry = databases.entry(key.clone()).or_default();
if entry.openers.is_empty() {
let mut files = live_files().write().unwrap_or_else(|p| p.into_inner());
for path in paths {
*files.names.entry(path).or_default() += 1;
}
}
let hazard = replacement_hazard(&key, entry, &opener);
retain_identities(entry, identities.into_iter().flatten());
entry.openers.push(opener);
hazard
};
if let Some(hazard) = hazard {
report(hazard);
}
key
}
/// Record that a tracked connection opened under `key` has closed.
pub fn note_close(key: &Path, store: &'static str) {
let mut databases = open_databases()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let Some(entry) = databases.get_mut(key) else {
return;
};
if let Some(index) = entry
.openers
.iter()
.rposition(|opener| opener.store == store)
{
entry.openers.remove(index);
}
if entry.openers.is_empty() {
let mut files = live_files().write().unwrap_or_else(|p| p.into_inner());
for path in database_files(key) {
if let Some(count) = files.names.get_mut(&path) {
*count -= 1;
if *count == 0 {
files.names.remove(&path);
}
}
}
for identity in &entry.identities {
if let Some(count) = files.identities.get_mut(identity) {
*count -= 1;
if *count == 0 {
files.identities.remove(identity);
}
}
}
databases.remove(key);
}
}
fn replacement_hazard(key: &Path, entry: &OpenDatabase, opener: &Opener) -> Option<DatabaseHazard> {
let identity = opener.identity?;
let previous = entry
.openers
.iter()
.find(|held| held.identity.is_some_and(|held| held != identity))?;
Some(DatabaseHazard {
kind: HazardKind::Replaced,
path: key.to_path_buf(),
detail: format!(
"the already-open {} met a new {}; SQLite shares one WAL-index per path, \
so the newer connection truncates the WAL-index the older one has mapped",
previous.describe(),
opener.describe()
),
})
}
/// Number of registered connections at `path` or at another name for its inode.
/// Hold [`filesystem_guard`] across this query and any file-set mutation so an
/// opener cannot appear between checking the registry and changing the files.
pub fn registered_connections_for_key(key: &Path) -> usize {
open_databases()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.get(key)
.map_or(0, |entry| entry.openers.len())
}
pub fn open_connections(path: &Path) -> usize {
let key = registry_key(path);
let identity = identity_of(&key);
open_databases()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.iter()
.map(|(registered_path, entry)| {
entry
.openers
.iter()
.filter(|opener| {
registered_path == &key || identity.is_some() && opener.identity == identity
})
.count()
})
.sum()
}
#[rustfmt::skip]
test_support_visibility! {
/// Cheap name check for project walkers whose roots are already canonical.
pub(crate) fn is_registered_file_path(path: &Path) -> bool {
live_files()
.read()
.unwrap_or_else(|p| p.into_inner())
.names
.contains_key(path)
}
}
/// Source readers must also reject aliases to live databases and their
/// sidecars. `stat` inspects the inode without opening a descriptor, so it does
/// not release SQLite's process-wide file locks.
pub fn is_live_sqlite_file(path: &Path) -> bool {
if is_registered_file_path(path) {
return true;
}
#[cfg(any(test, feature = "test-support"))]
stat_probe::record(path);
let Ok((metadata, identity, links)) = crate::file_identity::metadata_with_link_count(path)
else {
return false;
};
let Some(file) = native_identity(identity) else {
return false;
};
is_live_identity(
LiveFileIdentity {
file,
created: metadata.created().ok(),
},
links,
)
}
fn is_live_identity(identity: LiveFileIdentity, links: u64) -> bool {
let known = || {
live_files()
.read()
.unwrap_or_else(|p| p.into_inner())
.identities
.contains_key(&identity)
};
if known() {
return true;
}
if links < 2 {
return false;
}
refresh_sidecar_identities();
known()
}
pub fn is_live_sqlite_file_with_metadata(
path: &Path,
metadata: Option<&std::fs::Metadata>,
) -> bool {
#[cfg(windows)]
{
// On Windows, std::fs::Metadata omits the file index; crate::file_identity
// reads it from a handle opened without data access.
let _ = metadata;
return is_live_sqlite_file(path);
}
#[cfg(not(windows))]
{
// A symlink's own inode and link count say nothing about SQLite's target.
// Resolve only this uncommon case; ordinary source reads need one stat.
if metadata.is_some_and(|metadata| metadata.file_type().is_symlink()) {
let key = registry_key(path);
if is_registered_file_path(&key) {
return true;
}
let target = std::fs::metadata(path).ok();
return is_live_sqlite_file_with_metadata(&key, target.as_ref());
}
let Some(metadata) = metadata else {
return false;
};
let Some(identity) = LiveFileIdentity::from_metadata(metadata) else {
return false;
};
#[cfg(unix)]
let links = {
use std::os::unix::fs::MetadataExt;
metadata.nlink()
};
#[cfg(not(unix))]
let links = 1;
is_live_identity(identity, links)
}
}
fn refresh_sidecar_identities() {
let paths = open_databases()
.lock()
.unwrap_or_else(|p| p.into_inner())
.keys()
.cloned()
.collect::<Vec<_>>();
// Never stat while holding the connection registry or the reader cache lock.
let refreshed = paths
.into_iter()
.map(|key| {
let identities = database_files(&key)[1..]
.iter()
.filter_map(|path| LiveFileIdentity::of(path))
.collect::<Vec<_>>();
(key, identities)
})
.collect::<Vec<_>>();
let mut databases = open_databases().lock().unwrap_or_else(|p| p.into_inner());
for (key, identities) in refreshed {
if let Some(database) = databases.get_mut(&key) {
retain_identities(database, identities);
}
}
}
/// Whether an already-open file is a live SQLite database or sidecar, judged
/// by the handle's own identity (`metadata` must come from the open handle):
/// its device and inode, plus its birth time where the filesystem records
/// one, exactly as the registry keys live files. Unlike the path checks above
/// there is no link-count shortcut: by the time a file is open, the names
/// that made it look innocent may already be gone. Birth time keeps a
/// recycled inode of an unlinked sidecar from refusing an unrelated file.
///
/// On Windows, std::fs::Metadata omits the file index. Use is_live_sqlite_file
/// there to obtain the identity through a metadata-only handle.
pub fn is_live_sqlite_handle(metadata: &std::fs::Metadata) -> bool {
let Some(identity) = LiveFileIdentity::from_metadata(metadata) else {
return false;
};
let known = || {
live_files()
.read()
.unwrap_or_else(|p| p.into_inner())
.identities
.contains_key(&identity)
};
if known() {
return true;
}
// Sidecars created after their database opened are learned only here.
#[cfg(unix)]
refresh_sidecar_identities();
known()
}
/// Report `action` if it is about to delete, rename, or replace the database
/// file at `path` while this process still has a connection open on it.
///
/// `action` names the caller in the report, so it should read as a description
/// of the operation, for example `"callgraph generation sweep"`.
pub fn guard_replacement(path: &Path, action: &str) {
let key = registry_key(path);
let detail = {
let databases = open_databases()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let Some(entry) = databases.get(&key) else {
return;
};
if entry.openers.is_empty() {
return;
}
let openers = entry
.openers
.iter()
.map(Opener::describe)
.collect::<Vec<_>>()
.join("; ");
format!("{action} ran while these connections were still open: [{openers}]")
};
report(DatabaseHazard {
kind: HazardKind::MutatedWhileOpen,
path: key,
detail,
});
}
/// Hazards reported for `path` so far, newest last.
pub fn hazards_for_path(path: &Path) -> Vec<DatabaseHazard> {
let key = registry_key(path);
reported()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.iter()
.filter(|hazard| hazard.path == key)
.cloned()
.collect()
}
/// Every hazard retained so far, newest last.
pub fn reported_hazards() -> Vec<DatabaseHazard> {
reported()
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
}
#[cfg(any(test, feature = "test-support"))]
pub mod stat_probe {
use super::*;
use std::cell::RefCell;
thread_local! {
static COUNTS: RefCell<Option<BTreeMap<PathBuf, usize>>> = const { RefCell::new(None) };
static CANDIDATES_ONLY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
pub fn record_followed(path: &Path) {
if !CANDIDATES_ONLY.with(|only| only.get()) {
record(path);
}
}
pub fn record(path: &Path) {
COUNTS.with(|counts| {
if let Some(counts) = counts.borrow_mut().as_mut() {
*counts.entry(path.to_path_buf()).or_default() += 1;
}
});
}
pub fn count(f: impl FnOnce()) -> BTreeMap<PathBuf, usize> {
struct Reset;
impl Drop for Reset {
fn drop(&mut self) {
COUNTS.with(|counts| *counts.borrow_mut() = None);
}
}
let _reset = Reset;
COUNTS.with(|counts| *counts.borrow_mut() = Some(BTreeMap::new()));
f();
COUNTS.with(|counts| counts.borrow_mut().take().unwrap())
}
}
#[cfg(test)]
mod tests {
#[cfg(unix)]
use super::*;
// Only the POSIX-only tests below open raw connections.
#[cfg(unix)]
use rusqlite::Connection;
#[cfg(unix)]
fn shm_path(path: &Path) -> PathBuf {
PathBuf::from(format!("{}-shm", path.display()))
}
/// The mechanism, stated as an executable fact about SQLite rather than as
/// prose: replace the database file at a path while a connection still has
/// that path's WAL-index mapped, and the next connection truncates the
/// WAL-index under the first one.
///
/// SQLite maps a WAL-index in 32 KiB regions and re-extends the file to
/// cover region 0 immediately after truncating it, so the visible damage is
/// the file shrinking back to one region while the first connection still
/// holds pointers into region 1. Reading through those pointers is a read
/// past the end of a file-backed mapping, which the kernel answers with a
/// page-aligned SIGBUS. That is why the fixture first grows the WAL past
/// the 4062 frames region 0 can index: with only region 0 mapped, the
/// re-extension hides the truncation behind a page of zeroes instead.
///
/// The first connection is deliberately never used or dropped after the
/// truncation: touching it is the fault. Leaking one handle for the rest of
/// the test binary is the price of observing the state safely.
// Windows refuses to unlink or rename a database while a connection holds
// it open, so the replaced-under-a-live-connection precondition cannot form
// there; the hazard this registry reports is a POSIX one.
#[cfg(unix)]
#[test]
fn replacing_the_database_file_truncates_the_wal_index_under_a_live_mapping() {
/// SQLite maps the WAL-index one 32 KiB region at a time.
const WAL_INDEX_REGION_BYTES: u64 = 32 * 1024;
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("replaced.sqlite");
let first = Connection::open(&path).expect("open first connection");
// A small page size keeps the WAL small in bytes while still producing
// the thousands of frames needed to reach the second WAL-index region.
first
.pragma_update(None, "page_size", 512)
.expect("small pages");
first
.pragma_update(None, "journal_mode", "WAL")
.expect("first connection WAL");
first
.pragma_update(None, "synchronous", "OFF")
.expect("unsynced fixture writes");
first
.pragma_update(None, "wal_autocheckpoint", 0)
.expect("no autocheckpoint");
first
.execute_batch("CREATE TABLE t(id INTEGER PRIMARY KEY, payload BLOB);")
.expect("seed");
// One transaction per row, so every commit appends WAL frames and the
// log grows past what a single WAL-index region can address.
let mut mapped_bytes = 0;
for id in 0..20_000_i64 {
first
.execute(
"INSERT INTO t(id, payload) VALUES (?1, zeroblob(400))",
[id],
)
.expect("append a WAL frame");
if id % 256 == 0 {
mapped_bytes = std::fs::metadata(shm_path(&path))
.expect("WAL-index exists")
.len();
if mapped_bytes > WAL_INDEX_REGION_BYTES {
break;
}
}
}
assert!(
mapped_bytes > WAL_INDEX_REGION_BYTES,
"fixture never mapped a second WAL-index region (got {mapped_bytes} bytes); \
without one the truncation is hidden by SQLite re-extending region 0"
);
let first_identity = identity_of(&path).expect("first database identity");
// Replace the database file at the same path, leaving the WAL-index
// exactly where it is. This is the shape being hunted: a new database
// file inode under an unchanged `-shm` inode.
std::fs::remove_file(&path).expect("remove the database file");
let second = Connection::open(&path).expect("open second connection");
second
.pragma_update(None, "journal_mode", "WAL")
.expect("second connection WAL");
second
.execute_batch("CREATE TABLE t(id INTEGER PRIMARY KEY);")
.expect("write through the replacement");
let second_identity = identity_of(&path).expect("second database identity");
assert_ne!(
first_identity, second_identity,
"fixture did not actually replace the database file"
);
let after_bytes = std::fs::metadata(shm_path(&path))
.expect("WAL-index still exists")
.len();
assert!(
after_bytes < mapped_bytes,
"the second connection did not truncate the WAL-index the first one has mapped \
(before={mapped_bytes} bytes, after={after_bytes} bytes)"
);
drop(second);
// Dropping `first` would make SQLite read the truncated mapping during
// its close-time checkpoint, so the handle is deliberately leaked.
std::mem::forget(first);
}
}