1# 2005 November 30 2# 3# The author disclaims copyright to this source code. In place of 4# a legal notice, here is a blessing: 5# 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. 9# 10#*********************************************************************** 11# 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 14# _finalize() calls. 15# 16# $Id: malloc3.test,v 1.24 2008/10/14 15:54:08 drh Exp $ 17 18set testdir [file dirname $argv0] 19source $testdir/tester.tcl 20source $testdir/malloc_common.tcl 21 22# Only run these tests if memory debugging is turned on. 23# 24if {!$MEMDEBUG} { 25 puts "Skipping malloc3 tests: not compiled with -DSQLITE_MEMDEBUG..." 26 finish_test 27 return 28} 29 30 31# Do not run these tests with an in-memory journal. 32# 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. 40# 41# Of course, this doesn't work with an in-memory journal. 42# 43if {[permutation]=="inmemory_journal"} { 44 finish_test 45 return 46} 47 48#-------------------------------------------------------------------------- 49# NOTES ON RECOVERING FROM A MALLOC FAILURE 50# 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 55# elsewhere. 56# 57# Overview: 58# 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. 63# 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 66# called): 67# 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 70# rolled back). 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. 73# 74# The caller can tell the difference between these two scenarios by invoking 75# _get_autocommit(). 76# 77# 78# Handling of sqlite3_reset(): 79# 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. 85# 86# 87# Other active SQL statements: 88# 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. 93# 94# Non-transient mallocs in btree.c: 95# * The Btree structure itself 96# * Each BtCursor structure 97# 98# Mallocs in pager.c: 99# readMasterJournal() - Space to read the master journal name 100# pager_delmaster() - Space for the entire master journal file 101# 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 108# 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#-------------------------------------------------------------------------- 117 118#-------------------------------------------------------------------------- 119# NOTES ON TEST IMPLEMENTATION 120# 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. 125# 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]. 129# 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 132# [db]. 133# 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. 142# 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. 147# 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. 153# 154# That make any sense? If not, read the code in [run_test] and it might. 155# 156# Extra restriction imposed by the implementation: 157# 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. 160# 161#-------------------------------------------------------------------------- 162 163 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). 167# 168set ::run_test_sql_id 0 169set ::run_test_script [list] 170proc TEST {id t} {lappend ::run_test_script -test [list $id $t]} 171proc PREP {p} {lappend ::run_test_script -prep [string trim $p]} 172proc DEBUG {s} {lappend ::run_test_script -debug $s} 173 174# SQL -- 175# 176# SQL ?-norollback? <sql-text> 177# 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 181# transaction only. 182# 183proc 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] 188 if {$a2 == ""} { 189 lappend ::run_test_script -sql [list $id true [string trim $a1]] 190 } else { 191 lappend ::run_test_script -sql [list $id false [string trim $a2]] 192 } 193} 194 195# TEST_AUTOCOMMIT -- 196# 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. 200# 201proc TEST_AUTOCOMMIT {id a} { 202 TEST $id "do_test \$testid { sqlite3_get_autocommit \$::DB } {$a}" 203} 204 205#-------------------------------------------------------------------------- 206# Start of test program declaration 207# 208 209 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 212# wrong here. 213# 214TEST 1 { 215 do_test $testid { 216 execsql {SELECT tbl_name FROM sqlite_master;} 217 } {} 218} 219SQL { 220 CREATE TABLE IF NOT EXISTS abc(a, b, c); 221} 222TEST 2 { 223 do_test $testid.1 { 224 execsql {SELECT tbl_name FROM sqlite_master;} 225 } {abc} 226} 227 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. 232# 233TEST 3 { 234 do_test $testid.2 { 235 execsql {SELECT * FROM abc} 236 } {} 237} 238SQL {INSERT INTO abc VALUES(1, 2, 3);} 239SQL {INSERT INTO abc VALUES(4, 5, 6);} 240SQL {INSERT INTO abc VALUES(7, 8, 9);} 241TEST 4 { 242 do_test $testid { 243 execsql {SELECT * FROM abc} 244 } {1 2 3 4 5 6 7 8 9} 245} 246 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 250# perhaps. 251# 252SQL {CREATE INDEX abc_i ON abc(a, b, c);} 253TEST 4 { 254 do_test $testid { 255 execsql { 256 SELECT * FROM abc ORDER BY a DESC; 257 } 258 } {7 8 9 4 5 6 1 2 3} 259} 260 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. 265# 266SQL {DELETE FROM abc WHERE a > 2;} 267SQL {CREATE TRIGGER abc_t AFTER INSERT ON abc BEGIN SELECT 'trigger!'; END;} 268SQL {CREATE VIEW abc_v AS SELECT * FROM abc;} 269TEST 5 { 270 do_test $testid { 271 execsql { 272 SELECT name, tbl_name FROM sqlite_master ORDER BY name; 273 SELECT * FROM abc; 274 } 275 } {abc abc abc_i abc abc_t abc abc_v abc_v 1 2 3} 276} 277 278set sql { 279 BEGIN;DELETE FROM abc; 280} 281for {set i 1} {$i < 100} {incr i} { 282 set a $i 283 set b "String value $i" 284 set c [string repeat X $i] 285 append sql "INSERT INTO abc VALUES ($a, '$b', '$c');" 286} 287append sql {COMMIT;} 288PREP $sql 289 290SQL { 291 DELETE FROM abc WHERE oid IN (SELECT oid FROM abc ORDER BY random() LIMIT 5); 292} 293TEST 6 { 294 do_test $testid.1 { 295 execsql {SELECT count(*) FROM abc} 296 } {94} 297 do_test $testid.2 { 298 execsql { 299 SELECT min( 300 (oid == a) AND 'String value ' || a == b AND a == length(c) 301 ) FROM abc; 302 } 303 } {1} 304} 305SQL { 306 DELETE FROM abc WHERE oid IN (SELECT oid FROM abc ORDER BY random() LIMIT 5); 307} 308TEST 7 { 309 do_test $testid { 310 execsql {SELECT count(*) FROM abc} 311 } {89} 312 do_test $testid { 313 execsql { 314 SELECT min( 315 (oid == a) AND 'String value ' || a == b AND a == length(c) 316 ) FROM abc; 317 } 318 } {1} 319} 320SQL { 321 DELETE FROM abc WHERE oid IN (SELECT oid FROM abc ORDER BY random() LIMIT 5); 322} 323TEST 9 { 324 do_test $testid { 325 execsql {SELECT count(*) FROM abc} 326 } {84} 327 do_test $testid { 328 execsql { 329 SELECT min( 330 (oid == a) AND 'String value ' || a == b AND a == length(c) 331 ) FROM abc; 332 } 333 } {1} 334} 335 336set padding [string repeat X 500] 337PREP [subst { 338 DROP TABLE abc; 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); 343}] 344 345TEST 10 { 346 do_test $testid { 347 execsql {SELECT a, b, c FROM abc} 348 } {0 2 2 3 5 5 6 8 8} 349} 350 351SQL {BEGIN;} 352SQL {INSERT INTO abc VALUES(9, 'XXXXX', 11, 12);} 353TEST_AUTOCOMMIT 11 0 354SQL -norollback {UPDATE abc SET a = a + 1, c = c + 1;} 355TEST_AUTOCOMMIT 12 0 356SQL {DELETE FROM abc WHERE a = 10;} 357TEST_AUTOCOMMIT 13 0 358SQL {COMMIT;} 359 360TEST 14 { 361 do_test $testid.1 { 362 sqlite3_get_autocommit $::DB 363 } {1} 364 do_test $testid.2 { 365 execsql {SELECT a, b, c FROM abc} 366 } {1 2 3 4 5 6 7 8 9} 367} 368 369PREP [subst { 370 DROP TABLE abc; 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); 376}] 377 378TEST 15 { 379 db eval {PRAGMA cache_size = 10} 380} 381 382SQL {BEGIN;} 383SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc} 384TEST 16 { 385 do_test $testid { 386 execsql {SELECT a, count(*) FROM abc GROUP BY a;} 387 } {1 2 4 2 7 2} 388} 389SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc} 390TEST 17 { 391 do_test $testid { 392 execsql {SELECT a, count(*) FROM abc GROUP BY a;} 393 } {1 4 4 4 7 4} 394} 395SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc} 396TEST 18 { 397 do_test $testid { 398 execsql {SELECT a, count(*) FROM abc GROUP BY a;} 399 } {1 8 4 8 7 8} 400} 401SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc} 402TEST 19 { 403 do_test $testid { 404 execsql {SELECT a, count(*) FROM abc GROUP BY a;} 405 } {1 16 4 16 7 16} 406} 407SQL {COMMIT;} 408TEST 21 { 409 do_test $testid { 410 execsql {SELECT a, count(*) FROM abc GROUP BY a;} 411 } {1 16 4 16 7 16} 412} 413 414SQL {BEGIN;} 415SQL {DELETE FROM abc WHERE oid %2} 416TEST 22 { 417 do_test $testid { 418 execsql {SELECT a, count(*) FROM abc GROUP BY a;} 419 } {1 8 4 8 7 8} 420} 421SQL {DELETE FROM abc} 422TEST 23 { 423 do_test $testid { 424 execsql {SELECT * FROM abc} 425 } {} 426} 427SQL {ROLLBACK;} 428TEST 24 { 429 do_test $testid { 430 execsql {SELECT a, count(*) FROM abc GROUP BY a;} 431 } {1 16 4 16 7 16} 432} 433 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 436# more code. 437# 438PREP {DROP VIEW abc_v;} 439TEST 25 { 440 do_test $testid { 441 execsql { 442 SELECT name, tbl_name FROM sqlite_master; 443 } 444 } {abc abc abc_i abc} 445} 446SQL {BEGIN;} 447SQL {CREATE TABLE def(d, e, f);} 448SQL {CREATE TABLE ghi(g, h, i);} 449TEST 26 { 450 do_test $testid { 451 execsql { 452 SELECT name, tbl_name FROM sqlite_master; 453 } 454 } {abc abc abc_i abc def def ghi ghi} 455} 456SQL {CREATE VIEW v1 AS SELECT * FROM def, ghi} 457SQL {CREATE UNIQUE INDEX ghi_i1 ON ghi(g);} 458TEST 27 { 459 do_test $testid { 460 execsql { 461 SELECT name, tbl_name FROM sqlite_master; 462 } 463 } {abc abc abc_i abc def def ghi ghi v1 v1 ghi_i1 ghi} 464} 465SQL {INSERT INTO def VALUES('a', 'b', 'c')} 466SQL {INSERT INTO def VALUES(1, 2, 3)} 467SQL -norollback {INSERT INTO ghi SELECT * FROM def} 468TEST 28 { 469 do_test $testid { 470 execsql { 471 SELECT * FROM def, ghi WHERE d = g; 472 } 473 } {a b c a b c 1 2 3 1 2 3} 474} 475SQL {COMMIT} 476TEST 29 { 477 do_test $testid { 478 execsql { 479 SELECT * FROM v1 WHERE d = g; 480 } 481 } {a b c a b c 1 2 3 1 2 3} 482} 483 484# Test a simple multi-file transaction 485# 486forcedelete test2.db 487ifcapable attach { 488 SQL {ATTACH 'test2.db' AS aux;} 489 SQL {BEGIN} 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)} 493 TEST 30 { 494 do_test $testid { 495 execsql { 496 SELECT * FROM tbl2, def WHERE d = x; 497 } 498 } {1 2 3 1 2 3} 499 } 500 SQL {COMMIT} 501 TEST 31 { 502 do_test $testid { 503 execsql { 504 SELECT * FROM tbl2, def WHERE d = x; 505 } 506 } {1 2 3 1 2 3} 507 } 508} 509 510# Test what happens when a malloc() fails while there are other active 511# statements. This changes the way sqlite3VdbeHalt() works. 512TEST 32 { 513 if {![info exists ::STMT32]} { 514 set sql "SELECT name FROM sqlite_master" 515 set ::STMT32 [sqlite3_prepare $::DB $sql -1 DUMMY] 516 do_test $testid { 517 sqlite3_step $::STMT32 518 } {SQLITE_ROW} 519 } 520} 521SQL BEGIN 522TEST 33 { 523 do_test $testid { 524 execsql {SELECT * FROM ghi} 525 } {a b c 1 2 3} 526} 527SQL -norollback { 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; 531} 532TEST 34 { 533 if {[info exists ::STMT32]} { 534 do_test $testid { 535 sqlite3_finalize $::STMT32 536 } {SQLITE_OK} 537 unset ::STMT32 538 } 539} 540SQL COMMIT 541 542# 543# End of test program declaration 544#-------------------------------------------------------------------------- 545 546proc run_test {arglist iRepeat {pcstart 0} {iFailStart 1}} { 547 if {[llength $arglist] %2} { 548 error "Uneven number of arguments to TEST" 549 } 550 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 555 switch -- $k2 { 556 -sql {db eval [lindex $v2 2]} 557 -prep {db eval $v2} 558 -debug {eval $v2} 559 } 560 set nac [sqlite3_get_autocommit $::DB] ;# New Auto-Commit 561 if {$ac && !$nac} {set begin_pc $i} 562 } 563 564 db rollback_hook [list incr ::rollback_hook_count] 565 566 set iFail $iFailStart 567 set pc $pcstart 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}]] 572 573 # Id of this iteration: 574 set iterid "pc=$pc.iFail=$iFail$k" 575 576 switch -- $k { 577 578 -test { 579 foreach {id script} $v {} 580 set testid "malloc3-(test $id).$iterid" 581 eval $script 582 incr pc 583 } 584 585 -sql { 586 set ::rollback_hook_count 0 587 588 set id [lindex $v 0] 589 set testid "malloc3-(integrity $id).$iterid" 590 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 595 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 603 } {1} 604 } 605 606 set nFail [sqlite3_memdebug_fail -1 -benigncnt nBenign] 607 if {$rc == 0} { 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. 611 # 612 set expr {$nFail!=$nBenign} 613 if {[expr $expr]} { 614 error "Unreported malloc() failure, test \"$testid\", $expr" 615 } 616 617 if {$ac && !$nac} { 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. 621 set begin_pc $pc 622 } 623 624 incr pc 625 set iFail 1 626 integrity_check $testid 627 } elseif {[regexp {.*out of memory} $msg] || [db errorcode] == 3082} { 628 # Out of memory error, as expected. 629 # 630 integrity_check $testid 631 incr iFail 632 if {$nac && !$ac} { 633 if {![lindex $v 1] && [db errorcode] != 3082} { 634 # error "Statement \"[lindex $v 2]\" caused a rollback" 635 } 636 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}]] 640 set catchupsql "" 641 switch -- $k2 { 642 -sql {set catchupsql [lindex $v2 2]} 643 -prep {set catchupsql $v2} 644 } 645 db eval $catchupsql 646 } 647 } 648 } else { 649 error $msg 650 } 651 652 # back up to the previous "-test" block. 653 while {[lindex $arglist [expr {2 * ($pc - 1)}]] == "-test"} { 654 incr pc -1 655 } 656 } 657 658 -prep { 659 db eval $v 660 incr pc 661 } 662 663 -debug { 664 eval $v 665 incr pc 666 } 667 668 default { error "Unknown switch: $k" } 669 } 670 } 671} 672 673# Turn off the Tcl interface's prepared statement caching facility. Then 674# run the tests with "persistent" malloc failures. 675sqlite3_extended_result_codes db 1 676db cache size 0 677run_test $::run_test_script 1 678 679# Close and reopen the db. 680db close 681forcedelete test.db test.db-journal test2.db test2.db-journal 682sqlite3 db test.db 683sqlite3_extended_result_codes db 1 684set ::DB [sqlite3_connection_pointer db] 685 686# Turn off the Tcl interface's prepared statement caching facility in 687# the new connnection. Then run the tests with "transient" malloc failures. 688db cache size 0 689run_test $::run_test_script 0 690 691sqlite3_memdebug_fail -1 692finish_test 693