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