Debian Codegraph @

www/testing.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 SQLite Is Tested</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 SQLite Is Tested
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="#introduction">1. Introduction</a></div>
129 <div class="fancy-toc2"><a href="#executive_summary">1.1. Executive Summary</a></div>
130 <div class="fancy-toc1"><a href="#test_harnesses">2. Test Harnesses</a></div>
131 <div class="fancy-toc1"><a href="#anomaly_testing">3. Anomaly Testing</a></div>
132 <div class="fancy-toc2"><a href="#out_of_memory_testing">3.1. Out-Of-Memory Testing</a></div>
133 <div class="fancy-toc2"><a href="#i_o_error_testing">3.2. I/O Error Testing</a></div>
134 <div class="fancy-toc2"><a href="#crash_testing">3.3. Crash Testing</a></div>
135 <div class="fancy-toc2"><a href="#compound_failure_tests">3.4. Compound failure tests</a></div>
136 <div class="fancy-toc1"><a href="#fuzz_testing">4. Fuzz Testing</a></div>
137 <div class="fancy-toc2"><a href="#sql_fuzz">4.1. SQL Fuzz</a></div>
138 <div class="fancy-toc3"><a href="#sql_fuzz_using_the_american_fuzzy_lop_fuzzer">4.1.1. SQL Fuzz Using The American Fuzzy Lop Fuzzer</a></div>
139 <div class="fancy-toc3"><a href="#google_oss_fuzz">4.1.2. Google OSS Fuzz</a></div>
140 <div class="fancy-toc3"><a href="#the_dbsqlfuzz_and_jfuzz_fuzzers">4.1.3. The dbsqlfuzz and jfuzz fuzzers</a></div>
141 <div class="fancy-toc3"><a href="#other_third_party_fuzzers">4.1.4. Other third-party fuzzers</a></div>
142 <div class="fancy-toc3"><a href="#the_fuzzcheck_test_harness">4.1.5. The fuzzcheck test harness</a></div>
143 <div class="fancy-toc3"><a href="#tension_between_fuzz_testing_and_100_mc_dc_testing">4.1.6. Tension Between Fuzz Testing And 100% MC/DC Testing</a></div>
144 <div class="fancy-toc2"><a href="#malformed_database_files">4.2. Malformed Database Files</a></div>
145 <div class="fancy-toc2"><a href="#boundary_value_tests">4.3. Boundary Value Tests</a></div>
146 <div class="fancy-toc1"><a href="#regression_testing">5. Regression Testing</a></div>
147 <div class="fancy-toc1"><a href="#automatic_resource_leak_detection">6. Automatic Resource Leak Detection</a></div>
148 <div class="fancy-toc1"><a href="#test_coverage">7. Test Coverage</a></div>
149 <div class="fancy-toc2"><a href="#statement_versus_branch_coverage">7.1. Statement versus branch coverage</a></div>
150 <div class="fancy-toc2"><a href="#coverage_testing_of_defensive_code">7.2. Coverage testing of defensive code</a></div>
151 <div class="fancy-toc2"><a href="#forcing_coverage_of_boundary_values_and_boolean_vector_tests">7.3. Forcing coverage of boundary values and boolean vector tests</a></div>
152 <div class="fancy-toc2"><a href="#branch_coverage_versus_mc_dc">7.4. Branch coverage versus MC/DC</a></div>
153 <div class="fancy-toc2"><a href="#measuring_branch_coverage">7.5. Measuring branch coverage</a></div>
154 <div class="fancy-toc2"><a href="#mutation_testing">7.6. Mutation testing</a></div>
155 <div class="fancy-toc2"><a href="#experience_with_full_test_coverage">7.7. Experience with full test coverage</a></div>
156 <div class="fancy-toc1"><a href="#dynamic_analysis">8. Dynamic Analysis</a></div>
157 <div class="fancy-toc2"><a href="#assert">8.1. Assert</a></div>
158 <div class="fancy-toc2"><a href="#valgrind">8.2. Valgrind</a></div>
159 <div class="fancy-toc2"><a href="#memsys2">8.3. Memsys2</a></div>
160 <div class="fancy-toc2"><a href="#mutex_asserts">8.4. Mutex Asserts</a></div>
161 <div class="fancy-toc2"><a href="#journal_tests">8.5. Journal Tests</a></div>
162 <div class="fancy-toc2"><a href="#undefined_behavior_checks">8.6. Undefined Behavior Checks</a></div>
163 <div class="fancy-toc1"><a href="#disabled_optimization_tests">9. Disabled Optimization Tests</a></div>
164 <div class="fancy-toc1"><a href="#checklists">10. Checklists</a></div>
165 <div class="fancy-toc1"><a href="#static_analysis">11. Static Analysis</a></div>
166 <div class="fancy-toc1"><a href="#summary">12. Summary</a></div>
167 </div>
168 </div>
169 <script>
170 function toggle_toc(){
171 var sub = document.getElementById("toc_sub")
172 var mk = document.getElementById("toc_mk")
173 if( sub.style.display!="block" ){
174 sub.style.display = "block";
175 mk.innerHTML = "&#x25bc;";
176 } else {
177 sub.style.display = "none";
178 mk.innerHTML = "&#x25ba;";
179 }
180 }
181 </script>
182 </div>
183
184
185
186
187
188
189
190 <h1 id="introduction"><span>1. </span>Introduction</h1>
191
192 <p>The reliability and robustness of SQLite is achieved in part
193 by thorough and careful testing.</p>
194
195 <p>As of <a href="releaselog/3_42_0.html">version 3.42.0</a> (2023-05-16),
196 the SQLite library consists of approximately
197 155.8 KSLOC of C code.
198 (KSLOC means thousands of "Source Lines Of Code" or, in other words,
199 lines of code excluding blank lines and comments.)
200 By comparison, the project has
201 590 times as much
202 test code and test scripts -
203 92053.1 KSLOC.</p>
204
205 <h2 id="executive_summary"><span>1.1. </span>Executive Summary</h2>
206
207 <ul>
208 <li> Four independently developed test harnesses
209 </li><li> 100% branch test coverage in an as-deployed configuration
210 </li><li> Millions and millions of test cases
211 </li><li> Out-of-memory tests
212 </li><li> I/O error tests
213 </li><li> Crash and power loss tests
214 </li><li> Fuzz tests
215 </li><li> Boundary value tests
216 </li><li> Disabled optimization tests
217 </li><li> Regression tests
218 </li><li> Malformed database tests
219 </li><li> Extensive use of assert() and run-time checks
220 </li><li> Valgrind analysis
221 </li><li> Undefined behavior checks
222 </li><li> Checklists
223 </li></ul>
224
225 <a name="harnesses"></a>
226
227 <h1 id="test_harnesses"><span>2. </span>Test Harnesses</h1>
228
229 <p>There are four independent test harnesses used for testing the
230 core SQLite library.
231 Each test harness is designed, maintained, and managed separately
232 from the others.
233 </p>
234
235 <ol>
236 <li><p>
237 <a name="tcl"></a>
238
239 The <b>TCL Tests</b> are the original tests for SQLite.
240 They are contained in the same source tree as the
241 SQLite core and like the SQLite core are in the public domain. The
242 TCL tests are the primary tests used during development.
243 The TCL tests are written using the
244 <a href="http://www.tcl-lang.org/">TCL scripting language</a>.
245 The TCL test harness itself consists of 27.2 KSLOC
246 of C code used to create the TCL interface. The test scripts are contained
247 in 1390 files totaling
248 23.2MB in size. There are
249 51445 distinct test cases, but many of the test
250 cases are parameterized and run multiple times (with different parameters)
251 so that on a full test run millions of
252 separate tests are performed.
253 </p>
254 </li>
255
256 <li><p>
257 The <b><a href="th3.html">TH3</a></b> test harness is a set of proprietary tests, written in
258 C that provide 100% branch test coverage
259 (and <a href="testing.html#mcdc">100% MC/DC test coverage</a>) to
260 the core SQLite library. The TH3 tests are designed to run
261 on embedded and specialized platforms that would not easily support
262 TCL or other workstation services. TH3 tests use only the published
263 SQLite interfaces. TH3 consists of about
264 76.9 MB or 1055.4 KSLOC
265 of C code implementing 50362 distinct test cases.
266 TH3 tests are heavily parameterized, though, so a full-coverage test runs
267 about 2.4 million different test
268 instances.
269 The cases that provide 100% branch test coverage constitute
270 a subset of the total TH3 test suite. A soak test
271 prior to release does about
272 248.5 million tests.
273 Additional information on TH3 is <a href="th3.html">available separately</a>.</p></li>
274
275 <li><p>
276 <a name="slt"></a>
277
278 The <a href="https://www.sqlite.org/sqllogictest"><b>SQL Logic Test</b></a>
279 or SLT test harness is used to run huge numbers
280 of SQL statements against both SQLite and several other SQL database engines
281 and verify that they all get the same answers. SLT currently compares
282 SQLite against PostgreSQL, MySQL, Microsoft SQL Server, and Oracle 10g.
283 SLT runs 7.2 million queries comprising
284 1.12GB of test data.
285 </p></li>
286
287 <li><p>
288 The <a href="#dbsqlfuzz"><b>dbsqlfuzz</b></a> engine is a
289 proprietary fuzz tester. Other <a href="testing.html#fuzztesting">fuzzers for SQLite</a>
290 mutate either the SQL inputs or the database file. Dbsqlfuzz mutates
291 both the SQL and the database file at the same time, and is thus able
292 to reach new error states. Dbsqlfuzz is built using the
293 <a href="http://llvm.org/docs/LibFuzzer.html">libFuzzer</a> framework of LLVM
294 with a custom mutator. There are
295 336 seed files. The dbsqlfuzz fuzzer
296 runs about one billion test mutations per day.
297 Dbsqlfuzz helps ensure
298 that SQLite is robust against attack via malicious SQL or database
299 inputs.
300 </p></li></ol>
301
302 <p>In addition to the four main test harnesses, there many other
303 small programs that implement specialized tests. Here are a few
304 examples:
305 </p><ol>
306 <li value="5">The "speedtest1.c" program
307 estimates the performance of SQLite under a typical workload.
308 </li><li>The "mptester.c" program is a stress test for multiple processes
309 concurrently reading and writing a single database.
310 </li><li>The "threadtest3.c" program is a stress test for multiple threads using
311 SQLite simultaneously.
312 </li><li>The "fuzzershell.c" program is used to
313 run some <a href="#fuzztesting">fuzz tests</a>.
314 </li><li>The "jfuzz" program is a libfuzzer-based fuzzer for
315 <a href="json1.html#jsonbx">JSONB</a> inputs to the <a href="json1.html">JSON SQL functions</a>.
316 </li></ol>
317
318
319 <p>All of the tests above must run successfully, on multiple platforms
320 and under multiple compile-time configurations,
321 before each release of SQLite.</p>
322
323 <p>Prior to each check-in to the SQLite source tree, developers
324 typically run a subset (called "veryquick") of the Tcl tests
325 consisting of about
326 304.7 thousand test cases.
327 The veryquick tests include most tests other than the anomaly, fuzz, and
328 soak tests. The idea behind the veryquick tests are that they are
329 sufficient to catch most errors, but also run in only a few minutes
330 instead of a few hours.</p>
331
332 <a name="anomaly"></a>
333
334 <h1 id="anomaly_testing"><span>3. </span>Anomaly Testing</h1>
335
336 <p>Anomaly tests are tests designed to verify the correct behavior
337 of SQLite when something goes wrong. It is (relatively) easy to build
338 an SQL database engine that behaves correctly on well-formed inputs
339 on a fully functional computer. It is more difficult to build a system
340 that responds sanely to invalid inputs and continues to function following
341 system malfunctions. The anomaly tests are designed to verify the latter
342 behavior.</p>
343
344 <a name="oomtesting"></a>
345
346 <h2 id="out_of_memory_testing"><span>3.1. </span>Out-Of-Memory Testing</h2>
347
348 <p>SQLite, like all SQL database engines, makes extensive use of
349 malloc() (See the separate report on
350 <a href="malloc.html">dynamic memory allocation in SQLite</a> for
351 additional detail.)
352 On servers and workstations, malloc() never fails in practice and so correct
353 handling of out-of-memory (OOM) errors is not particularly important.
354 But on embedded devices, OOM errors are frighteningly common and since
355 SQLite is frequently used on embedded devices, it is important that
356 SQLite be able to gracefully handle OOM errors.</p>
357
358 <p>OOM testing is accomplished by simulating OOM errors.
359 SQLite allows an application to substitute an alternative malloc()
360 implementation using the <a href="c3ref/config.html">sqlite3_config</a>(<a href="c3ref/c_config_covering_index_scan.html#sqliteconfigmalloc">SQLITE_CONFIG_MALLOC</a>,...)
361 interface. The TCL and TH3 test harnesses are both capable of
362 inserting a modified version of malloc() that can be rigged to fail
363 after a certain number of allocations. These instrumented mallocs
364 can be set to fail only once and then start working again, or to
365 continue failing after the first failure. OOM tests are done in a
366 loop. On the first iteration of the loop, the instrumented malloc
367 is rigged to fail on the first allocation. Then some SQLite operation
368 is carried out and checks are done to make sure SQLite handled the
369 OOM error correctly. Then the time-to-failure counter
370 on the instrumented malloc is increased by one and the test is
371 repeated. The loop continues until the entire operation runs to
372 completion without ever encountering a simulated OOM failure.
373 Tests like this are run twice, once with the instrumented malloc
374 set to fail only once, and again with the instrumented malloc set
375 to fail continuously after the first failure.</p>
376
377 <a name="ioerrtesting"></a>
378
379 <h2 id="i_o_error_testing"><span>3.2. </span>I/O Error Testing</h2>
380
381 <p>I/O error testing seeks to verify that SQLite responds sanely
382 to failed I/O operations. I/O errors might result from a full disk drive,
383 malfunctioning disk hardware, network outages when using a network
384 file system, system configuration or permission changes that occur in the
385 middle of an SQL operation, or other hardware or operating system
386 malfunctions. Whatever the cause, it is important that SQLite be able
387 to respond correctly to these errors and I/O error testing seeks to
388 verify that it does.</p>
389
390 <p>I/O error testing is similar in concept to OOM testing; I/O errors
391 are simulated and checks are made to verify that SQLite responds
392 correctly to the simulated errors. I/O errors are simulated in both
393 the TCL and TH3 test harnesses by inserting a new
394 <a href="c3ref/vfs.html">Virtual File System object</a> that is specially rigged
395 to simulate an I/O error after a set number of I/O operations.
396 As with OOM error testing, the I/O error simulators can be set to
397 fail just once, or to fail continuously after the first failure.
398 Tests are run in a loop, slowly increasing the point of failure until
399 the test case runs to completion without error. The loop is run twice,
400 once with the I/O error simulator set to simulate only a single failure
401 and a second time with it set to fail all I/O operations after the first
402 failure.</p>
403
404 <p>In I/O error tests, after the I/O error simulation failure mechanism
405 is disabled, the database is examined using
406 <a href="pragma.html#pragma_integrity_check">PRAGMA integrity_check</a> to make sure that the I/O error has not
407 introduced database corruption.</p>
408
409 <a name="crashtesting"></a>
410
411 <h2 id="crash_testing"><span>3.3. </span>Crash Testing</h2>
412
413 <p>Crash testing seeks to demonstrate that an SQLite database will not
414 go corrupt if the application or operating system crashes or if there
415 is a power failure in the middle of a database update. A separate
416 white-paper titled
417 <a href="atomiccommit.html">Atomic Commit in SQLite</a> describes the
418 defensive measure SQLite takes to prevent database corruption following
419 a crash. Crash tests strive to verify that those defensive measures
420 are working correctly.</p>
421
422 <p>It is impractical to do crash testing using real power failures, of
423 course, and so crash testing is done in simulation. An alternative
424 <a href="c3ref/vfs.html">Virtual File System</a> is inserted that allows the test
425 harness to simulate the state of the database file following a crash.</p>
426
427 <p>In the TCL test harness, the crash simulation is done in a separate
428 process. The main testing process spawns a child process which runs
429 some SQLite operation and randomly crashes somewhere in the middle of
430 a write operation. A special <a href="vfs.html">VFS</a> randomly reorders and corrupts
431 the unsynchronized
432 write operations to simulate the effect of buffered filesystems. After
433 the child dies, the original test process opens and reads the test
434 database and verifies that the changes attempted by the child either
435 completed successfully or else were completely rolled back. The
436 <a href="pragma.html#pragma_integrity_check">integrity_check</a> <a href="pragma.html#syntax">PRAGMA</a> is used to make sure no database corruption
437 occurs.</p>
438
439 <p>The TH3 test harness needs to run on embedded systems that do not
440 necessarily have the ability to spawn child processes, so it uses
441 an in-memory <a href="vfs.html">VFS</a> to simulate crashes. The in-memory <a href="vfs.html">VFS</a> can be rigged
442 to make a snapshot of the entire filesystem after a set number of I/O
443 operations. Crash tests run in a loop. On each iteration of the loop,
444 the point at which a snapshot is made is advanced until the SQLite
445 operations being tested run to completion without ever hitting a
446 snapshot. Within the loop, after the SQLite operation under test has
447 completed, the filesystem is reverted to the snapshot and random file
448 damage is introduced that is characteristic of the kinds of damage
449 one expects to see following a power loss. Then the database is opened
450 and checks are made to ensure that it is well-formed and that the
451 transaction either ran to completion or was completely rolled back.
452 The interior of the loop is repeated multiple times for each
453 snapshot with different random damage each time.</p>
454
455 <a name="multifail"></a>
456
457 <h2 id="compound_failure_tests"><span>3.4. </span>Compound failure tests</h2>
458
459 <p>The test suites for SQLite also explore the result of stacking
460 multiple failures. For example, tests are run to ensure correct behavior
461 when an I/O error or OOM fault occurs while trying to recover from a
462 prior crash.
463
464 <a name="fuzztesting"></a>
465
466 </p><h1 id="fuzz_testing"><span>4. </span>Fuzz Testing</h1>
467
468 <p><a href="http://en.wikipedia.org/wiki/Fuzz_testing">Fuzz testing</a>
469 seeks to establish that SQLite responds correctly to invalid, out-of-range,
470 or malformed inputs.</p>
471
472 <h2 id="sql_fuzz"><span>4.1. </span>SQL Fuzz</h2>
473
474 <p>SQL fuzz testing consists of creating syntactically correct yet
475 wildly nonsensical SQL statements and feeding them to SQLite to see
476 what it will do with them. Usually some kind of error is returned
477 (such as "no such table"). Sometimes, purely by chance, the SQL
478 statement also happens to be semantically correct. In that case, the
479 resulting prepared statement is run to make sure it gives a reasonable
480 result.</p>
481
482 <a name="aflfuzz"></a>
483
484 <h3 id="sql_fuzz_using_the_american_fuzzy_lop_fuzzer"><span>4.1.1. </span>SQL Fuzz Using The American Fuzzy Lop Fuzzer</h3>
485
486 <p>The concept of fuzz testing has been around for decades, but fuzz
487 testing was not an effective way to find bugs until 2014 when
488 Michal Zalewski invented the first practical profile-guided fuzzer,
489 <a href="http://lcamtuf.coredump.cx/afl/">American Fuzzy Lop</a> or "AFL".
490 Unlike prior fuzzers that blindly generate random inputs, AFL
491 instruments the program being tested (by modifying the assembly-language
492 output from the C compiler) and uses that instrumentation to detect when
493 an input causes the program to do something different - to follow
494 a new control path or loop a different number of times. Inputs that provoke
495 new behavior are retained and further mutated. In this way, AFL is able
496 to "discover" new behaviors of the program under test, including behaviors
497 that were never envisioned by the designers.
498
499 </p><p>AFL proved adept at finding arcane bugs in SQLite.
500 Most of the findings have been assert() statements where the conditional
501 was false under obscure circumstances. But AFL has also found
502 a fair number of crash bugs in SQLite, and even a few cases where SQLite
503 computed incorrect results.
504
505 </p><p>Because of its past success, AFL became a standard part of the testing
506 strategy for SQLite beginning with <a href="releaselog/3_8_10.html">version 3.8.10</a> (2015-05-07) until
507 it was superseded by better fuzzers in <a href="releaselog/3_29_0.html">version 3.29.0</a> (2019-07-10).
508
509 <a name="ossfuzz"></a>
510
511 </p><h3 id="google_oss_fuzz"><span>4.1.2. </span>Google OSS Fuzz</h3>
512
513 <p>Beginning in 2016, a team of engineers at Google started the
514 <a href="https://github.com/google/oss-fuzz">OSS Fuzz</a> project.
515 OSS Fuzz uses a AFL-style guided fuzzer running on Google's infrastructure.
516 The Fuzzer automatically downloads the latest check-ins for participating
517 projects, fuzzes them, and sends email to the developers reporting any
518 problems. When a fix is checked in, the fuzzer automatically detects this
519 and emails a confirmation to the developers.
520
521 </p><p>SQLite is one of many open-source projects that OSS Fuzz tests. The
522 <a href="https://www.sqlite.org/src/file/test/ossfuzz.c">test/ossfuzz.c</a> source file
523 in the SQLite repository is SQLite's interface to OSS fuzz.
524
525 </p><p>OSS Fuzz no longer finds historical bugs in SQLite. But it is still
526 running and does occasionally find issues in new development check-ins.
527 Examples:
528 <a href="https://www.sqlite.org/src/timeline?y=ci&c=c422afb507dc8757">&#91;1&#93;</a>
529 <a href="https://www.sqlite.org/src/timeline?y=ci&c=0a2eb949f8a759e5">&#91;2&#93;</a>
530 <a href="https://www.sqlite.org/src/timeline?y=ci&c=62f2235adf796c72">&#91;3&#93;</a>.
531
532 <a name="dbsqlfuzz"></a>
533
534 </p><h3 id="the_dbsqlfuzz_and_jfuzz_fuzzers"><span>4.1.3. </span>The dbsqlfuzz and jfuzz fuzzers</h3>
535
536 <p>Beginning in late 2018, SQLite has been fuzzed using a proprietary
537 fuzzer called "dbsqlfuzz". Dbsqlfuzz is built using the
538 <a href="http://llvm.org/docs/LibFuzzer.html">libFuzzer</a> framework of LLVM.
539
540 </p><p>The dbsqlfuzz fuzzer mutates both the SQL input and the database file
541 at the same time. Dbsqlfuzz uses a custom
542 <a href="https://github.com/google/fuzzing/blob/master/docs/structure-aware-fuzzing.md">Structure-Aware Mutator</a>
543 on a specialized input file that defines both an input database and SQL
544 text to be run against that database. Because it mutates both the input
545 database and the input SQL at the same time, dbsqlfuzz has been able to
546 find some obscure faults in SQLite that were missed by prior fuzzers that
547 mutated only SQL inputs or only the database file.
548 The SQLite developers keep dbsqlfuzz running against trunk in about
549 16 cores at all times. Each instance of dbsqlfuzz program is able to
550 evalutes about 400 test cases per second, meaning that about 500 million
551 cases are checked every day.</p>
552
553 <p>The dbsqlfuzz fuzzer has been very successful at hardening the
554 SQLite code base against malicious attack. Since dbsqlfuzz has been
555 added to the SQLite internal test suite, bug reports from external
556 fuzzers such as OSSFuzz have all but stopped.
557
558 </p><p>Note that dbsqlfuzz is <i>not</i> the Protobuf-based structure-aware
559 fuzzer for SQLite that is used by Chromium and described in the
560 <a href="https://github.com/google/fuzzing/blob/master/docs/structure-aware-fuzzing.md#user-content-example-sqlite">Structure-Aware Mutator article</a>.
561 There is no connection between these two fuzzers, other than the fact that they
562 are both based on <a href="http://llvm.org/docs/LibFuzzer.html">libFuzzer</a>
563 The Protobuf fuzzer for SQLite is written and maintained by the Chromium
564 team at Google, whereas dbsqlfuzz is written and maintained by the original
565 SQLite developers. Having multiple independently-developed fuzzers for SQLite
566 is good, as it means that obscure issues are more likely to be uncovered.
567
568 </p><p>Near the end of January 2024, a second libFuzzer-based tool called
569 "jfuzz" came into use. Jfuzz generates corrupt <a href="json1.html#jsonbx">JSONB</a> blobs and feeds
570 them into the <a href="json1.html">JSON SQL functions</a> to verify that the JSON functions
571 are able to safely and efficiently deal with corrupt binary inputs.
572
573
574 <a name="3pfuzz"></a>
575
576 </p><h3 id="other_third_party_fuzzers"><span>4.1.4. </span>Other third-party fuzzers</h3>
577
578 <p>SQLite seems to be a popular target for third-parties to fuzz.
579 The developers hear about many attempts to fuzz SQLite
580 and they do occasionally get bug reports found by independent
581 fuzzers. All such reports are promptly fixed, so the product is
582 improved and that the entire SQLite user community benefits.
583 This mechanism of having many independent testers is similar to
584 <a href="https://en.wikipedia.org/wiki/Linus%27s_law">Linus's law</a>:
585 "given enough eyeballs, all bugs are shallow".
586
587 </p><p>One fuzzing researcher of particular note is
588 <a href="https://www.manuelrigger.at/">Manuel Rigger</a>.
589 Most fuzzers only look for assertion faults, crashes, undefined behavior (UB),
590 or other easily detected anomalies. Dr. Rigger's fuzzers, on the other hand,
591 are able to find cases where SQLite computes an incorrect answer.
592 Rigger has found
593 <a href="https://www.sqlite.org/src/timeline?y=t&u=mrigger&n=all">many such cases</a>.
594 Most of these finds are obscure corner cases involving type
595 conversions and affinity transformations, and a good number of the finds
596 are against unreleased features. Nevertheless, his finds are still important
597 as they are real bugs,
598 and the SQLite developers are grateful to be able to identify and fix
599 the underlying problems.
600
601 <a name="fuzzcheck"></a>
602
603 </p><h3 id="the_fuzzcheck_test_harness"><span>4.1.5. </span>The fuzzcheck test harness</h3>
604
605 <p>Historical test cases from <a href="testing.html#aflfuzz">AFL</a>, <a href="testing.html#ossfuzz">OSS Fuzz</a>, and <a href="testing.html#dbsqlfuzz">dbsqlfuzz</a> are
606 collected in a set of database files in the main SQLite source tree
607 and then rerun by the "fuzzcheck" utility program whenever one runs
608 "make test". Fuzzcheck only runs a few thousand "interesting" cases
609 out of the billions of cases that the various fuzzers have
610 examined over the years. "Interesting" cases are cases that exhibit
611 previously unseen behavior. Actual bugs found by fuzzers are always
612 included among the interesting test cases, but most of the cases run
613 by fuzzcheck were never actual bugs.
614
615 <a name="tension"></a>
616
617 </p><h3 id="tension_between_fuzz_testing_and_100_mc_dc_testing"><span>4.1.6. </span>Tension Between Fuzz Testing And 100% MC/DC Testing</h3>
618
619 <p>Fuzz testing and <a href="testing.html#mcdc">100% MC/DC testing</a> are in tension with
620 one another.
621 That is to say, code tested to 100% MC/DC will tend to be
622 more vulnerable to problems found by fuzzing and code that performs
623 well during fuzz testing will tend to have (much) less than
624 100% MC/DC.
625 This is because MC/DC testing discourages <a href="testing.html#defcode">defensive code</a> with
626 unreachable branches, but without defensive code, a fuzzer is
627 more likely to find a path that causes problems. MC/DC testing
628 seems to work well for building code that is robust during
629 normal use, whereas fuzz testing is good for building code that is
630 robust against malicious attack.
631
632 </p><p>Of course, users would prefer code that is both robust in normal
633 use and resistant to malicious attack. The SQLite developers are
634 dedicated to providing that. The purpose of this section is merely
635 to point out that doing both at the same time is difficult.
636
637 </p><p>For much of its history SQLite has been focused on 100% MC/DC testing.
638 Resistance to fuzzing attacks only became a concern with the introduction
639 of AFL in 2014. For a while there, fuzzers were finding many problems
640 in SQLite. In more recent years, the testing strategy of SQLite has
641 evolved to place more emphasis on fuzz testing. We still maintain
642 100% MC/DC of the core SQLite code, but most testing CPU cycles are
643 now devoted to fuzzing.
644
645 </p><p>While fuzz testing and 100% MC/DC testing are in tension, they
646 are not completely at cross-purposes. The fact that the SQlite test
647 suite does test to 100% MC/DC means that when fuzzers do find problems,
648 those problems can be fixed quickly and with little risk of introducing
649 new errors.
650
651 </p><h2 id="malformed_database_files"><span>4.2. </span>Malformed Database Files</h2>
652
653 <p>There are numerous test cases that verify that SQLite is able to
654 deal with malformed database files.
655 These tests first build a well-formed database file, then add
656 corruption by changing one or more bytes in the file by some means
657 other than SQLite. Then SQLite is used to read the database.
658 In some cases, the bytes changes are in the middle of data.
659 This causes the content of the database to change while keeping the
660 database well-formed.
661 In other cases, unused bytes of the file are modified, which has
662 no effect on the integrity of the database.
663 The interesting cases are when bytes of the file that
664 define database structure get changed. The malformed database tests
665 verify that SQLite finds the file format errors and reports them
666 using the <a href="rescode.html#corrupt">SQLITE_CORRUPT</a> return code without overflowing
667 buffers, dereferencing NULL pointers, or performing other
668 unwholesome actions.</p>
669
670 <p>The <a href="testing.html#dbsqlfuzz">dbsqlfuzz</a> fuzzer also does an excellent job of verifying
671 that SQLite responds sanely to malformed database files.</p>
672
673 <h2 id="boundary_value_tests"><span>4.3. </span>Boundary Value Tests</h2>
674
675 <p>SQLite defines certain <a href="limits.html">limits</a> on its operation, such as the
676 maximum number of columns in a table, the maximum length of an
677 SQL statement, or the maximum value of an integer. The TCL and TH3 test
678 suites both contains numerous tests that push SQLite right to the edge
679 of its defined limits and verify that it performs correctly for
680 all allowed values. Additional tests go beyond the defined limits
681 and verify that SQLite correctly returns errors. The source code
682 contains <a href="testing.html#testcase">testcase macros</a> to verify that both sides of each boundary
683 have been tested.</p>
684
685 <a name="regressiontesting"></a>
686
687 <h1 id="regression_testing"><span>5. </span>Regression Testing</h1>
688
689 <p>Whenever a bug is reported against SQLite, that bug is not considered
690 fixed until new test cases that would exhibit the bug have been added
691 to either the TCL or TH3 test suites.
692 Over the years,
693 this has resulted in thousands and thousands of new tests.
694 These regression tests ensure that bugs that have
695 been fixed in the past are not reintroduced into future versions of
696 SQLite.</p>
697
698 <a name="leakcheck"></a>
699
700 <h1 id="automatic_resource_leak_detection"><span>6. </span>Automatic Resource Leak Detection</h1>
701
702 <p>Resource leak occurs when system resources
703 are allocated and never freed. The most troublesome resource leaks
704 in many applications are memory leaks - when memory is allocated using
705 malloc() but never released using free(). But other kinds of resources
706 can also be leaked: file descriptors, threads, mutexes, etc.</p>
707
708 <p>Both the TCL and TH3 test harnesses automatically track system
709 resources and report resource leaks on <u>every</u> test run.
710 No special configuration or setup is required. The test harnesses
711 are especially vigilant with regard to memory leaks. If a change
712 causes a memory leak, the test harnesses will recognize this
713 quickly. SQLite is designed to never leak memory, even after
714 an exception such as an OOM error or disk I/O error. The test
715 harnesses are zealous to enforce this.</p>
716
717 <a name="coverage"></a>
718
719 <h1 id="test_coverage"><span>7. </span>Test Coverage</h1>
720
721 <p>The SQLite core, including the unix <a href="vfs.html">VFS</a>,
722 has 100% branch test coverage under <a href="th3.html">TH3</a> in
723 its default configuration as measured by
724 <a href="http://gcc.gnu.org/onlinedocs/gcc/Gcov.html">gcov</a>.
725 Extensions such as FTS3 and RTree are excluded from this
726 analysis.</p>
727
728 <a name="stmtvbr"></a>
729
730 <h2 id="statement_versus_branch_coverage"><span>7.1. </span>Statement versus branch coverage</h2>
731
732 <p>There are many ways to measure test coverage. The most popular
733 metric is "statement coverage". When you hear someone say that their
734 program as "XX% test coverage" without further explanation, they usually
735 mean statement coverage. Statement coverage measures what percentage
736 of lines of code are executed at least once by the test suite.</p>
737
738 <p>Branch coverage is more rigorous than statement coverage. Branch
739 coverage measures the number of machine-code branch instructions that
740 are evaluated at least once on both directions.</p>
741
742 <p>To illustrate the difference between statement coverage and
743 branch coverage, consider the following hypothetical
744 line of C code:</p>
745
746 <div class="codeblock"><pre>if( a>b && c!=25 ){ d++; }
747 </pre></div>
748
749 <p>Such a line of C code might generate a dozen separate machine code
750 instructions. If any one of those instructions is ever evaluated, then
751 we say that the statement has been tested. So, for example, it might
752 be the case that the conditional expression is
753 always false and the "d" variable is
754 never incremented. Even so, statement coverage counts this line of
755 code as having been tested.</p>
756
757 <p>Branch coverage is more strict. With branch coverage, each test and
758 each subblock within the statement is considered separately. In order
759 to achieve 100% branch coverage in the example above, there must be at
760 least three test cases:</p>
761
762 <p></p><ul>
763 <li> a&lt;=b
764 </li><li> a&gt;b && c==25
765 </li><li> a&gt;b && c!=25
766 </li></ul>
767
768 <p>Any one of the above test cases would provide 100% statement coverage
769 but all three are required for 100% branch coverage. Generally speaking,
770 100% branch coverage implies 100% statement coverage, but the converse is
771 not true. To reemphasize, the
772 <a href="th3.html">TH3</a> test harness for SQLite provides the stronger form of
773 test coverage - 100% branch test coverage.</p>
774
775 <a name="defcode"></a>
776
777 <h2 id="coverage_testing_of_defensive_code"><span>7.2. </span>Coverage testing of defensive code</h2>
778
779 <p>A well-written C program will typically contain some defensive
780 conditionals which in practice are always true or always false.
781 This leads to a
782 programming dilemma: Does one remove defensive code in order to obtain
783 100% branch coverage?</p>
784
785 <p>In SQLite, the answer to the previous question is "no".
786 For testing purposes, the SQLite source code defines
787 macros called ALWAYS() and NEVER(). The ALWAYS() macro
788 surrounds conditions
789 which are expected to always evaluate as true and NEVER() surrounds
790 conditions that are always evaluated to false. These macros serve as
791 comments to indicate that the conditions are defensive code.
792 In release builds, these macros are pass-throughs:</p>
793
794 <div class="codeblock"><pre>#define ALWAYS(X) (X)
795 #define NEVER(X) (X)
796 </pre></div>
797
798 <p>During most testing, however, these macros will throw an assertion
799 fault if their argument does not have the expected truth value. This
800 alerts the developers quickly to incorrect design assumptions.
801
802 </p><div class="codeblock"><pre>#define ALWAYS(X) ((X)?1:assert(0),0)
803 #define NEVER(X) ((X)?assert(0),1:0)
804 </pre></div>
805
806 <p>When measuring test coverage, these macros are defined to be constant
807 truth values so that they do not generate assembly language branch
808 instructions, and hence do not come into play when calculating the
809 branch coverage:</p>
810
811 <div class="codeblock"><pre>#define ALWAYS(X) (1)
812 #define NEVER(X) (0)
813 </pre></div>
814
815 <p>The test suite is designed to be run three times, once for each of
816 the ALWAYS() and NEVER() definitions shown above. All three test runs
817 should yield exactly the same result. There is a run-time test using
818 the <a href="c3ref/test_control.html">sqlite3_test_control</a>(<a href="c3ref/c_testctrl_always.html">SQLITE_TESTCTRL_ALWAYS</a>, ...) interface that
819 can be used to verify that the macros are correctly set to the first
820 form (the pass-through form) for deployment.</p>
821
822 <a name="testcase"></a>
823
824 <h2 id="forcing_coverage_of_boundary_values_and_boolean_vector_tests"><span>7.3. </span>Forcing coverage of boundary values and boolean vector tests</h2>
825
826 <p>Another macro used in conjunction with test coverage measurement is
827 the <tt>testcase()</tt> macro. The argument is a condition for which
828 we want test cases that evaluate to both true and false.
829 In non-coverage builds (that is to say, in release builds) the
830 <tt>testcase()</tt> macro is a no-op:</p>
831
832 <div class="codeblock"><pre>#define testcase(X)
833 </pre></div>
834
835 <p>But in a coverage measuring build, the <tt>testcase()</tt> macro
836 generates code that evaluates the conditional expression in its argument.
837 Then during analysis, a check
838 is made to ensure tests exist that evaluate the conditional to both true
839 and false. <tt>Testcase()</tt> macros are used, for example, to help verify
840 that boundary values are tested. For example:</p>
841
842 <div class="codeblock"><pre>testcase( a==b );
843 testcase( a==b+1 );
844 if( a>b && c!=25 ){ d++; }
845 </pre></div>
846
847 <p>Testcase macros are also used when two or more cases of a switch
848 statement go to the same block of code, to make sure that the code was
849 reached for all cases:</p>
850
851 <div class="codeblock"><pre>switch( op ){
852 case OP_Add:
853 case OP_Subtract: {
854 testcase( op==OP_Add );
855 testcase( op==OP_Subtract );
856 /* ... */
857 break;
858 }
859 /* ... */
860 }
861 </pre></div>
862
863 <p>For bitmask tests, <tt>testcase()</tt> macros are used to verify that every
864 bit of the bitmask affects the outcome. For example, in the following block
865 of code, the condition is true if the mask contains either of two bits
866 indicating either a MAIN_DB or a TEMP_DB is being opened.
867 The <tt>testcase()</tt>
868 macros that precede the if statement verify that both cases are tested:</p>
869
870 <div class="codeblock"><pre>testcase( mask & SQLITE_OPEN_MAIN_DB );
871 testcase( mask & SQLITE_OPEN_TEMP_DB );
872 if( (mask & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB))!=0 ){ ... }
873 </pre></div>
874
875 <p>The SQLite source code contains 1184
876 uses of the <tt>testcase()</tt> macro.</p>
877
878 <a name="mcdc"></a>
879
880 <h2 id="branch_coverage_versus_mc_dc"><span>7.4. </span>Branch coverage versus MC/DC</h2>
881
882 <p>Two methods of measuring test coverage were described above:
883 "statement" and "branch" coverage. There are many other test coverage
884 metrics besides these two. Another popular metric is "Modified
885 Condition/Decision Coverage" or MC/DC.
886 <a href="http://en.wikipedia.org/wiki/Modified_Condition/Decision_Coverage">Wikipedia</a>
887 defines MC/DC as follows:</p>
888
889 <ul>
890 <li> Each decision tries every possible outcome.
891 </li><li> Each condition in a decision takes on every possible outcome.
892 </li><li> Each entry and exit point is invoked.
893 </li><li> Each condition in a decision is shown to independently
894 affect the outcome of the decision.
895 </li></ul>
896
897 <p>In the C programming language
898 where <b><tt>&amp;&amp;</tt></b> and <b><tt>||</tt></b>
899 are "short-circuit" operators, MC/DC and branch coverage are very nearly
900 the same thing. The primary difference is in boolean vector tests.
901 One can test for any of several bits in bit-vector and still obtain
902 100% branch test coverage even though the second element of MC/DC - the
903 requirement that each condition in a decision take on every possible outcome -
904 might not be satisfied.</p>
905
906 <p>SQLite uses <tt>testcase()</tt> macros as described in the previous
907 subsection to make sure that every condition in a bit-vector decision takes
908 on every possible outcome. In this way, SQLite also achieves 100% MC/DC
909 in addition to 100% branch coverage.</p>
910
911 <h2 id="measuring_branch_coverage"><span>7.5. </span>Measuring branch coverage</h2>
912
913 <p>Branch coverage in SQLite is currently measured
914 using <a href="https://gcc.gnu.org/onlinedocs/gcc/Gcov.html">gcov</a> with the "-b"
915 option. First the test program is compiled using options
916 "-g -fprofile-arcs -ftest-coverage" and then the test program is run.
917 Then "gcov -b" is run to generate a coverage report.
918 The coverage report is verbose and inconvenient to read,
919 so the gcov-generated report is processed using
920 some simple scripts to put it into a more human-friendly format.
921 This entire process is automated using scripts, of course.
922
923 </p><p>Note that running SQLite with gcov is not a test of SQLite &mdash;
924 it is a test of the test suite. The gcov run does not test SQLite because
925 the -fprofile-args and -ftest-coverage options cause the compiler to
926 generate different code.
927 The gcov run merely verifies that the test suite provides 100% branch test
928 coverage. The gcov run is a test of the test - a meta-test.
929
930 </p><p>After gcov has been run to verify 100% branch test coverage,
931 then the test program is recompiled using delivery compiler options
932 (without the special -fprofile-arcs and -ftest-coverage options)
933 and the test program is rerun.
934 This second run is the actual test of SQLite.
935
936 </p><p>It is important to verify that the gcov test run
937 and the second real test run both give the same output. Any
938 differences in output indicate either the use of undefined or
939 indeterminate behavior in the SQLite code (and hence a bug),
940 or a bug in the compiler.
941 Note that SQLite has, over the previous decade, encountered bugs
942 in each of GCC, Clang, and MSVC. Compiler bugs, while rare, do happen,
943 which is why it is so important to test the code in an as-delivered
944 configuration.
945
946 <a name="mutationtests"></a>
947
948 </p><h2 id="mutation_testing"><span>7.6. </span>Mutation testing</h2>
949
950 <p>Using gcov (or similar) to show that every branch instruction is taken
951 at least once in both directions is good measure of test suite quality.
952 But even better is showing that every branch instruction makes
953 a difference in the output. In other words, we want to show
954 not only that every branch instruction both jumps and falls through but also
955 that every branch is doing useful work and that the test suite is able
956 to detect and verify that work. When a branch is found that does not
957 make a difference in the output, that suggests that code associated with
958 the branch can be removed (reducing the size of the library and perhaps
959 making it run faster) or that the test suite is inadequately testing the
960 feature that the branch implements.
961
962 </p><p>SQLite strives to verify that every branch instruction makes a difference
963 using <a href="https://en.wikipedia.org/wiki/Mutation_testing">mutation testing</a>.
964 <a href="th3.html#muttest">A script</a>
965 first compiles the SQLite source code into assembly language
966 (using, for example, the -S option to gcc). Then the script steps through
967 the generated assembly language and, one by one, changes each branch
968 instruction into either an unconditional jump or a no-op, compiles the
969 result, and verifies that the test suite catches the mutation.
970
971 </p><p>
972 Unfortunately, SQLite contains many branch instructions that
973 help the code run faster without changing the output.
974 Such branches generate false-positives during mutation testing.
975 As an example, consider the following
976 <a href="https://www.sqlite.org/src/artifact/55b5fb474?ln=55-62">hash function</a>
977 used to accelerate table-name lookup:
978
979 </p><div class="codeblock"><pre>55 static unsigned int strHash(const char *z){
980 56 unsigned int h = 0;
981 57 unsigned char c;
982 58 while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/
983 59 h = (h&lt;&lt;3) &#94; h &#94; sqlite3UpperToLower&#91;c&#93;;
984 60 }
985 61 return h;
986 62 }
987 </pre></div>
988
989 <p>
990 If the branch instruction that implements the "c!=0" test on line 58
991 is changed into a no-op, then the while-loop will loop forever and the
992 test suite will fail with a time-out. But if that branch is changed
993 into an unconditional jump, then the hash function will always return 0.
994 The problem is that 0 is a valid hash. A hash function that always
995 returns 0 still works in the sense that SQLite still always gets the correct
996 answer. The table-name hash table degenerates into a linked-list
997 and so the table-name lookups that occur while parsing SQL statements
998 might be a little slower, but the end result will be the same.
999
1000 </p><p>
1001 To work around this problem, comments of the form
1002 "<code>/*OPTIMIZATION-IF-TRUE*/</code>" and
1003 "<code>/*OPTIMIZATION-IF-FALSE*/</code>" are inserted into the SQLite
1004 source code to tell the mutation testing script to ignore some branch
1005 instructions.
1006
1007 <a name="thoughts1"></a>
1008
1009 </p><h2 id="experience_with_full_test_coverage"><span>7.7. </span>Experience with full test coverage</h2>
1010
1011 <p>The developers of SQLite have found that full coverage testing is an
1012 extremely effective method for locating and preventing bugs.
1013 Because every single branch
1014 instruction in SQLite core code is covered by test cases, the developers
1015 can be confident that changes made in one part of the code
1016 do not have unintended consequences in other parts of the code.
1017 The many new features and performance improvements that have been
1018 added to SQLite in recent years would not have been possible without
1019 the availability of full-coverage testing.</p>
1020
1021 <p>Maintaining 100% MC/DC is laborious and time-consuming.
1022 The level of effort needed to maintain full-coverage testing
1023 is probably not cost effective for a typical application.
1024 However, we think that full-coverage testing is justified for a
1025 <a href="mostdeployed.html">very widely deployed</a> infrastructure library
1026 like SQLite, and especially for a database library which by its very
1027 nature "remembers" past mistakes.
1028
1029
1030 <a name="dynamicanalysis"></a>
1031
1032 </p><h1 id="dynamic_analysis"><span>8. </span>Dynamic Analysis</h1>
1033
1034 <p>Dynamic analysis refers to internal and external checks on the
1035 SQLite code which are performed while the code is live and running.
1036 Dynamic analysis has proven to be a great help in maintaining the
1037 quality of SQLite.</p>
1038
1039 <a name="asserts"></a>
1040
1041 <h2 id="assert"><span>8.1. </span>Assert</h2>
1042
1043 <p>The SQLite core contains 6754 <tt>assert()</tt>
1044 statements that verify function preconditions and postconditions and
1045 loop invariants. Assert() is a macro which is a standard part of
1046 ANSI-C. The argument is a boolean value that is assumed to always be
1047 true. If the assertion is false, the program prints an error message
1048 and halts.</p>
1049
1050 <p>Assert() macros are disabled by compiling with the NDEBUG macro defined.
1051 In most systems, asserts are enabled by default. But in SQLite, the
1052 asserts are so numerous and are in such performance critical places, that
1053 the database engine runs about three times slower when asserts are enabled.
1054 Hence, the default (production) build of SQLite disables asserts.
1055 Assert statements are only enabled when SQLite is compiled with the
1056 SQLITE_DEBUG preprocessor macro defined.</p>
1057
1058 <p>See the <a href="assert.html">Use Of assert in SQLite</a> document
1059 for additional information about how SQLite uses assert().</p>
1060
1061 <a name="valgrind"></a>
1062
1063 <h2 id="valgrind"><span>8.2. </span>Valgrind</h2>
1064
1065 <p><a href="http://valgrind.org/">Valgrind</a> is perhaps the most amazing
1066 and useful developer tool in the world. Valgrind is a simulator - it simulates
1067 an x86 running a Linux binary. (Ports of Valgrind for platforms other
1068 than Linux are in development, but as of this writing, Valgrind only
1069 works reliably on Linux, which in the opinion of the SQLite developers
1070 means that Linux should be the preferred platform for all software development.)
1071 As Valgrind runs a Linux binary, it looks for all kinds of interesting
1072 errors such as array overruns, reading from uninitialized memory,
1073 stack overflows, memory leaks, and so forth. Valgrind finds problems
1074 that can easily slip through all of the other tests run against SQLite.
1075 And, when Valgrind does find an error, it can dump the developer directly
1076 into a symbolic debugger at the exact point where the error occur, to
1077 facilitate a quick fix.</p>
1078
1079 <p>Because it is a simulator, running a binary in Valgrind is slower than
1080 running it on native hardware. (To a first approximation, an application
1081 running in Valgrind on a workstation will perform about the same as it
1082 would running natively on a smartphone.) So it is impractical to run the full
1083 SQLite test suite through Valgrind. However, the veryquick tests and
1084 the coverage of the TH3 tests are run through Valgrind prior to every
1085 release.</p>
1086
1087 <a name="memtesting"></a>
1088
1089 <h2 id="memsys2"><span>8.3. </span>Memsys2</h2>
1090
1091 <p>SQLite contains a pluggable
1092 <a href="malloc.html">memory allocation subsystem</a>.
1093 The default implementation uses system malloc() and free().
1094 However, if SQLite is compiled with <a href="compile.html#memdebug">SQLITE_MEMDEBUG</a>, an alternative
1095 memory allocation wrapper (<a href="malloc.html#memdebug">memsys2</a>)
1096 is inserted that looks for memory allocation
1097 errors at run-time. The memsys2 wrapper checks for memory leaks, of
1098 course, but also looks for buffer overruns, uses of uninitialized memory,
1099 and attempts to use memory after it has been freed. These same checks
1100 are also done by valgrind (and, indeed, Valgrind does them better)
1101 but memsys2 has the advantage of being much faster than Valgrind, which
1102 means the checks can be done more often and for longer tests.</p>
1103
1104 <a name="mutextesting"></a>
1105
1106 <h2 id="mutex_asserts"><span>8.4. </span>Mutex Asserts</h2>
1107
1108 <p>SQLite contains a pluggable mutex subsystem. Depending on
1109 compile-time options, the default mutex system contains interfaces
1110 <a href="c3ref/mutex_held.html">sqlite3_mutex_held()</a> and <a href="c3ref/mutex_held.html">sqlite3_mutex_notheld()</a> that detect
1111 whether or not a particular mutex is held by the calling thread.
1112 These two interfaces are used extensively within assert() statements
1113 in SQLite to verify mutexes are held and released at all the right
1114 moments, in order to double-check that SQLite does work correctly
1115 in multi-threaded applications.</p>
1116
1117 <a name="journaltest"></a>
1118
1119 <h2 id="journal_tests"><span>8.5. </span>Journal Tests</h2>
1120
1121 <p>One of the things that SQLite does to ensure that transactions
1122 are atomic across system crashes and power failures is to write
1123 all changes into the rollback journal file prior to changing the
1124 database. The TCL test harness contains an alternative
1125 <a href="vfs.html">OS backend</a> implementation that helps to
1126 verify this is occurring correctly. The "journal-test VFS" monitors
1127 all disk I/O traffic between the database file and rollback journal,
1128 checking to make sure that nothing is written into the database
1129 file which has not first been written and synced to the rollback journal.
1130 If any discrepancies are found, an assertion fault is raised.</p>
1131
1132 <p>The journal tests are an additional double-check over and above
1133 the crash tests to make sure that SQLite transactions will be atomic
1134 across system crashes and power failures.</p>
1135
1136 <a name="intoverflow"></a>
1137
1138 <h2 id="undefined_behavior_checks"><span>8.6. </span>Undefined Behavior Checks</h2>
1139
1140 <p>In the C programming language, it is very easy to write code that
1141 has "undefined" or "implementation defined" behavior.
1142 That means that the code might work during development, but then give
1143 a different answer on a different system, or when recompiled using different
1144 compiler options.
1145 Examples of undefined and implementation-defined behavior in
1146 ANSI C include:
1147 </p><ul>
1148 <li>Signed integer overflow. (Signed integer overflow does <u>not</u>
1149 necessarily wrap around, as most people expect.)
1150 </li><li>Shifting an N-bit integer by more than N bits.
1151 </li><li>Shifting by a negative amount.
1152 </li><li>Shifting a negative number.
1153 </li><li>Using the memcpy() function on overlapping buffers.
1154 </li><li>The order of evaluation of function arguments.
1155 </li><li>Whether or not "char" variables are signed or unsigned.
1156 </li><li>And so forth....
1157 </li></ul>
1158
1159 <p>Since undefined and implementation-defined behavior is non-portable
1160 and can easily lead to incorrect answers, SQLite works very hard to avoid it.
1161 For example,
1162 when adding two integer column values together as part of an SQL statement,
1163 SQLite does not simply add them together using the C-language "+" operator.
1164 Instead, it first checks to make sure the
1165 addition will not overflow, and if it will, it does the addition using
1166 floating point instead.
1167
1168 </p><p>To help ensure that SQLite does not make use of undefined or
1169 implementation defined behavior, the test suites are rerun using
1170 instrumented builds that try to detect undefined behavior. For example,
1171 test suites are run using the "-ftrapv" option of GCC. And they
1172 are run again using the "-fsanitize=undefined" option on Clang. And
1173 again using the "/RTC1" option in MSVC. Then the test suites are rerun
1174 using options like "-funsigned-char" and "-fsigned-char" to make sure
1175 that implementation differences do not matter either. Tests are then repeated
1176 on 32-bit and 64-bit systems and on big-endian and little-endian systems,
1177 using a variety of CPU architectures.
1178 Furthermore, the test suites are augmented with many test cases that are
1179 deliberately designed to provoke undefined behavior. For example:
1180 "<b>SELECT -1*(-9223372036854775808);</b>".
1181
1182 <a name="disopttest"></a>
1183
1184 </p><h1 id="disabled_optimization_tests"><span>9. </span>Disabled Optimization Tests</h1>
1185
1186 <p>The <a href="c3ref/test_control.html">sqlite3_test_control</a>(<a href="c3ref/c_testctrl_always.html">SQLITE_TESTCTRL_OPTIMIZATIONS</a>, ...) interface
1187 allows selected SQL statement optimizations to be disabled at run-time.
1188 SQLite should always generate exactly the same answer with optimizations
1189 enabled and with optimizations disabled; the answer simply arrives quicker
1190 with the optimizations turned on. So in a production environment, one always
1191 leaves the optimizations turned on (the default setting).</p>
1192
1193 <p>One verification technique used on SQLite is to run an entire test suite
1194 twice, once with optimizations left on and a second time with optimizations
1195 turned off, and verify that the same output is obtained both times. This
1196 shows that the optimizations do not introduce errors.</p>
1197
1198 <p>Not all test cases can be handled this way. Some test cases check
1199 to verify that the optimizations really are reducing the amount of
1200 computation by counting the number of disk accesses, sort operations,
1201 full-scan steps, or other processing steps that occur during queries.
1202 Those test cases will appear to fail when optimizations are disabled.
1203 But the majority of test cases simply check that the correct answer
1204 was obtained, and all of those cases can be run successfully with and
1205 without the optimizations, in order to show that the optimizations do not
1206 cause malfunctions.</p>
1207
1208
1209 <a name="cklist"></a>
1210
1211 <h1 id="checklists"><span>10. </span>Checklists</h1>
1212
1213 <p>The SQLite developers use an on-line checklist to coordinate testing
1214 activity and to verify that all tests pass prior each SQLite release.
1215 <a href="https://www.sqlite.org/checklists/index.html">Past checklists</a>
1216 are retained for historical reference.
1217 (The checklists are read-only for anonymous internet viewers, but
1218 developers can log in and update checklist items in their web
1219 browsers.)
1220 The use of checklists for SQLite testing and other development activities
1221 is inspired by <i>
1222 <a href="http://atulgawande.com/book/the-checklist-manifesto/">The Checklist Manifesto</a>
1223 </i>.</p>
1224
1225 <p>The latest checklists contain approximately 200 items that are
1226 individually verified for each release. Some checklist items only take
1227 a few seconds to verify and mark off. Others involve test suites
1228 that run for many hours.</p>
1229
1230 <p>The release checklist is not automated: developers run each item on
1231 the checklist manually. We find that it is important to keep a human in
1232 the loop. Sometimes problems are found while running a checklist item
1233 even though the test itself passed. It is important to have a human
1234 reviewing the test output at the highest level, and constantly asking
1235 "Is this really right?"</p>
1236
1237 <p>The release checklist is continuously evolving. As new problems or
1238 potential problems are discovered, new checklist items are added to
1239 make sure those problems do not appear in subsequent releases. The
1240 release checklist has proven to be an invaluable tool in helping to
1241 ensure that nothing is overlooked during the release process.</p>
1242
1243
1244 <a name="staticanalysis"></a>
1245
1246 <h1 id="static_analysis"><span>11. </span>Static Analysis</h1>
1247
1248 <p>Static analysis means analyzing source code at compile-time to
1249 check for correctness. Static analysis includes compiler
1250 warning messages and more in-depth analysis engines such as the
1251 <a href="http://clang-analyzer.llvm.org/">Clang Static Analyzer</a>.
1252 SQLite compiles without warnings on GCC and Clang using
1253 the -Wall and -Wextra flags on Linux and Mac and on MSVC on Windows.
1254 No valid warnings are generated by the Clang Static Analyzer tool "scan-build"
1255 either (though recent versions of clang seem to generate many false-positives.)
1256 Nevertheless, some warnings might be generated by other
1257 static analyzers. Users are encouraged not to stress over these
1258 warnings and to instead take solace in the intense testing of SQLite
1259 described above.
1260 </p>
1261
1262 <p>Static analysis has not been helpful in finding
1263 bugs in SQLite. Static analysis has found a few bugs in SQLite, but
1264 those are the exceptions. More bugs have been
1265 introduced into SQLite while trying to get it to compile without
1266 warnings than have been found by static analysis.</p>
1267
1268 <a name="summary"></a>
1269
1270 <h1 id="summary"><span>12. </span>Summary</h1>
1271
1272 <p>SQLite is open source. This gives many people the idea that
1273 it is not well tested as commercial software and is perhaps unreliable.
1274 But that impression is false.
1275 SQLite has exhibited very high reliability in the field and
1276 a very low defect rate, especially considering how rapidly it is evolving.
1277 The quality of SQLite is achieved in part by careful code design and
1278 implementation. But extensive testing also plays a vital role in
1279 maintaining and improving the quality of SQLite. This document has
1280 summarized the testing procedures that every release of SQLite undergoes
1281 with the hope of inspiring confidence that SQLite is
1282 suitable for use in mission-critical applications.</p>
1283
1284