3 # The author disclaims copyright to this source code. In place of
4 # a legal notice, here is a blessing:
6 # May you do good and not evil.
7 # May you find forgiveness for yourself and forgive others.
8 # May you share freely, never taking more than you give.
10 #***********************************************************************
12 # This file contains tests to ensure that the library handles malloc() failures
13 # correctly. The emphasis of these tests are the _prepare(), _step() and
16 # $Id: malloc3.test,v 1.24 2008/10/14 15:54:08 drh Exp $
18 set testdir [file dirname $argv0]
19 source $testdir/tester.tcl
20 source $testdir/malloc_common.tcl
22 # Only run these tests if memory debugging is turned on.
25 puts "Skipping malloc3 tests: not compiled with -DSQLITE_MEMDEBUG..."
31 # Do not run these tests with an in-memory journal.
33 # In the pager layer, if an IO or OOM error occurs during a ROLLBACK, or
34 # when flushing a page to disk due to cache-stress, the pager enters an
35 # "error state". The only way out of the error state is to unlock the
36 # database file and end the transaction, leaving whatever journal and
37 # database files happen to be on disk in place. The next time the current
38 # (or any other) connection opens a read transaction, hot-journal rollback
39 # is performed if necessary.
41 # Of course, this doesn't work with an in-memory journal.
43 if {[permutation]=="inmemory_journal"} {
48 #--------------------------------------------------------------------------
49 # NOTES ON RECOVERING FROM A MALLOC FAILURE
51 # The tests in this file test the behaviours described in the following
52 # paragraphs. These tests test the behaviour of the system when malloc() fails
53 # inside of a call to _prepare(), _step(), _finalize() or _reset(). The
54 # handling of malloc() failures within ancillary procedures is tested
59 # Executing a statement is done in three stages (prepare, step and finalize). A
60 # malloc() failure may occur within any stage. If a memory allocation fails
61 # during statement preparation, no statement handle is returned. From the users
62 # point of view the system state is as if _prepare() had never been called.
64 # If the memory allocation fails during the _step() or _finalize() calls, then
65 # the database may be left in one of two states (after finalize() has been
68 # * As if the neither _step() nor _finalize() had ever been called on
69 # the statement handle (i.e. any changes made by the statement are
71 # * The current transaction may be rolled back. In this case a hot-journal
72 # may or may not actually be present in the filesystem.
74 # The caller can tell the difference between these two scenarios by invoking
78 # Handling of sqlite3_reset():
80 # If a malloc() fails while executing an sqlite3_reset() call, this is handled
81 # in the same way as a failure within _finalize(). The statement handle
82 # is not deleted and must be passed to _finalize() for resource deallocation.
83 # Attempting to _step() or _reset() the statement after a failed _reset() will
84 # always return SQLITE_NOMEM.
87 # Other active SQL statements:
89 # The effect of a malloc failure on concurrently executing SQL statements,
90 # particularly when the statement is executing with READ_UNCOMMITTED set and
91 # the malloc() failure mandates statement rollback only. Currently, if
92 # transaction rollback is required, all other vdbe's are aborted.
94 # Non-transient mallocs in btree.c:
95 # * The Btree structure itself
96 # * Each BtCursor structure
99 # readMasterJournal() - Space to read the master journal name
100 # pager_delmaster() - Space for the entire master journal file
102 # sqlite3pager_open() - The pager structure itself
103 # sqlite3_pagerget() - Space for a new page
104 # pager_open_journal() - Pager.aInJournal[] bitmap
105 # sqlite3pager_write() - For in-memory databases only: history page and
106 # statement history page.
107 # pager_stmt_begin() - Pager.aInStmt[] bitmap
109 # None of the above are a huge problem. The most troublesome failures are the
110 # transient malloc() calls in btree.c, which can occur during the tree-balance
111 # operation. This means the tree being balanced will be internally inconsistent
112 # after the malloc() fails. To avoid the corrupt tree being read by a
113 # READ_UNCOMMITTED query, we have to make sure the transaction or statement
114 # rollback occurs before sqlite3_step() returns, not during a subsequent
115 # sqlite3_finalize().
116 #--------------------------------------------------------------------------
118 #--------------------------------------------------------------------------
119 # NOTES ON TEST IMPLEMENTATION
121 # The tests in this file are implemented differently from those in other
122 # files. Instead, tests are specified using three primitives: SQL, PREP and
123 # TEST. Each primitive has a single argument. Primitives are processed in
124 # the order they are specified in the file.
126 # A TEST primitive specifies a TCL script as its argument. When a TEST
127 # directive is encountered the Tcl script is evaluated. Usually, this Tcl
128 # script contains one or more calls to [do_test].
130 # A PREP primitive specifies an SQL script as its argument. When a PREP
131 # directive is encountered the SQL is evaluated using database connection
134 # The SQL primitives are where the action happens. An SQL primitive must
135 # contain a single, valid SQL statement as its argument. When an SQL
136 # primitive is encountered, it is evaluated one or more times to test the
137 # behaviour of the system when malloc() fails during preparation or
138 # execution of said statement. The Nth time the statement is executed,
139 # the Nth malloc is said to fail. The statement is executed until it
140 # succeeds, i.e. (M+1) times, where M is the number of mallocs() required
141 # to prepare and execute the statement.
143 # Each time an SQL statement fails, the driver program (see proc [run_test]
144 # below) figures out if a transaction has been automatically rolled back.
145 # If not, it executes any TEST block immediately proceeding the SQL
146 # statement, then reexecutes the SQL statement with the next value of N.
148 # If a transaction has been automatically rolled back, then the driver
149 # program executes all the SQL specified as part of SQL or PREP primitives
150 # between the current SQL statement and the most recent "BEGIN". Any
151 # TEST block immediately proceeding the SQL statement is evaluated, and
152 # then the SQL statement reexecuted with the incremented N value.
154 # That make any sense? If not, read the code in [run_test] and it might.
156 # Extra restriction imposed by the implementation:
158 # * If a PREP block starts a transaction, it must finish it.
159 # * A PREP block may not close a transaction it did not start.
161 #--------------------------------------------------------------------------
164 # These procs are used to build up a "program" in global variable
165 # ::run_test_script. At the end of this file, the proc [run_test] is used
166 # to execute the program (and all test cases contained therein).
168 set ::run_test_sql_id 0
169 set ::run_test_script [list]
170 proc TEST {id t} {lappend ::run_test_script -test [list $id $t]}
171 proc PREP {p} {lappend ::run_test_script -prep [string trim $p]}
172 proc DEBUG {s} {lappend ::run_test_script -debug $s}
176 # SQL ?-norollback? <sql-text>
178 # Add an 'SQL' primitive to the program (see notes above). If the -norollback
179 # switch is present, then the statement is not allowed to automatically roll
180 # back any active transaction if malloc() fails. It must rollback the statement
183 proc SQL {a1 {a2 ""}} {
184 # An SQL primitive parameter is a list of three elements, an id, a boolean
185 # value indicating if the statement may cause transaction rollback when
186 # malloc() fails, and the sql statement itself.
187 set id [incr ::run_test_sql_id]
189 lappend ::run_test_script -sql [list $id true [string trim $a1]]
191 lappend ::run_test_script -sql [list $id false [string trim $a2]]
197 # A shorthand test to see if a transaction is active or not. The first
198 # argument - $id - is the integer number of the test case. The second
199 # argument is either 1 or 0, the expected value of the auto-commit flag.
201 proc TEST_AUTOCOMMIT {id a} {
202 TEST $id "do_test \$testid { sqlite3_get_autocommit \$::DB } {$a}"
205 #--------------------------------------------------------------------------
206 # Start of test program declaration
210 # Warm body test. A malloc() fails in the middle of a CREATE TABLE statement
211 # in a single-statement transaction on an empty database. Not too much can go
216 execsql {SELECT tbl_name FROM sqlite_master;}
220 CREATE TABLE IF NOT EXISTS abc(a, b, c);
224 execsql {SELECT tbl_name FROM sqlite_master;}
228 # Insert a couple of rows into the table. each insert is in its own
229 # transaction. test that the table is unpopulated before running the inserts
230 # (and hence after each failure of the first insert), and that it has been
231 # populated correctly after the final insert succeeds.
235 execsql {SELECT * FROM abc}
238 SQL {INSERT INTO abc VALUES(1, 2, 3);}
239 SQL {INSERT INTO abc VALUES(4, 5, 6);}
240 SQL {INSERT INTO abc VALUES(7, 8, 9);}
243 execsql {SELECT * FROM abc}
244 } {1 2 3 4 5 6 7 8 9}
247 # Test a CREATE INDEX statement. Because the table 'abc' is so small, the index
248 # will all fit on a single page, so this doesn't test too much that the CREATE
249 # TABLE statement didn't test. A few of the transient malloc()s in btree.c
252 SQL {CREATE INDEX abc_i ON abc(a, b, c);}
256 SELECT * FROM abc ORDER BY a DESC;
258 } {7 8 9 4 5 6 1 2 3}
261 # Test a DELETE statement. Also create a trigger and a view, just to make sure
262 # these statements don't have any obvious malloc() related bugs in them. Note
263 # that the test above will be executed each time the DELETE fails, so we're
264 # also testing rollback of a DELETE from a table with an index on it.
266 SQL {DELETE FROM abc WHERE a > 2;}
267 SQL {CREATE TRIGGER abc_t AFTER INSERT ON abc BEGIN SELECT 'trigger!'; END;}
268 SQL {CREATE VIEW abc_v AS SELECT * FROM abc;}
272 SELECT name, tbl_name FROM sqlite_master ORDER BY name;
275 } {abc abc abc_i abc abc_t abc abc_v abc_v 1 2 3}
279 BEGIN;DELETE FROM abc;
281 for {set i 1} {$i < 100} {incr i} {
283 set b "String value $i"
284 set c [string repeat X $i]
285 append sql "INSERT INTO abc VALUES ($a, '$b', '$c');"
291 DELETE FROM abc WHERE oid IN (SELECT oid FROM abc ORDER BY random() LIMIT 5);
295 execsql {SELECT count(*) FROM abc}
300 (oid == a) AND 'String value ' || a == b AND a == length(c)
306 DELETE FROM abc WHERE oid IN (SELECT oid FROM abc ORDER BY random() LIMIT 5);
310 execsql {SELECT count(*) FROM abc}
315 (oid == a) AND 'String value ' || a == b AND a == length(c)
321 DELETE FROM abc WHERE oid IN (SELECT oid FROM abc ORDER BY random() LIMIT 5);
325 execsql {SELECT count(*) FROM abc}
330 (oid == a) AND 'String value ' || a == b AND a == length(c)
336 set padding [string repeat X 500]
339 CREATE TABLE abc(a PRIMARY KEY, padding, b, c);
340 INSERT INTO abc VALUES(0, '$padding', 2, 2);
341 INSERT INTO abc VALUES(3, '$padding', 5, 5);
342 INSERT INTO abc VALUES(6, '$padding', 8, 8);
347 execsql {SELECT a, b, c FROM abc}
348 } {0 2 2 3 5 5 6 8 8}
352 SQL {INSERT INTO abc VALUES(9, 'XXXXX', 11, 12);}
354 SQL -norollback {UPDATE abc SET a = a + 1, c = c + 1;}
356 SQL {DELETE FROM abc WHERE a = 10;}
362 sqlite3_get_autocommit $::DB
365 execsql {SELECT a, b, c FROM abc}
366 } {1 2 3 4 5 6 7 8 9}
371 CREATE TABLE abc(a, padding, b, c);
372 INSERT INTO abc VALUES(1, '$padding', 2, 3);
373 INSERT INTO abc VALUES(4, '$padding', 5, 6);
374 INSERT INTO abc VALUES(7, '$padding', 8, 9);
375 CREATE INDEX abc_i ON abc(a, padding, b, c);
379 db eval {PRAGMA cache_size = 10}
383 SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc}
386 execsql {SELECT a, count(*) FROM abc GROUP BY a;}
389 SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc}
392 execsql {SELECT a, count(*) FROM abc GROUP BY a;}
395 SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc}
398 execsql {SELECT a, count(*) FROM abc GROUP BY a;}
401 SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc}
404 execsql {SELECT a, count(*) FROM abc GROUP BY a;}
410 execsql {SELECT a, count(*) FROM abc GROUP BY a;}
415 SQL {DELETE FROM abc WHERE oid %2}
418 execsql {SELECT a, count(*) FROM abc GROUP BY a;}
421 SQL {DELETE FROM abc}
424 execsql {SELECT * FROM abc}
430 execsql {SELECT a, count(*) FROM abc GROUP BY a;}
434 # Test some schema modifications inside of a transaction. These should all
435 # cause transaction rollback if they fail. Also query a view, to cover a bit
438 PREP {DROP VIEW abc_v;}
442 SELECT name, tbl_name FROM sqlite_master;
444 } {abc abc abc_i abc}
447 SQL {CREATE TABLE def(d, e, f);}
448 SQL {CREATE TABLE ghi(g, h, i);}
452 SELECT name, tbl_name FROM sqlite_master;
454 } {abc abc abc_i abc def def ghi ghi}
456 SQL {CREATE VIEW v1 AS SELECT * FROM def, ghi}
457 SQL {CREATE UNIQUE INDEX ghi_i1 ON ghi(g);}
461 SELECT name, tbl_name FROM sqlite_master;
463 } {abc abc abc_i abc def def ghi ghi v1 v1 ghi_i1 ghi}
465 SQL {INSERT INTO def VALUES('a', 'b', 'c')}
466 SQL {INSERT INTO def VALUES(1, 2, 3)}
467 SQL -norollback {INSERT INTO ghi SELECT * FROM def}
471 SELECT * FROM def, ghi WHERE d = g;
473 } {a b c a b c 1 2 3 1 2 3}
479 SELECT * FROM v1 WHERE d = g;
481 } {a b c a b c 1 2 3 1 2 3}
484 # Test a simple multi-file transaction
488 SQL {ATTACH 'test2.db' AS aux;}
490 SQL {CREATE TABLE aux.tbl2(x, y, z)}
491 SQL {INSERT INTO tbl2 VALUES(1, 2, 3)}
492 SQL {INSERT INTO def VALUES(4, 5, 6)}
496 SELECT * FROM tbl2, def WHERE d = x;
504 SELECT * FROM tbl2, def WHERE d = x;
510 # Test what happens when a malloc() fails while there are other active
511 # statements. This changes the way sqlite3VdbeHalt() works.
513 if {![info exists ::STMT32]} {
514 set sql "SELECT name FROM sqlite_master"
515 set ::STMT32 [sqlite3_prepare $::DB $sql -1 DUMMY]
517 sqlite3_step $::STMT32
524 execsql {SELECT * FROM ghi}
528 -- There is a unique index on ghi(g), so this statement may not cause
529 -- an automatic ROLLBACK. Hence the "-norollback" switch.
530 INSERT INTO ghi SELECT '2'||g, h, i FROM ghi;
533 if {[info exists ::STMT32]} {
535 sqlite3_finalize $::STMT32
543 # End of test program declaration
544 #--------------------------------------------------------------------------
546 proc run_test {arglist iRepeat {pcstart 0} {iFailStart 1}} {
547 if {[llength $arglist] %2} {
548 error "Uneven number of arguments to TEST"
551 for {set i 0} {$i < $pcstart} {incr i} {
552 set k2 [lindex $arglist [expr {2 * $i}]]
553 set v2 [lindex $arglist [expr {2 * $i + 1}]]
554 set ac [sqlite3_get_autocommit $::DB] ;# Auto-Commit
556 -sql {db eval [lindex $v2 2]}
560 set nac [sqlite3_get_autocommit $::DB] ;# New Auto-Commit
561 if {$ac && !$nac} {set begin_pc $i}
564 db rollback_hook [list incr ::rollback_hook_count]
566 set iFail $iFailStart
568 while {$pc*2 < [llength $arglist]} {
569 # Fetch the current instruction type and payload.
570 set k [lindex $arglist [expr {2 * $pc}]]
571 set v [lindex $arglist [expr {2 * $pc + 1}]]
573 # Id of this iteration:
574 set iterid "pc=$pc.iFail=$iFail$k"
579 foreach {id script} $v {}
580 set testid "malloc3-(test $id).$iterid"
586 set ::rollback_hook_count 0
589 set testid "malloc3-(integrity $id).$iterid"
591 set ac [sqlite3_get_autocommit $::DB] ;# Auto-Commit
592 sqlite3_memdebug_fail $iFail -repeat 0
593 set rc [catch {db eval [lindex $v 2]} msg] ;# True error occurs
594 set nac [sqlite3_get_autocommit $::DB] ;# New Auto-Commit
596 if {$rc != 0 && $nac && !$ac} {
597 # Before [db eval] the auto-commit flag was clear. Now it
598 # is set. Since an error occurred we assume this was not a
599 # commit - therefore a rollback occurred. Check that the
600 # rollback-hook was invoked.
601 do_test malloc3-rollback_hook_count.$iterid {
602 set ::rollback_hook_count
606 set nFail [sqlite3_memdebug_fail -1 -benigncnt nBenign]
608 # Successful execution of sql. The number of failed malloc()
609 # calls should be equal to the number of benign failures.
610 # Otherwise a malloc() failed and the error was not reported.
612 set expr {$nFail!=$nBenign}
614 error "Unreported malloc() failure, test \"$testid\", $expr"
618 # Before the [db eval] the auto-commit flag was set, now it
619 # is clear. We can deduce that a "BEGIN" statement has just
620 # been successfully executed.
626 integrity_check $testid
627 } elseif {[regexp {.*out of memory} $msg] || [db errorcode] == 3082} {
628 # Out of memory error, as expected.
630 integrity_check $testid
633 if {![lindex $v 1] && [db errorcode] != 3082} {
634 # error "Statement \"[lindex $v 2]\" caused a rollback"
637 for {set i $begin_pc} {$i < $pc} {incr i} {
638 set k2 [lindex $arglist [expr {2 * $i}]]
639 set v2 [lindex $arglist [expr {2 * $i + 1}]]
642 -sql {set catchupsql [lindex $v2 2]}
643 -prep {set catchupsql $v2}
652 # back up to the previous "-test" block.
653 while {[lindex $arglist [expr {2 * ($pc - 1)}]] == "-test"} {
668 default { error "Unknown switch: $k" }
673 # Turn off the Tcl interface's prepared statement caching facility. Then
674 # run the tests with "persistent" malloc failures.
675 sqlite3_extended_result_codes db 1
677 run_test $::run_test_script 1
679 # Close and reopen the db.
681 forcedelete test.db test.db-journal test2.db test2.db-journal
683 sqlite3_extended_result_codes db 1
684 set ::DB [sqlite3_connection_pointer db]
686 # Turn off the Tcl interface's prepared statement caching facility in
687 # the new connnection. Then run the tests with "transient" malloc failures.
689 run_test $::run_test_script 0
691 sqlite3_memdebug_fail -1