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.7 2006/01/20 10:55:05 danielk1977 Exp $ 17 18set testdir [file dirname $argv0] 19source $testdir/tester.tcl 20 21# Only run these tests if memory debugging is turned on. 22if {[info command sqlite_malloc_stat]==""} { 23 puts "Skipping malloc tests: not compiled with -DSQLITE_MEMDEBUG..." 24 finish_test 25 return 26} 27 28#-------------------------------------------------------------------------- 29# NOTES ON RECOVERING FROM A MALLOC FAILURE 30# 31# The tests in this file test the behaviours described in the following 32# paragraphs. These tests test the behaviour of the system when malloc() fails 33# inside of a call to _prepare(), _step(), _finalize() or _reset(). The 34# handling of malloc() failures within ancillary procedures is tested 35# elsewhere. 36# 37# Overview: 38# 39# Executing a statement is done in three stages (prepare, step and finalize). A 40# malloc() failure may occur within any stage. If a memory allocation fails 41# during statement preparation, no statement handle is returned. From the users 42# point of view the system state is as if _prepare() had never been called. 43# 44# If the memory allocation fails during the _step() or _finalize() calls, then 45# the database may be left in one of two states (after finalize() has been 46# called): 47# 48# * As if the neither _step() nor _finalize() had ever been called on 49# the statement handle (i.e. any changes made by the statement are 50# rolled back). 51# * The current transaction may be rolled back. In this case a hot-journal 52# may or may not actually be present in the filesystem. 53# 54# The caller can tell the difference between these two scenarios by invoking 55# _get_autocommit(). 56# 57# 58# Handling of sqlite3_reset(): 59# 60# If a malloc() fails while executing an sqlite3_reset() call, this is handled 61# in the same way as a failure within _finalize(). The statement handle 62# is not deleted and must be passed to _finalize() for resource deallocation. 63# Attempting to _step() or _reset() the statement after a failed _reset() will 64# always return SQLITE_NOMEM. 65# 66# 67# Other active SQL statements: 68# 69# The effect of a malloc failure on concurrently executing SQL statements, 70# particularly when the statement is executing with READ_UNCOMMITTED set and 71# the malloc() failure mandates statement rollback only. Currently, if 72# transaction rollback is required, all other vdbe's are aborted. 73# 74# Non-transient mallocs in btree.c: 75# * The Btree structure itself 76# * Each BtCursor structure 77# 78# Mallocs in pager.c: 79# readMasterJournal() - Space to read the master journal name 80# pager_delmaster() - Space for the entire master journal file 81# 82# sqlite3pager_open() - The pager structure itself 83# sqlite3_pagerget() - Space for a new page 84# pager_open_journal() - Pager.aInJournal[] bitmap 85# sqlite3pager_write() - For in-memory databases only: history page and 86# statement history page. 87# pager_stmt_begin() - Pager.aInStmt[] bitmap 88# 89# None of the above are a huge problem. The most troublesome failures are the 90# transient malloc() calls in btree.c, which can occur during the tree-balance 91# operation. This means the tree being balanced will be internally inconsistent 92# after the malloc() fails. To avoid the corrupt tree being read by a 93# READ_UNCOMMITTED query, we have to make sure the transaction or statement 94# rollback occurs before sqlite3_step() returns, not during a subsequent 95# sqlite3_finalize(). 96#-------------------------------------------------------------------------- 97 98#-------------------------------------------------------------------------- 99# NOTES ON TEST IMPLEMENTATION 100# 101# The tests in this file are implemented differently from those in other 102# files. Instead, tests are specified using three primitives: SQL, PREP and 103# TEST. Each primitive has a single argument. Primitives are processed in 104# the order they are specified in the file. 105# 106# A TEST primitive specifies a TCL script as it's argument. When a TEST 107# directive is encountered the Tcl script is evaluated. Usually, this Tcl 108# script contains one or more calls to [do_test]. 109# 110# A PREP primitive specifies an SQL script as it's argument. When a PREP 111# directive is encountered the SQL is evaluated using database connection 112# [db]. 113# 114# The SQL primitives are where the action happens. An SQL primitive must 115# contain a single, valid SQL statement as it's argument. When an SQL 116# primitive is encountered, it is evaluated one or more times to test the 117# behaviour of the system when malloc() fails during preparation or 118# execution of said statement. The Nth time the statement is executed, 119# the Nth malloc is said to fail. The statement is executed until it 120# succeeds, i.e. (M+1) times, where M is the number of mallocs() required 121# to prepare and execute the statement. 122# 123# Each time an SQL statement fails, the driver program (see proc [run_test] 124# below) figures out if a transaction has been automatically rolled back. 125# If not, it executes any TEST block immediately proceeding the SQL 126# statement, then reexecutes the SQL statement with the next value of N. 127# 128# If a transaction has been automatically rolled back, then the driver 129# program executes all the SQL specified as part of SQL or PREP primitives 130# between the current SQL statement and the most recent "BEGIN". Any 131# TEST block immediately proceeding the SQL statement is evaluated, and 132# then the SQL statement reexecuted with the incremented N value. 133# 134# That make any sense? If not, read the code in [run_test] and it might. 135# 136# Extra restriction imposed by the implementation: 137# 138# * If a PREP block starts a transaction, it must finish it. 139# * A PREP block may not close a transaction it did not start. 140# 141#-------------------------------------------------------------------------- 142 143 144# These procs are used to build up a "program" in global variable 145# ::run_test_script. At the end of this file, the proc [run_test] is used 146# to execute the program (and all test cases contained therein). 147# 148set ::run_test_script [list] 149proc TEST {id t} {lappend ::run_test_script -test [list $id $t]} 150proc PREP {p} {lappend ::run_test_script -prep [string trim $p]} 151 152# SQL -- 153# 154# SQL ?-norollback? <sql-text> 155# 156# Add an 'SQL' primitive to the program (see notes above). If the -norollback 157# switch is present, then the statement is not allowed to automatically roll 158# back any active transaction if malloc() fails. It must rollback the statement 159# transaction only. 160# 161proc SQL {a1 {a2 ""}} { 162 # An SQL primitive parameter is a list of two elements, a boolean value 163 # indicating if the statement may cause transaction rollback when malloc() 164 # fails, and the sql statement itself. 165 if {$a2 == ""} { 166 lappend ::run_test_script -sql [list true [string trim $a1]] 167 } else { 168 lappend ::run_test_script -sql [list false [string trim $a2]] 169 } 170} 171 172# TEST_AUTOCOMMIT -- 173# 174# A shorthand test to see if a transaction is active or not. The first 175# argument - $id - is the integer number of the test case. The second 176# argument is either 1 or 0, the expected value of the auto-commit flag. 177# 178proc TEST_AUTOCOMMIT {id a} { 179 TEST $id "do_test \$testid { sqlite3_get_autocommit $::DB } {$a}" 180} 181 182#-------------------------------------------------------------------------- 183# Start of test program declaration 184# 185 186 187# Warm body test. A malloc() fails in the middle of a CREATE TABLE statement 188# in a single-statement transaction on an empty database. Not too much can go 189# wrong here. 190# 191TEST 1 { 192 do_test $testid { 193 execsql {SELECT tbl_name FROM sqlite_master;} 194 } {} 195} 196SQL { 197 CREATE TABLE abc(a, b, c); 198} 199TEST 2 { 200 do_test $testid.1 { 201 execsql {SELECT tbl_name FROM sqlite_master;} 202 } {abc} 203} 204 205# Insert a couple of rows into the table. each insert is in it's own 206# transaction. test that the table is unpopulated before running the inserts 207# (and hence after each failure of the first insert), and that it has been 208# populated correctly after the final insert succeeds. 209# 210TEST 3 { 211 do_test $testid.2 { 212 execsql {SELECT * FROM abc} 213 } {} 214} 215SQL {INSERT INTO abc VALUES(1, 2, 3);} 216SQL {INSERT INTO abc VALUES(4, 5, 6);} 217SQL {INSERT INTO abc VALUES(7, 8, 9);} 218TEST 4 { 219 do_test $testid { 220 execsql {SELECT * FROM abc} 221 } {1 2 3 4 5 6 7 8 9} 222} 223 224# Test a CREATE INDEX statement. Because the table 'abc' is so small, the index 225# will all fit on a single page, so this doesn't test too much that the CREATE 226# TABLE statement didn't test. A few of the transient malloc()s in btree.c 227# perhaps. 228# 229SQL {CREATE INDEX abc_i ON abc(a, b, c);} 230TEST 4 { 231 do_test $testid { 232 execsql { 233 SELECT * FROM abc ORDER BY a DESC; 234 } 235 } {7 8 9 4 5 6 1 2 3} 236} 237 238# Test a DELETE statement. Also create a trigger and a view, just to make sure 239# these statements don't have any obvious malloc() related bugs in them. Note 240# that the test above will be executed each time the DELETE fails, so we're 241# also testing rollback of a DELETE from a table with an index on it. 242# 243SQL {DELETE FROM abc WHERE a > 2;} 244SQL {CREATE TRIGGER abc_t AFTER INSERT ON abc BEGIN SELECT 'trigger!'; END;} 245SQL {CREATE VIEW abc_v AS SELECT * FROM abc;} 246TEST 5 { 247 do_test $testid { 248 execsql { 249 SELECT name, tbl_name FROM sqlite_master ORDER BY name; 250 SELECT * FROM abc; 251 } 252 } {abc abc abc_i abc abc_t abc abc_v abc_v 1 2 3} 253} 254 255set sql { 256 BEGIN;DELETE FROM abc; 257} 258for {set i 1} {$i < 100} {incr i} { 259 set a $i 260 set b "String value $i" 261 set c [string repeat X $i] 262 append sql "INSERT INTO abc VALUES ($a, '$b', '$c');" 263} 264append sql {COMMIT;} 265PREP $sql 266 267SQL { 268 DELETE FROM abc WHERE oid IN (SELECT oid FROM abc ORDER BY random() LIMIT 5); 269} 270TEST 6 { 271 do_test $testid.1 { 272 execsql {SELECT count(*) FROM abc} 273 } {94} 274 do_test $testid.2 { 275 execsql { 276 SELECT min( 277 (oid == a) AND 'String value ' || a == b AND a == length(c) 278 ) FROM abc; 279 } 280 } {1} 281} 282SQL { 283 DELETE FROM abc WHERE oid IN (SELECT oid FROM abc ORDER BY random() LIMIT 5); 284} 285TEST 7 { 286 do_test $testid { 287 execsql {SELECT count(*) FROM abc} 288 } {89} 289 do_test $testid { 290 execsql { 291 SELECT min( 292 (oid == a) AND 'String value ' || a == b AND a == length(c) 293 ) FROM abc; 294 } 295 } {1} 296} 297SQL { 298 DELETE FROM abc WHERE oid IN (SELECT oid FROM abc ORDER BY random() LIMIT 5); 299} 300TEST 9 { 301 do_test $testid { 302 execsql {SELECT count(*) FROM abc} 303 } {84} 304 do_test $testid { 305 execsql { 306 SELECT min( 307 (oid == a) AND 'String value ' || a == b AND a == length(c) 308 ) FROM abc; 309 } 310 } {1} 311} 312 313set padding [string repeat X 500] 314PREP [subst { 315 DROP TABLE abc; 316 CREATE TABLE abc(a PRIMARY KEY, padding, b, c); 317 INSERT INTO abc VALUES(0, '$padding', 2, 2); 318 INSERT INTO abc VALUES(3, '$padding', 5, 5); 319 INSERT INTO abc VALUES(6, '$padding', 8, 8); 320}] 321 322TEST 10 { 323 do_test $testid { 324 execsql {SELECT a, b, c FROM abc} 325 } {0 2 2 3 5 5 6 8 8} 326} 327 328SQL {BEGIN;} 329SQL {INSERT INTO abc VALUES(9, 'XXXXX', 11, 12);} 330TEST_AUTOCOMMIT 11 0 331SQL -norollback {UPDATE abc SET a = a + 1, c = c + 1;} 332TEST_AUTOCOMMIT 12 0 333SQL {DELETE FROM abc WHERE a = 10;} 334TEST_AUTOCOMMIT 13 0 335SQL {COMMIT;} 336 337TEST 14 { 338 do_test $testid.1 { 339 sqlite3_get_autocommit $::DB 340 } {1} 341 do_test $testid.2 { 342 execsql {SELECT a, b, c FROM abc} 343 } {1 2 3 4 5 6 7 8 9} 344} 345 346PREP [subst { 347 DROP TABLE abc; 348 CREATE TABLE abc(a, padding, b, c); 349 INSERT INTO abc VALUES(1, '$padding', 2, 3); 350 INSERT INTO abc VALUES(4, '$padding', 5, 6); 351 INSERT INTO abc VALUES(7, '$padding', 8, 9); 352 CREATE INDEX abc_i ON abc(a, padding, b, c); 353}] 354 355TEST 15 { 356 db eval {PRAGMA cache_size = 10} 357} 358 359SQL {BEGIN;} 360SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc} 361TEST 16 { 362 do_test $testid { 363 execsql {SELECT a, count(*) FROM abc GROUP BY a;} 364 } {1 2 4 2 7 2} 365} 366SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc} 367TEST 17 { 368 do_test $testid { 369 execsql {SELECT a, count(*) FROM abc GROUP BY a;} 370 } {1 4 4 4 7 4} 371} 372SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc} 373TEST 18 { 374 do_test $testid { 375 execsql {SELECT a, count(*) FROM abc GROUP BY a;} 376 } {1 8 4 8 7 8} 377} 378SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc} 379TEST 19 { 380 do_test $testid { 381 execsql {SELECT a, count(*) FROM abc GROUP BY a;} 382 } {1 16 4 16 7 16} 383} 384SQL {COMMIT;} 385TEST 21 { 386 do_test $testid { 387 execsql {SELECT a, count(*) FROM abc GROUP BY a;} 388 } {1 16 4 16 7 16} 389} 390 391SQL {BEGIN;} 392SQL {DELETE FROM abc WHERE oid %2} 393TEST 22 { 394 do_test $testid { 395 execsql {SELECT a, count(*) FROM abc GROUP BY a;} 396 } {1 8 4 8 7 8} 397} 398SQL {DELETE FROM abc} 399TEST 23 { 400 do_test $testid { 401 execsql {SELECT * FROM abc} 402 } {} 403} 404SQL {ROLLBACK;} 405TEST 24 { 406 do_test $testid { 407 execsql {SELECT a, count(*) FROM abc GROUP BY a;} 408 } {1 16 4 16 7 16} 409} 410 411# Test some schema modifications inside of a transaction. These should all 412# cause transaction rollback if they fail. Also query a view, to cover a bit 413# more code. 414# 415PREP {DROP VIEW abc_v;} 416TEST 25 { 417 do_test $testid { 418 execsql { 419 SELECT name, tbl_name FROM sqlite_master; 420 } 421 } {abc abc abc_i abc} 422} 423SQL {BEGIN;} 424SQL {CREATE TABLE def(d, e, f);} 425SQL {CREATE TABLE ghi(g, h, i);} 426TEST 26 { 427 do_test $testid { 428 execsql { 429 SELECT name, tbl_name FROM sqlite_master; 430 } 431 } {abc abc abc_i abc def def ghi ghi} 432} 433SQL {CREATE VIEW v1 AS SELECT * FROM def, ghi} 434SQL {CREATE UNIQUE INDEX ghi_i1 ON ghi(g);} 435TEST 27 { 436 do_test $testid { 437 execsql { 438 SELECT name, tbl_name FROM sqlite_master; 439 } 440 } {abc abc abc_i abc def def ghi ghi v1 v1 ghi_i1 ghi} 441} 442SQL {INSERT INTO def VALUES('a', 'b', 'c')} 443SQL {INSERT INTO def VALUES(1, 2, 3)} 444SQL -norollback {INSERT INTO ghi SELECT * FROM def} 445TEST 28 { 446 do_test $testid { 447 execsql { 448 SELECT * FROM def, ghi WHERE d = g; 449 } 450 } {a b c a b c 1 2 3 1 2 3} 451} 452SQL {COMMIT} 453TEST 29 { 454 do_test $testid { 455 execsql { 456 SELECT * FROM v1 WHERE d = g; 457 } 458 } {a b c a b c 1 2 3 1 2 3} 459} 460 461# Test a simple multi-file transaction 462# 463file delete -force test2.db 464SQL {ATTACH 'test2.db' AS aux;} 465SQL {BEGIN} 466SQL {CREATE TABLE aux.tbl2(x, y, z)} 467SQL {INSERT INTO tbl2 VALUES(1, 2, 3)} 468SQL {INSERT INTO def VALUES(4, 5, 6)} 469TEST 30 { 470 do_test $testid { 471 execsql { 472 SELECT * FROM tbl2, def WHERE d = x; 473 } 474 } {1 2 3 1 2 3} 475} 476SQL {COMMIT} 477TEST 31 { 478 do_test $testid { 479 execsql { 480 SELECT * FROM tbl2, def WHERE d = x; 481 } 482 } {1 2 3 1 2 3} 483} 484 485# Test what happens when a malloc() fails while there are other active 486# statements. This changes the way sqlite3VdbeHalt() works. 487TEST 32 { 488 if {![info exists ::STMT32]} { 489 set sql "SELECT name FROM sqlite_master" 490 set ::STMT32 [sqlite3_prepare $::DB $sql -1 DUMMY] 491 do_test $testid { 492 sqlite3_step $::STMT32 493 } {SQLITE_ROW} 494 } 495puts [execsql {SELECT * FROM ghi}] 496} 497SQL { 498 BEGIN; 499 INSERT INTO ghi SELECT * FROM ghi; 500 COMMIT; 501} 502 503# 504# End of test program declaration 505#-------------------------------------------------------------------------- 506 507proc run_test {arglist {pcstart 0} {iFailStart 1}} { 508 if {[llength $arglist] %2} { 509 error "Uneven number of arguments to TEST" 510 } 511 512 for {set i 0} {$i < $pcstart} {incr i} { 513 set k2 [lindex $arglist [expr 2 * $i]] 514 set v2 [lindex $arglist [expr 2 * $i + 1]] 515 set ac [sqlite3_get_autocommit $::DB] ;# Auto-Commit 516# puts "STARTUP" 517 switch -- $k2 { 518 -sql {db eval [lindex $v2 1]} 519 -prep {db eval $v2} 520 } 521 set nac [sqlite3_get_autocommit $::DB] ;# New Auto-Commit 522 if {$ac && !$nac} {set begin_pc $i} 523 } 524 525 db rollback_hook [list incr ::rollback_hook_count] 526 527 set iFail $iFailStart 528 set pc $pcstart 529 while {$pc*2 < [llength $arglist]} { 530 531 # Id of this iteration: 532 set iterid "(pc $pc).(iFail $iFail)" 533 534 set k [lindex $arglist [expr 2 * $pc]] 535 set v [lindex $arglist [expr 2 * $pc + 1]] 536 537 switch -- $k { 538 539 -test { 540 foreach {id script} $v {} 541 set testid "malloc3-(test $id).$iterid" 542 eval $script 543 incr pc 544 } 545 546 -sql { 547 set ::rollback_hook_count 0 548 549 set ac [sqlite3_get_autocommit $::DB] ;# Auto-Commit 550 sqlite_malloc_fail $iFail 551# puts "SQL $iterid [lindex $v 1]" 552 set rc [catch {db eval [lindex $v 1]} msg] ;# True error occurs 553# puts "rc = $rc msg = \"$msg\"" 554 set nac [sqlite3_get_autocommit $::DB] ;# New Auto-Commit 555 556 557 if {$rc != 0 && $nac && !$ac} { 558 # Before [db eval] the auto-commit flag was clear. Now it 559 # is set. Since an error occured we assume this was not a 560 # commit - therefore a rollback occured. Check that the 561 # rollback-hook was invoked. 562 do_test malloc3-rollback_hook.$iterid { 563 set ::rollback_hook_count 564 } {1} 565 } 566 567 if {$rc == 0} { 568 # Successful execution of sql. Our "mallocs-until-failure" 569 # count should be greater than 0. Otherwise a malloc() failed 570 # and the error was not reported. 571 if {[lindex [sqlite_malloc_stat] 2] <= 0} { 572 error "Unreported malloc() failure" 573 } 574 575 if {$ac && !$nac} { 576 # Before the [db eval] the auto-commit flag was set, now it 577 # is clear. We can deduce that a "BEGIN" statement has just 578 # been successfully executed. 579 set begin_pc $pc 580 } 581 582 incr pc 583 set iFail 1 584 sqlite_malloc_fail 0 585 integrity_check "malloc3-(integrity).$iterid" 586 } elseif {[regexp {.*out of memory} $msg]} { 587 # Out of memory error, as expected 588 integrity_check "malloc3-(integrity).$iterid" 589 incr iFail 590 if {$nac && !$ac} { 591 592 if {![lindex $v 0]} { 593 error "Statement \"[lindex $v 1]\" caused a rollback" 594 } 595 596# puts "Statement \"[lindex $v 1]\" caused a rollback" 597 for {set i $begin_pc} {$i < $pc} {incr i} { 598 set k2 [lindex $arglist [expr 2 * $i]] 599 set v2 [lindex $arglist [expr 2 * $i + 1]] 600 set catchupsql "" 601 switch -- $k2 { 602 -sql {set catchupsql [lindex $v2 1]} 603 -prep {set catchupsql $v2} 604 } 605# puts "CATCHUP $iterid $i $catchupsql" 606 db eval $catchupsql 607 } 608 } 609 } else { 610 error $msg 611 } 612 613 while {[lindex $arglist [expr 2 * ($pc -1)]] == "-test"} { 614 incr pc -1 615 } 616 } 617 618 -prep { 619# puts "PREP $iterid $v" 620 db eval $v 621 incr pc 622 } 623 624 default { error "Unknown switch: $k" } 625 } 626# if {$iFail > ($iFailStart+1)} return 627 } 628} 629 630# Turn of the Tcl interface's prepared statement caching facility. 631db cache size 0 632 633run_test $::run_test_script 76 6 634# run_test [lrange $::run_test_script 0 3] 0 63 635sqlite_malloc_fail 0 636db close 637 638pp_check_for_leaks 639 640finish_test 641 642