Debian Codegraph @

www/howtocorrupt.html

raw
1 <!DOCTYPE html>
2 <html><head>
3 <meta name="viewport" content="width=device-width, initial-scale=1.0">
4 <meta http-equiv="content-type" content="text/html; charset=UTF-8">
5 <link href="sqlite.css" rel="stylesheet">
6 <title>How To Corrupt An SQLite Database File</title>
7 <!-- path= -->
8 </head>
9 <body>
10 <div class=nosearch>
11 <a href="index.html">
12 <img class="logo" src="images/sqlite370_banner.gif" alt="SQLite" border="0">
13 </a>
14 <div><!-- IE hack to prevent disappearing logo --></div>
15 <div class="tagline desktoponly">
16 Small. Fast. Reliable.<br>Choose any three.
17 </div>
18 <div class="menu mainmenu">
19 <ul>
20 <li><a href="index.html">Home</a>
21 <li class='mobileonly'><a href="javascript:void(0)" onclick='toggle_div("submenu")'>Menu</a>
22 <li class='wideonly'><a href='about.html'>About</a>
23 <li class='desktoponly'><a href="docs.html">Documentation</a>
24 <li class='desktoponly'><a href="download.html">Download</a>
25 <li class='wideonly'><a href='copyright.html'>License</a>
26 <li class='desktoponly'><a href="support.html">Support</a>
27 <li class='desktoponly'><a href="prosupport.html">Purchase</a>
28 <li class='search' id='search_menubutton'>
29 <a href="javascript:void(0)" onclick='toggle_search()'>Search</a>
30 </ul>
31 </div>
32 <div class="menu submenu" id="submenu">
33 <ul>
34 <li><a href='about.html'>About</a>
35 <li><a href='docs.html'>Documentation</a>
36 <li><a href='download.html'>Download</a>
37 <li><a href='support.html'>Support</a>
38 <li><a href='prosupport.html'>Purchase</a>
39 </ul>
40 </div>
41 <div class="searchmenu" id="searchmenu">
42 <form method="GET" action="search">
43 <select name="s" id="searchtype">
44 <option value="d">Search Documentation</option>
45 <option value="c">Search Changelog</option>
46 </select>
47 <input type="text" name="q" id="searchbox" value="">
48 <input type="submit" value="Go">
49 </form>
50 </div>
51 </div>
52 <script>
53 function toggle_div(nm) {
54 var w = document.getElementById(nm);
55 if( w.style.display=="block" ){
56 w.style.display = "none";
57 }else{
58 w.style.display = "block";
59 }
60 }
61 function toggle_search() {
62 var w = document.getElementById("searchmenu");
63 if( w.style.display=="block" ){
64 w.style.display = "none";
65 } else {
66 w.style.display = "block";
67 setTimeout(function(){
68 document.getElementById("searchbox").focus()
69 }, 30);
70 }
71 }
72 function div_off(nm){document.getElementById(nm).style.display="none";}
73 window.onbeforeunload = function(e){div_off("submenu");}
74 /* Disable the Search feature if we are not operating from CGI, since */
75 /* Search is accomplished using CGI and will not work without it. */
76 if( !location.origin || !location.origin.match || !location.origin.match(/http/) ){
77 document.getElementById("search_menubutton").style.display = "none";
78 }
79 /* Used by the Hide/Show button beside syntax diagrams, to toggle the */
80 function hideorshow(btn,obj){
81 var x = document.getElementById(obj);
82 var b = document.getElementById(btn);
83 if( x.style.display!='none' ){
84 x.style.display = 'none';
85 b.innerHTML='show';
86 }else{
87 x.style.display = '';
88 b.innerHTML='hide';
89 }
90 return false;
91 }
92 var antiRobot = 0;
93 function antiRobotGo(){
94 if( antiRobot!=3 ) return;
95 antiRobot = 7;
96 var j = document.getElementById("mtimelink");
97 if(j && j.hasAttribute("data-href")) j.href=j.getAttribute("data-href");
98 }
99 function antiRobotDefense(){
100 document.body.onmousedown=function(){
101 antiRobot |= 2;
102 antiRobotGo();
103 document.body.onmousedown=null;
104 }
105 document.body.onmousemove=function(){
106 antiRobot |= 2;
107 antiRobotGo();
108 document.body.onmousemove=null;
109 }
110 setTimeout(function(){
111 antiRobot |= 1;
112 antiRobotGo();
113 }, 100)
114 antiRobotGo();
115 }
116 antiRobotDefense();
117 </script>
118 <div class=fancy>
119 <div class=nosearch>
120 <div class="fancy_title">
121 How To Corrupt An SQLite Database File
122 </div>
123 <div class="fancy_toc">
124 <a onclick="toggle_toc()">
125 <span class="fancy_toc_mark" id="toc_mk">&#x25ba;</span>
126 Table Of Contents
127 </a>
128 <div id="toc_sub"><div class="fancy-toc1"><a href="#_file_overwrite_by_a_rogue_thread_or_process">1. File overwrite by a rogue thread or process</a></div>
129 <div class="fancy-toc2"><a href="#_continuing_to_use_a_file_descriptor_after_it_has_been_closed">1.1. Continuing to use a file descriptor after it has been closed</a></div>
130 <div class="fancy-toc2"><a href="#_backup_or_restore_while_a_transaction_is_active">1.2. Backup or restore while a transaction is active</a></div>
131 <div class="fancy-toc2"><a href="#_deleting_a_hot_journal">1.3. Deleting a hot journal</a></div>
132 <div class="fancy-toc2"><a href="#_mispairing_database_files_and_hot_journals_">1.4. Mispairing database files and hot journals </a></div>
133 <div class="fancy-toc1"><a href="#_file_locking_problems">2. File locking problems</a></div>
134 <div class="fancy-toc2"><a href="#_filesystems_with_broken_or_missing_lock_implementations">2.1. Filesystems with broken or missing lock implementations</a></div>
135 <div class="fancy-toc2"><a href="#_posix_advisory_locks_canceled_by_a_separate_thread_doing_close_">2.2. Posix advisory locks canceled by a separate thread doing close()</a></div>
136 <div class="fancy-toc3"><a href="#multiple_copies_of_sqlite_linked_into_the_same_application">2.2.1. Multiple copies of SQLite linked into the same application</a></div>
137 <div class="fancy-toc2"><a href="#_two_processes_using_different_locking_protocols">2.3. Two processes using different locking protocols</a></div>
138 <div class="fancy-toc2"><a href="#_unlinking_or_renaming_a_database_file_while_in_use">2.4. Unlinking or renaming a database file while in use</a></div>
139 <div class="fancy-toc2"><a href="#_multiple_links_to_the_same_file">2.5. Multiple links to the same file</a></div>
140 <div class="fancy-toc2"><a href="#_carrying_an_open_database_connection_across_a_fork_">2.6. Carrying an open database connection across a fork() </a></div>
141 <div class="fancy-toc1"><a href="#_failure_to_sync">3. Failure to sync</a></div>
142 <div class="fancy-toc2"><a href="#_disk_drives_that_do_not_honor_sync_requests">3.1. Disk drives that do not honor sync requests</a></div>
143 <div class="fancy-toc2"><a href="#_disabling_sync_using_pragmas">3.2. Disabling sync using PRAGMAs</a></div>
144 <div class="fancy-toc1"><a href="#_disk_drive_and_flash_memory_failures">4. Disk Drive and Flash Memory Failures</a></div>
145 <div class="fancy-toc2"><a href="#_non_powersafe_flash_memory_controllers">4.1. Non-powersafe flash memory controllers</a></div>
146 <div class="fancy-toc2"><a href="#_fake_capacity_usb_sticks">4.2. Fake capacity USB sticks</a></div>
147 <div class="fancy-toc1"><a href="#_memory_corruption">5. Memory corruption</a></div>
148 <div class="fancy-toc1"><a href="#_other_operating_system_problems">6. Other operating system problems</a></div>
149 <div class="fancy-toc2"><a href="#_linux_threads">6.1. Linux Threads</a></div>
150 <div class="fancy-toc2"><a href="#_failures_of_mmap_on_qnx">6.2. Failures of mmap() on QNX</a></div>
151 <div class="fancy-toc2"><a href="#_filesystem_corruption">6.3. Filesystem Corruption</a></div>
152 <div class="fancy-toc1"><a href="#sqlite_configuration_errors">7. SQLite Configuration Errors</a></div>
153 <div class="fancy-toc1"><a href="#_bugs_in_sqlite">8. Bugs in SQLite</a></div>
154 <div class="fancy-toc2"><a href="#_false_corruption_reports_due_to_database_shrinkage">8.1. False corruption reports due to database shrinkage</a></div>
155 <div class="fancy-toc2"><a href="#_corruption_following_switches_between_rollback_and_wal_modes">8.2. Corruption following switches between rollback and WAL modes</a></div>
156 <div class="fancy-toc2"><a href="#_i_o_error_while_obtaining_a_lock_leads_to_corruption">8.3. I/O error while obtaining a lock leads to corruption</a></div>
157 <div class="fancy-toc2"><a href="#_database_pages_leak_from_the_free_page_list">8.4. Database pages leak from the free page list</a></div>
158 <div class="fancy-toc2"><a href="#_corruption_following_alternating_writes_from_3_6_and_3_7">8.5. Corruption following alternating writes from 3.6 and 3.7</a></div>
159 <div class="fancy-toc2"><a href="#_race_condition_in_recovery_on_windows_systems">8.6. Race condition in recovery on Windows systems</a></div>
160 <div class="fancy-toc2"><a href="#_boundary_value_error_in_the_secondary_journals_used_by_nested_transactions">8.7. Boundary value error in the secondary journals used by nested transactions</a></div>
161 </div>
162 </div>
163 <script>
164 function toggle_toc(){
165 var sub = document.getElementById("toc_sub")
166 var mk = document.getElementById("toc_mk")
167 if( sub.style.display!="block" ){
168 sub.style.display = "block";
169 mk.innerHTML = "&#x25bc;";
170 } else {
171 sub.style.display = "none";
172 mk.innerHTML = "&#x25ba;";
173 }
174 }
175 </script>
176 </div>
177
178
179
180
181 <h2 style="margin-left:1.0em" notoc="1" id="overview"> Overview</h2>
182
183 <p>An SQLite database is highly resistant to corruption.
184 If an application crash, or an operating-system crash, or even
185 a power failure occurs in the middle of a transaction, the partially
186 written transaction should be automatically rolled back the next time
187 the database file is accessed. The recovery process is fully
188 automatic and does not require any action on the part of the user
189 or the application.
190 </p>
191
192 <p>Though SQLite is resistant to database corruption, it is not immune.
193 This document describes the various ways that an SQLite database might
194 go corrupt.</p>
195
196 <h1 id="_file_overwrite_by_a_rogue_thread_or_process"><span>1. </span> File overwrite by a rogue thread or process</h1>
197
198 <p>SQLite database files are ordinary disk files.
199 That means that any process can open the file and
200 overwrite it with garbage. There is nothing that the SQLite
201 library can do to defend against this.</p>
202
203 <a name="stalefd"></a>
204
205 <h2 id="_continuing_to_use_a_file_descriptor_after_it_has_been_closed"><span>1.1. </span> Continuing to use a file descriptor after it has been closed</h2>
206
207 <p>We have seen multiple cases where a file descriptor was open on a file,
208 then that file descriptor was closed and reopened on an SQLite database.
209 Later, some other thread continued to write into the
210 old file descriptor, not realizing that the original file had been closed
211 already. But because the file descriptor had been reopened by SQLite,
212 the information that was intended to go into the original file ended up
213 overwriting parts of the SQLite database, leading to corruption of the
214 database.</p>
215
216 <p>One example of this occurred circa 2013-08-30 on the canonical repository
217 for the <a href="http://www.fossil-scm.org/">Fossil DVCS</a>. In that event,
218 file descriptor 2 (standard error) was being erroneously closed (by
219 <a href="http://www.stunnel.org/">stunnel</a>, we suspect) prior to
220 <a href="c3ref/open.html">sqlite3_open_v2()</a> so that the file descriptor used for the
221 repository database file was 2. Later, an application
222 bug caused an assert() statement to emit
223 an error message by invoking write(2,...). But since file descriptor 2 was
224 now connected to a database file, the error message
225 overwrote part of the database. To guard against this kind of problem,
226 SQLite <a href="releaselog/3_8_1.html">version 3.8.1</a> (2013-10-17)
227 and later refuse to use low-numbered file descriptors
228 for database files.
229 (See <a href="compile.html#minimum_file_descriptor">SQLITE_MINIMUM_FILE_DESCRIPTOR</a> for additional information.)</p>
230
231 <p>Another example of corruption caused by using a closed file
232 descriptor was
233 <a href="https://code.facebook.com/posts/313033472212144/debugging-file-corruption-on-ios/">reported by facebook engineers</a> in a blog post on 2014-08-12.</p>
234
235 <p>Another example of this error was reported against
236 <a href="https://fossil-scm.org/">Fossil</a> on 2019-07-11. A file descriptor would
237 be opened for debugging output, but then closed and reopened by SQLite.
238 But the debugging logic continued to write into the original file
239 descriptor. See the
240 <a href="https://fossil-scm.org/forum/forumpost/c51b9a1169">forum discussion</a>
241 for the bug report and a link to the fix.
242
243 </p><h2 id="_backup_or_restore_while_a_transaction_is_active"><span>1.2. </span> Backup or restore while a transaction is active</h2>
244
245 <p>Systems that run automatic backups in the background might try to
246 make a backup copy of an SQLite database file while it is in the middle
247 of a transaction. The backup copy then might contain some old and some
248 new content, and thus be corrupt.</p>
249
250 <p>The best approach to make reliable backup copies of an SQLite database
251 is to make use of the <a href="backup.html">backup API</a> that is part of the SQLite library.
252 Failing that, it is safe to make a copy of an SQLite database file as long
253 as there are no transactions in progress by any process. If the previous
254 transaction failed, then it is important that any rollback journal
255 (the <tt>*-journal</tt> file) or write-ahead log (the <tt>*-wal</tt> file)
256 be copied together with the database file itself.</p>
257
258 <a name="delhotjrnl"></a>
259
260 <h2 id="_deleting_a_hot_journal"><span>1.3. </span> Deleting a hot journal</h2>
261
262 <p>SQLite normally stores all content in a single disk file. However,
263 while performing a transaction, information necessary to recover the
264 database following a crash or power failure is stored in auxiliary
265 journal files. Such journal files are described as <a href="fileformat2.html#hotjrnl">"hot"</a>.
266 The journal files have the same name as the
267 original database file with the addition
268 of <tt>-journal</tt> or <tt>-wal</tt> suffix.</p>
269
270 <p>SQLite must see the journal files in order to recover from a crash
271 or power failure. If the <a href="fileformat2.html#hotjrnl">hot journal files</a> are moved, deleted, or renamed
272 after a crash or power failure, then automatic recovery will not work
273 and the database may go corrupt.</p>
274
275 <p>Another manifestation of this problem is
276 <a href="shortnames.html#db83corrupt">database corruption caused by inconsistent use of 8+3 filenames</a>.</p>
277
278 <a name="roguejrnl"></a>
279
280 <h2 id="_mispairing_database_files_and_hot_journals_"><span>1.4. </span> Mispairing database files and hot journals </h2>
281
282 <p> The previous example is a specific case of a more general problem:
283 The state of an SQLite database is controlled by both the
284 database file and the journal file. In a quiescent state, the journal
285 file does not exist and only the database file matters.
286 But if the journal file does exist, it must be
287 kept together with the database to avoid corruption. The following
288 actions are all likely to lead to corruption:
289 </p><ul>
290 <li> Swapping journal files between two different databases.
291 </li><li> Overwritting a journal file with a different journal file.
292 </li><li> Moving a journal file from one database to another.
293 </li><li> Copying a database file without also copying its journal.
294 </li><li> Overwriting a database file with another without also
295 deleting any hot journal associated with the original database.
296 </li></ul>
297
298 <h1 id="_file_locking_problems"><span>2. </span> File locking problems</h1>
299
300 <p>SQLite uses file locks on the database file, and on the
301 <a href="wal.html">write-ahead log</a> or <a href="wal.html">WAL</a> file, to coordinate access between concurrent
302 processes. Without coordination, two threads or processes might try
303 to make incompatible changes to a database file at the same time,
304 resulting in database corruption.</p>
305
306 <h2 id="_filesystems_with_broken_or_missing_lock_implementations"><span>2.1. </span> Filesystems with broken or missing lock implementations</h2>
307
308 <p>SQLite depends on the underlying filesystem to do locking as the
309 documentation says it will. But some filesystems contain bugs in their
310 locking logic such that the locks do not always behave as advertised.
311 This is especially true of network filesystems and NFS in particular.
312 If SQLite is used on a filesystem where the locking primitives contain
313 bugs, and if two or more threads or processes try to access the same
314 database at the same time, then database corruption might result.</p>
315
316 <a name="posix_close_bug"></a>
317
318 <h2 id="_posix_advisory_locks_canceled_by_a_separate_thread_doing_close_"><span>2.2. </span> Posix advisory locks canceled by a separate thread doing close()</h2>
319
320 <p>The default locking mechanism used by SQLite on unix platforms is
321 POSIX advisory locking. Unfortunately, POSIX advisory locking has design
322 quirks that make it prone to misuse and failure. In particular, any
323 thread in the same process with a file descriptor that is holding a POSIX
324 advisory lock can override that lock using a different file descriptor.
325 One particularly pernicious problem is that the <tt>close()</tt> system
326 call will cancel all POSIX advisory locks on the same file for all
327 threads and all file descriptors in the process.</p>
328
329 <p>So, for example, suppose a multi-thread process has
330 two or more threads with separate SQLite database connections to the
331 same database file. Then a third thread comes along and wants to read
332 something out of that same database file on its own, without using the
333 SQLite library.
334 The third thread does an <tt>open()</tt>, a <tt>read()</tt> and then
335 a <tt>close()</tt>.
336 One would think this would be harmless.
337 But the <tt>close()</tt> system call caused the
338 locks held on the database by all the other threads to be dropped. Those
339 other threads have no way of knowing that their locks have just been
340 trashed (POSIX does not provide any mechanism to determine this) and so
341 they keep on running under the assumption that their locks are still valid.
342 This can lead to two or more threads or processes trying to write to the
343 database at the same time, resulting in database corruption.</p>
344
345 <p>Note that it is perfectly safe for two or more threads to access the
346 same SQLite database file using the SQLite library. The unix drivers for
347 SQLite know about the POSIX advisory locking quirks and work around them.
348 This problem only arises when a thread tries to bypass the SQLite library
349 and read the database file directly.</p>
350
351 <h3 id="multiple_copies_of_sqlite_linked_into_the_same_application"><span>2.2.1. </span>Multiple copies of SQLite linked into the same application</h3>
352
353 <p>As pointed out in the previous paragraph, SQLite takes steps to work
354 around the quirks of POSIX advisory locking. Part of that work-around involves
355 keeping a global list (mutex protected) of open SQLite database files.
356 But, if multiple copies of SQLite are linked into the same application,
357 then there will be multiple instances of this global list.
358 Database connections opened using one copy of the SQLite library
359 will be unaware of database connections opened using the other copy,
360 and will be unable to work around the POSIX advisory locking quirks.
361 A <tt>close()</tt> operation on one connection might unknowingly
362 clear the locks on a different database connection, leading to database
363 corruption.</p>
364
365 <p>The scenario above sounds far-fetched.
366 But the SQLite developers are aware of at
367 least one commercial product that was released
368 with exactly this bug. The vendor came to the SQLite developers seeking
369 help in tracking down some infrequent database corruption issues they were
370 seeing on Linux and Mac. The problem was eventually traced to the
371 fact that the application was linking against two separate copies of SQLite.
372 The solution was to change the application build procedures to link against
373 just one copy of SQLite instead of two.</p>
374
375 <h2 id="_two_processes_using_different_locking_protocols"><span>2.3. </span> Two processes using different locking protocols</h2>
376
377 <p>The default locking mechanism used by SQLite on unix platforms is
378 POSIX advisory locking, but there are other options. By selecting an
379 alternative <a href="c3ref/vfs.html">sqlite3_vfs</a> using the <a href="c3ref/open.html">sqlite3_open_v2()</a> interface, an
380 application can make use of other locking protocols that might be more
381 appropriate to certain filesystems. For example, dot-file locking might
382 be select for use in an application that has to run on an NFS filesystem
383 that does not support POSIX advisory locking.</p>
384
385 <p>It is important that all connections to the same database file use
386 the same locking protocol.
387 If one application is using POSIX advisory locks and another application
388 is using dot-file locking, then the two applications will not see each
389 other's locks and will not be able to coordinate database access, possibly
390 leading to database corruption.</p>
391
392 <a name="unlink"></a>
393
394 <h2 id="_unlinking_or_renaming_a_database_file_while_in_use"><span>2.4. </span> Unlinking or renaming a database file while in use</h2>
395
396 <p>If two processes have open connections to the same database file and
397 one process closes its connection, unlinks the file, then creates a new
398 database file in its place with the same name and reopens the new file,
399 then the two processes will be talking to different database files with
400 the same name. (Note that this is only possible on Posix and Posix-like
401 systems that permit a file to be unlinked while it is still open for
402 reading and writing. Windows does not allow this to occur.)
403 Since rollback journals and WAL files are based on the name of the database
404 file, the two different database files will share the same rollback
405 journal or WAL file. A rollback or recovery for one of the databases
406 might use content from the other database, resulting in corruption.
407 A similar problem occurs if a database file is renamed while it is
408 opened and a new file is created with the old name.</p>
409
410 <p>In other words, unlinking or renaming an open database file
411 results in behavior that is undefined and probably undesirable.</p>
412
413 <p>Beginning with SQLite <a href="releaselog/3_7_17.html">version 3.7.17</a> (2013-05-20),
414 the unix OS interface will
415 send SQLITE_WARNING messages to the <a href="errlog.html">error log</a> if a database file is unlinked
416 while it is still in use.</p>
417
418 <a name="alias"></a>
419
420 <h2 id="_multiple_links_to_the_same_file"><span>2.5. </span> Multiple links to the same file</h2>
421
422 <p>If a single database file has multiple links (either hard or soft links)
423 then that is just another way of saying that the file has multiple names.
424 If two or more processes open the database using different names, then
425 they will use different rollback journals and WAL files. That means that
426 if one process crashes, the other process will be unable to recover the
427 transaction in progress because it will be looking in the wrong place
428 for the appropriate journal.</p>
429
430 <p>In other words, opening and using a database file that has two or
431 more names results in behavior that is undefined and probably undesirable.</p>
432
433 <p>Beginning with SQLite <a href="releaselog/3_7_17.html">version 3.7.17</a> (2013-05-20),
434 the unix OS interface will
435 send SQLITE_WARNING messages to the <a href="errlog.html">error log</a> if a database file has
436 multiple hard links.</p>
437
438 <p>Beginning with SQLite <a href="releaselog/3_10_0.html">version 3.10.0</a> (2016-01-06),
439 the unix OS interface will
440 attempt to resolve symbolic links and open the database file by its
441 canonical name. Prior to version 3.10.0, opening a database file
442 through a symbolic link was similar to opening a database file
443 that had multiple hard links and resulted in undefined behavior.</p>
444
445 <a name="fork"></a>
446
447 <h2 id="_carrying_an_open_database_connection_across_a_fork_"><span>2.6. </span> Carrying an open database connection across a fork() </h2>
448
449 <p> Do not open an SQLite database connection, then fork(), then try
450 to use that database connection in the child process. All kinds of
451 locking problems will result and you can easily end up with a corrupt
452 database. SQLite is not designed to support that kind of behavior.
453 Any database connection that is used in a child process must be opened
454 in the child process, not inherited from the parent.
455
456 </p><p> Do not even call <a href="c3ref/close.html">sqlite3_close()</a> on a database connection from a
457 child process if the connection was opened in the parent. It is safe
458 to close the underlying file descriptor, but the <a href="c3ref/close.html">sqlite3_close()</a>
459 interface might invoke cleanup activities that will delete content out
460 from under the parent, leading to errors and perhaps even database
461 corruption.
462
463 </p><h1 id="_failure_to_sync"><span>3. </span> Failure to sync</h1>
464
465 <p>In order to guarantee that database files are always consistent, SQLite
466 will occasionally ask the operating system to flush all pending writes to
467 persistent storage then wait for that flush to complete. This is
468 accomplished using the <tt>fsync()</tt> system call under unix and
469 <tt>FlushFileBuffers()</tt> under Windows. We call this flush of
470 pending writes a "sync".</p>
471
472 <p>Actually, if one is only concerned with atomic and consistent writes and
473 is willing to forego durable writes, the sync operation does not need
474 to wait until the content is completely stored on persistent media. Instead,
475 the sync operation can be thought of as an I/O barrier. As long as all
476 writes that occur before the sync are completed before any write that happens
477 after the sync, no database corruption will occur. If sync is operating as
478 an I/O barrier and not as a true sync, then a power failure or system crash
479 might cause one or more previously committed transactions to roll back
480 (in violation of the "durable" property of "ACID") but the database will at
481 least continue to be consistent, and that is what most people care about.</p>
482
483 <h2 id="_disk_drives_that_do_not_honor_sync_requests"><span>3.1. </span> Disk drives that do not honor sync requests</h2>
484
485 <p>Unfortunately, most consumer-grade mass storage devices lie about
486 syncing. Disk drives will report that content is safely on persistent
487 media as soon as it reaches the track buffer and before actually being
488 written to oxide. This makes the disk drives seem to operate faster
489 (which is vitally important to the manufacturer so that they can show
490 good benchmark numbers in trade magazines). And in fairness, the lie
491 normally causes no harm, as long as there is no power loss or hard reset
492 prior to the track buffer actually being written to oxide. But if a
493 power loss or hard reset does occur, and if that results in content that
494 was written after a sync reaching oxide while content written before
495 the sync is still in a track buffer, then database corruption can occur.</p>
496
497 <p>USB flash memory sticks seem to be especially pernicious liars
498 regarding sync requests. One can easily see this by committing a large
499 transaction to an SQLite database on a USB memory stick. The COMMIT
500 command will return relatively quickly, indicating that the memory stick
501 has told the operating system and the operating system has told SQLite that
502 all content is safely in persistent storage, and yet the LED on the end
503 of the memory stick will continue flashing for several more seconds.
504 Pulling out the memory stick while the LED is still flashing will frequently
505 result in database corruption.</p>
506
507 <p>Note that SQLite must believe whatever the operating system and hardware
508 tell it about the status of sync requests. There is no way for SQLite to
509 detect that either is lying and that writes might be occurring out-of-order.
510 However, SQLite in <a href="wal.html">WAL mode</a> is far more forgiving of
511 out-of-order writes than in the default rollback journal modes. In WAL
512 mode, the only time that a failed sync operation can cause database corruption
513 is during a <a href="wal.html#ckpt">checkpoint</a> operation. A sync failure during a COMMIT might
514 result in loss of durability but not in a corrupt database file. Hence,
515 one line of defense against database corruption due to failed sync operations
516 is to use SQLite in WAL mode and to checkpoint as infrequently as possible.</p>
517
518 <h2 id="_disabling_sync_using_pragmas"><span>3.2. </span> Disabling sync using PRAGMAs</h2>
519
520 <p>The sync operations that SQLite performs to help ensure integrity
521 can be disabled at run-time using the <a href="pragma.html#pragma_synchronous">synchronous pragma</a>. By setting
522 PRAGMA synchronous=OFF, all sync operations are omitted. This makes
523 SQLite seem to run faster, but it also allows the operating system to freely
524 reorder writes, which could result in database corruption if a power failure
525 or hard reset occurs prior to all content reaching persistent storage.</p>
526
527 <p>For maximum reliability and for robustness against database corruption,
528 SQLite should always be run with its default synchronous setting of FULL.</p>
529
530 <a name="hardwarefault"></a>
531
532 <h1 id="_disk_drive_and_flash_memory_failures"><span>4. </span> Disk Drive and Flash Memory Failures</h1>
533
534 <p>An SQLite database can become corrupt if the file content changes
535 due to a disk drive or flash memory failure. It is very rare, but disks
536 will occasionally flip a bit in the middle of a sector.</p>
537
538 <h2 id="_non_powersafe_flash_memory_controllers"><span>4.1. </span> Non-powersafe flash memory controllers</h2>
539
540 <p>We are told that in some flash memory controllers the wear-leveling logic
541 can cause random filesystem damage if power is interrupted during a write.
542 This can manifest, for example, as random changes in the middle of a file
543 that was not even open at the time of the power loss. So, for example,
544 a device would be writing content into an MP3 file in flash memory when a
545 power loss occurs, and that could result in an SQLite database being
546 corrupted even though the database was not even in use at the time of the
547 power loss.</p>
548
549 <a name="fakeusb"></a>
550
551 <h2 id="_fake_capacity_usb_sticks"><span>4.2. </span> Fake capacity USB sticks</h2>
552
553 <p>There are many fraudulent USB sticks in circulation that report to have
554 a high capacity (ex: 8GB) but are really only capable of storing a much
555 smaller amount (ex: 1GB). Attempts to write on these devices will
556 often result in unrelated files being overwritten. Any use of a fraudulent
557 flash memory device can easily lead to database corruption, therefore.
558 Internet searches such as "fake capacity usb" will turn up lots of
559 disturbing information about this problem.
560
561 </p><h1 id="_memory_corruption"><span>5. </span> Memory corruption</h1>
562
563 <p>SQLite is a C-library that runs in the same address space as the
564 application that it serves. That means that stray pointers, buffer
565 overruns, heap corruption, or other malfunctions in the application can
566 corrupt internal SQLite data structure and ultimately result in a
567 corrupt database file. Normally these kinds of problems manifest themselves
568 as segfaults prior to any database corruption occurring, but there have
569 been instances where application code errors have caused SQLite to
570 malfunction subtly so as to corrupt the database file rather than
571 panicking.</p>
572
573 <p>The memory corruption problem becomes more acute when
574 using <a href="mmap.html">memory-mapped I/O</a>.
575 When all or part of the database file is mapped into the application's
576 address space, then a stray pointer that overwrites any part of that
577 mapped space will immediately corrupt the database file, without
578 requiring the application to do a subsequent write() system call.</p>
579
580 <h1 id="_other_operating_system_problems"><span>6. </span> Other operating system problems</h1>
581
582 <p>Sometimes operating systems will exhibit non-standard behavior which
583 can lead to problems. Sometimes this non-standard behavior is deliberate,
584 and sometimes it is a mistake in the implementation. But in any event,
585 if the operating performs differently from they way SQLite expects it to
586 perform, the possibility of database corruption exists.</p>
587
588 <h2 id="_linux_threads"><span>6.1. </span> Linux Threads</h2>
589
590 <p>Some older versions of Linux used the LinuxThreads library for thread
591 support. LinuxThreads is similar to Pthreads, but is subtly different
592 with respect to handling of POSIX advisory locks. SQLite versions
593 2.2.3 through 3.6.23 recognized that LinuxThreads were being used at
594 runtime and took appropriate action to work around the non-standard
595 behavior of LinuxThreads. But most modern Linux implementations make
596 use of the newer, and correct, NPTL implementation of Pthreads. Beginning
597 with SQLite <a href="releaselog/3_7_0.html">version 3.7.0</a> (2010-07-21), the use of NPTL is assumed.
598 No checks are
599 made. Hence, recent versions of SQLite will subtly malfunction and may
600 corrupt database files if used in multi-threaded application that run
601 on older linux systems that make use of LinuxThreads.</p>
602
603 <h2 id="_failures_of_mmap_on_qnx"><span>6.2. </span> Failures of mmap() on QNX</h2>
604
605 <p>There exists some subtle problem with mmap() on QNX such that making
606 a second mmap() call against a single file descriptor can cause
607 the memory obtained from the first mmap() call to be zeroed. SQLite on
608 unix uses mmap() to create a shared memory region for transaction
609 coordination in <a href="wal.html">WAL mode</a>, and it will call mmap() multiple times
610 for large transactions. The QNX mmap() has been demonstrated to corrupt
611 database file under that scenario. QNX engineers are aware of this problem
612 and are working on a solution; the problem may have already been fixed by
613 the time you read this.</p>
614
615 <p>When running on QNX, it is recommended that <a href="mmap.html">memory-mapped I/O</a> never
616 be used. Furthermore, to use <a href="wal.html">WAL mode</a>, it is recommended that applications
617 employ the <a href="pragma.html#pragma_locking_mode">exclusive locking mode</a> in order to
618 use <a href="wal.html#noshm">WAL without shared memory</a>.
619
620
621 <a name="fscorruption"></a>
622
623 </p><h2 id="_filesystem_corruption"><span>6.3. </span> Filesystem Corruption</h2>
624
625 <p>Since SQLite databases are ordinary disk files, any malfunction in the
626 filesystem can corrupt the database. Filesystems in modern operating systems
627 are very reliable, but errors do still occur. For example, on 2013-10-01
628 the SQLite database that holds the
629 <a href="http://wiki.tcl-lang.org/">Wiki for Tcl/Tk</a> went corrupt a few days
630 after the host computer was moved to a dodgy build of the (linux) kernel
631 that had issues in the filesystem layer. In that event, the filesystem
632 eventually became so badly corrupted that the machine was unusable, but
633 the earliest symptom of trouble was the corrupted SQLite database.</p>
634
635 <a name="cfgerr"></a>
636
637 <h1 id="sqlite_configuration_errors"><span>7. </span>SQLite Configuration Errors</h1>
638
639 <p>SQLite has many built-in protections against database corruption.
640 But many of these protections can be disabled by configuration options.
641 If protections are disabled, database corruption may occur.
642
643 </p><p>The following are examples of disabling the built-in protection
644 mechanisms of SQLite:
645
646 </p><ul>
647 <li><p>Setting <a href="pragma.html#pragma_synchronous">PRAGMA synchronous=OFF</a> can cause the database to
648 go corrupt if there is an operating-system crash or power failure,
649 though this setting is safe from damage due to application crashes.
650
651 </p></li><li><p>Changing the <a href="pragma.html#pragma_schema_version">PRAGMA schema_version</a> while other database
652 connections are open.
653
654 </p></li><li><p>Using <a href="pragma.html#pragma_journal_mode">PRAGMA journal_mode=OFF</a> or <a href="pragma.html#pragma_journal_mode">PRAGMA journal_mode=MEMORY</a>
655 and taking an application crash in the middle of a write transaction.
656
657 </p></li><li><p>Setting <a href="pragma.html#pragma_writable_schema">PRAGMA writable_schema=ON</a> and then changing the
658 database schema using DML statements can render the database completely
659 unreadable, if not done carefully.
660 </p></li></ul>
661
662 <h1 id="_bugs_in_sqlite"><span>8. </span> Bugs in SQLite</h1>
663
664 <p>SQLite is <a href="testing.html">very carefully tested</a> to help ensure that it is
665 as bug-free as possible. Among the many tests that are carried out for
666 every SQLite version are tests that simulate power failures, I/O errors,
667 and out-of-memory (OOM) errors and verify that no database corruption occurs
668 during any of these events. SQLite is also field-proven with approximately
669 two billion active deployments with no serious problems.</p>
670
671 <p>Nevertheless, no software is 100% perfect. There have been a few
672 historical bugs in SQLite (now fixed) that could cause database corruption.
673 And there may be yet a few more that remain undiscovered. Because of the
674 extensive testing and widespread use of SQLite, bugs that result in
675 database corruption tend to be very obscure. The likelihood
676 of an application encountering an SQLite bug is small. To illustrate this,
677 an account is given below
678 of all database-corruption bugs found in SQLite during the
679 four-year period from 2009-04-01 to 2013-04-15.
680 This account should give the reader an intuitive sense of the
681 kinds of bugs in SQLite that manage to slip through testing procedures
682 and make it into a release.</p>
683
684
685 <h2 id="_false_corruption_reports_due_to_database_shrinkage"><span>8.1. </span> False corruption reports due to database shrinkage</h2>
686
687 <p>If a database is written by SQLite version 3.7.0 or later and then
688 written again by SQLite version 3.6.23 or earlier in such a way as to
689 make the size of the database file decrease, then the next time that
690 SQLite version 3.7.0 access the database file, it might report that the
691 database file is corrupt. The database file is not really corrupt, however.
692 Version 3.7.0 was simply being overly zealous in its corruption detection.</p>
693
694 <p>The problem was fixed on 2011-02-20. The fix first appears in
695 SQLite <a href="releaselog/3_7_6.html">version 3.7.6</a> (2011-04-12).</p>
696
697 <h2 id="_corruption_following_switches_between_rollback_and_wal_modes"><span>8.2. </span> Corruption following switches between rollback and WAL modes</h2>
698
699 <p>Repeatedly switching an SQLite database in and out of <a href="wal.html">WAL mode</a>
700 and running the <a href="lang_vacuum.html">VACUUM</a> command in between switches, in one process or
701 thread, can cause another process or thread that has the database file
702 open to miss the fact that the database has changed. That second process
703 or thread might then try to modify the database using a stale cache and
704 cause database corruption.</p>
705
706 <p>This problem was discovered during internal testing and has never been
707 observed in the wild. The problem was fixed on 2011-01-27 and in version
708 3.7.5.</p>
709
710 <h2 id="_i_o_error_while_obtaining_a_lock_leads_to_corruption"><span>8.3. </span> I/O error while obtaining a lock leads to corruption</h2>
711
712 <p>If the operating system returns an I/O error while attempting to obtain
713 a certain lock on shared memory in <a href="wal.html">WAL mode</a> then SQLite might fail
714 to reset its cache,
715 which could lead to database corruption if subsequent writes are attempted.</p>
716
717 <p>Note that this problem only occurs if the attempt to acquire the lock
718 resulted in an I/O error. If the lock is simply not granted (because some
719 other thread or process is already holding a conflicting lock) then no
720 corruption will ever occur. We are not aware of any operating systems that
721 will fail with an I/O error while attempting to get a file lock on shared
722 memory. So this is a theoretical problem rather than a real problem.
723 Needless to say, this problem has never been observed in the wild. The
724 problem was discovered while doing stress testing of SQLite in a test
725 harness that simulates I/O errors.</p>
726
727 <p>This problem was fixed on 2010-09-20 for SQLite version 3.7.3.</p>
728
729 <h2 id="_database_pages_leak_from_the_free_page_list"><span>8.4. </span> Database pages leak from the free page list</h2>
730
731 <p>When content is deleted from an SQLite database, pages that are no
732 longer used are added to a free list and are reused to hold content
733 added by subsequent inserts. A bug in SQLite that was present in
734 version 3.6.16 through 3.7.2 might cause pages to go missing out of
735 the free list when <a href="pragma.html#pragma_incremental_vacuum">incremental_vacuum</a> was used. This would not cause
736 data loss. But it would result in the database file being larger than
737 necessary. And it would cause the <a href="pragma.html#pragma_integrity_check">integrity_check pragma</a> to report
738 pages missing from the free list.</p>
739
740 <p>This problem was fixed on 2010-08-23 for SQLite version 3.7.2.</p>
741
742 <h2 id="_corruption_following_alternating_writes_from_3_6_and_3_7"><span>8.5. </span> Corruption following alternating writes from 3.6 and 3.7</h2>
743
744 <p>SQLite version 3.7.0 introduced a number of new enhancements to
745 the SQLite database file format (such as but not limited to <a href="wal.html">WAL</a>).
746 The 3.7.0 release was a shake-out release for these new features.
747 We expected to find problems and were not disappointed.</p>
748
749 <p>If a database were originally created using SQLite version 3.7.0,
750 then written by SQLite version 3.6.23.1 such that the size of the database
751 file increased, then written again by SQLite version 3.7.0, the database
752 file could go corrupt.</p>
753
754 <p>This problem was fixed on 2010-08-04 for SQLite version 3.7.1.</p>
755
756 <h2 id="_race_condition_in_recovery_on_windows_systems"><span>8.6. </span> Race condition in recovery on Windows systems</h2>
757
758 <p>SQLite version 3.7.16.2 fixes a subtle race condition in the locking
759 logic on Windows systems. When a database file is in need
760 of recovery because the previous process writing to it crashed in the
761 middle of a transaction and two or more processes try to open the
762 that database at the same time, then the race condition might cause
763 one of those processes to get a false indication that the recovery
764 has already completed, allowing that process to continue using the
765 database file without running recovery first. If that process writes
766 to the file, then the file might go corrupt. This race condition
767 had apparently existed in all prior versions of SQLite for Windows going
768 back to 2004. But the race was very tight. Practically speaking, you
769 need a fast multi-core machine in which you launch two processes to run
770 recovery at the same moment on two separate cores. This defect was
771 on Windows systems only and did not affect the posix OS interface.</p>
772
773 <a name="svptbug"></a>
774
775 <h2 id="_boundary_value_error_in_the_secondary_journals_used_by_nested_transactions"><span>8.7. </span> Boundary value error in the secondary journals used by nested transactions</h2>
776
777 <p>When a nested transaction is started using <a href="lang_savepoint.html">SAVEPOINT</a>, SQLite uses
778 a secondary rollback journal to track the changes for the nested
779 transaction, in case the inner transaction needs to be rolled back. Secondary
780 journals are not involved in protecting the database from corruption due
781 to program crashes or power outages. The secondary journals only come into
782 play when rolling back an inner transaction of a nested transaction.
783
784 </p><p>These secondary journals can be held either in memory or as temporary
785 files on disk. The default behavior is to store them on disk. But that
786 can be changed using the <a href="compile.html#temp_store">-DSQLITE_TEMP_STORE</a> compile-time option,
787 or at run-time using the <a href="pragma.html#pragma_temp_store">PRAGMA temp_store</a> statement. The bug
788 only arises when secondary journals are held in memory.
789
790 </p><p>In SQLite <a href="releaselog/3_35_0.html">version 3.35.0</a> (2021-03-12), a new optimization was
791 added so that when SQLite is holding secondary journals in memory,
792 less memory will be used. Unfortunately, an boundary check in
793 the new logic was coded incorrectly.
794 What should have been a "&lt;" operator was coded as "&lt;=". This
795 error might cause the secondary journal to enter an inconsistent state
796 if it is ever rolled back. If additional changes are made and the
797 outer transaction eventually commits, the database might be left in
798 an inconsistent state.
799
800 </p><p>This problem was discovered by an
801 <a href="https://sqlite.org/forum/forumpost/b03d86f9516cb3a2">independent researcher</a>
802 who was attempting to find bugs in SQLite using a fuzzer. The fuzzer found a
803 failure in an <a href="assert.html">assert() statement</a> that is used
804 to help verify the internal state of the secondary journal. The bug was a
805 sufficiently obscure corner-case that it might have gone unnoticed for many
806 years, had it not been for the intensive use of assert() statements in SQLite,
807 the persistence and tenacity of the security researchers, and their
808 customized state-of-the-art fuzzer.
809
810 </p><p>This problem was <a href="https://www.sqlite.org/src/info/73c2b50211d3ae26">fixed</a>
811 in <a href="releaselog/3_37_2.html">version 3.37.2</a> (2022-01-06).
812 </p>
813