xref: /sqlite-3.40.0/test/malloc3.test (revision 93aed5a1)
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.19 2008/01/16 17:46:38 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 malloc3 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 its 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 its 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 its 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]}
152proc DEBUG {s} {lappend ::run_test_script -debug $s}
153
154# SQL --
155#
156#     SQL ?-norollback? <sql-text>
157#
158# Add an 'SQL' primitive to the program (see notes above). If the -norollback
159# switch is present, then the statement is not allowed to automatically roll
160# back any active transaction if malloc() fails. It must rollback the statement
161# transaction only.
162#
163proc SQL  {a1 {a2 ""}} {
164  # An SQL primitive parameter is a list of two elements, a boolean value
165  # indicating if the statement may cause transaction rollback when malloc()
166  # fails, and the sql statement itself.
167  if {$a2 == ""} {
168    lappend ::run_test_script -sql [list true [string trim $a1]]
169  } else {
170    lappend ::run_test_script -sql [list false [string trim $a2]]
171  }
172}
173
174# TEST_AUTOCOMMIT --
175#
176#     A shorthand test to see if a transaction is active or not. The first
177#     argument - $id - is the integer number of the test case. The second
178#     argument is either 1 or 0, the expected value of the auto-commit flag.
179#
180proc TEST_AUTOCOMMIT {id a} {
181    TEST $id "do_test \$testid { sqlite3_get_autocommit \$::DB } {$a}"
182}
183
184#--------------------------------------------------------------------------
185# Start of test program declaration
186#
187
188
189# Warm body test. A malloc() fails in the middle of a CREATE TABLE statement
190# in a single-statement transaction on an empty database. Not too much can go
191# wrong here.
192#
193TEST 1 {
194  do_test $testid {
195    execsql {SELECT tbl_name FROM sqlite_master;}
196  } {}
197}
198SQL {
199  CREATE TABLE abc(a, b, c);
200}
201TEST 2 {
202  do_test $testid.1 {
203    execsql {SELECT tbl_name FROM sqlite_master;}
204  } {abc}
205}
206
207# Insert a couple of rows into the table. each insert is in its own
208# transaction. test that the table is unpopulated before running the inserts
209# (and hence after each failure of the first insert), and that it has been
210# populated correctly after the final insert succeeds.
211#
212TEST 3 {
213  do_test $testid.2 {
214    execsql {SELECT * FROM abc}
215  } {}
216}
217SQL {INSERT INTO abc VALUES(1, 2, 3);}
218SQL {INSERT INTO abc VALUES(4, 5, 6);}
219SQL {INSERT INTO abc VALUES(7, 8, 9);}
220TEST 4 {
221  do_test $testid {
222    execsql {SELECT * FROM abc}
223  } {1 2 3 4 5 6 7 8 9}
224}
225
226# Test a CREATE INDEX statement. Because the table 'abc' is so small, the index
227# will all fit on a single page, so this doesn't test too much that the CREATE
228# TABLE statement didn't test. A few of the transient malloc()s in btree.c
229# perhaps.
230#
231SQL {CREATE INDEX abc_i ON abc(a, b, c);}
232TEST 4 {
233  do_test $testid {
234    execsql {
235      SELECT * FROM abc ORDER BY a DESC;
236    }
237  } {7 8 9 4 5 6 1 2 3}
238}
239
240# Test a DELETE statement. Also create a trigger and a view, just to make sure
241# these statements don't have any obvious malloc() related bugs in them. Note
242# that the test above will be executed each time the DELETE fails, so we're
243# also testing rollback of a DELETE from a table with an index on it.
244#
245SQL {DELETE FROM abc WHERE a > 2;}
246SQL {CREATE TRIGGER abc_t AFTER INSERT ON abc BEGIN SELECT 'trigger!'; END;}
247SQL {CREATE VIEW abc_v AS SELECT * FROM abc;}
248TEST 5 {
249  do_test $testid {
250    execsql {
251      SELECT name, tbl_name FROM sqlite_master ORDER BY name;
252      SELECT * FROM abc;
253    }
254  } {abc abc abc_i abc abc_t abc abc_v abc_v 1 2 3}
255}
256
257set sql {
258  BEGIN;DELETE FROM abc;
259}
260for {set i 1} {$i < 15} {incr i} {
261  set a $i
262  set b "String value $i"
263  set c [string repeat X $i]
264  append sql "INSERT INTO abc VALUES ($a, '$b', '$c');"
265}
266append sql {COMMIT;}
267PREP $sql
268
269SQL {
270  DELETE FROM abc WHERE oid IN (SELECT oid FROM abc ORDER BY random() LIMIT 5);
271}
272TEST 6 {
273  do_test $testid.1 {
274    execsql {SELECT count(*) FROM abc}
275  } {94}
276  do_test $testid.2 {
277    execsql {
278      SELECT min(
279          (oid == a) AND 'String value ' || a == b AND a == length(c)
280      ) FROM abc;
281    }
282  } {1}
283}
284SQL {
285  DELETE FROM abc WHERE oid IN (SELECT oid FROM abc ORDER BY random() LIMIT 5);
286}
287TEST 7 {
288  do_test $testid {
289    execsql {SELECT count(*) FROM abc}
290  } {89}
291  do_test $testid {
292    execsql {
293      SELECT min(
294          (oid == a) AND 'String value ' || a == b AND a == length(c)
295      ) FROM abc;
296    }
297  } {1}
298}
299SQL {
300  DELETE FROM abc WHERE oid IN (SELECT oid FROM abc ORDER BY random() LIMIT 5);
301}
302TEST 9 {
303  do_test $testid {
304    execsql {SELECT count(*) FROM abc}
305  } {84}
306  do_test $testid {
307    execsql {
308      SELECT min(
309          (oid == a) AND 'String value ' || a == b AND a == length(c)
310      ) FROM abc;
311    }
312  } {1}
313}
314
315set padding [string repeat X 500]
316PREP [subst {
317  DROP TABLE abc;
318  CREATE TABLE abc(a PRIMARY KEY, padding, b, c);
319  INSERT INTO abc VALUES(0, '$padding', 2, 2);
320  INSERT INTO abc VALUES(3, '$padding', 5, 5);
321  INSERT INTO abc VALUES(6, '$padding', 8, 8);
322}]
323
324TEST 10 {
325  do_test $testid {
326    execsql {SELECT a, b, c FROM abc}
327  } {0 2 2 3 5 5 6 8 8}
328}
329
330SQL {BEGIN;}
331SQL {INSERT INTO abc VALUES(9, 'XXXXX', 11, 12);}
332TEST_AUTOCOMMIT 11 0
333SQL -norollback {UPDATE abc SET a = a + 1, c = c + 1;}
334TEST_AUTOCOMMIT 12 0
335SQL {DELETE FROM abc WHERE a = 10;}
336TEST_AUTOCOMMIT 13 0
337SQL {COMMIT;}
338
339TEST 14 {
340  do_test $testid.1 {
341    sqlite3_get_autocommit $::DB
342  } {1}
343  do_test $testid.2 {
344    execsql {SELECT a, b, c FROM abc}
345  } {1 2 3 4 5 6 7 8 9}
346}
347
348PREP [subst {
349  DROP TABLE abc;
350  CREATE TABLE abc(a, padding, b, c);
351  INSERT INTO abc VALUES(1, '$padding', 2, 3);
352  INSERT INTO abc VALUES(4, '$padding', 5, 6);
353  INSERT INTO abc VALUES(7, '$padding', 8, 9);
354  CREATE INDEX abc_i ON abc(a, padding, b, c);
355}]
356
357TEST 15 {
358  db eval {PRAGMA cache_size = 10}
359}
360
361SQL {BEGIN;}
362SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc}
363TEST 16 {
364  do_test $testid {
365    execsql {SELECT a, count(*) FROM abc GROUP BY a;}
366  } {1 2 4 2 7 2}
367}
368SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc}
369TEST 17 {
370  do_test $testid {
371    execsql {SELECT a, count(*) FROM abc GROUP BY a;}
372  } {1 4 4 4 7 4}
373}
374SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc}
375TEST 18 {
376  do_test $testid {
377    execsql {SELECT a, count(*) FROM abc GROUP BY a;}
378  } {1 8 4 8 7 8}
379}
380SQL -norllbck {INSERT INTO abc (oid, a, padding, b, c) SELECT NULL, * FROM abc}
381TEST 19 {
382  do_test $testid {
383    execsql {SELECT a, count(*) FROM abc GROUP BY a;}
384  } {1 16 4 16 7 16}
385}
386SQL {COMMIT;}
387TEST 21 {
388  do_test $testid {
389    execsql {SELECT a, count(*) FROM abc GROUP BY a;}
390  } {1 16 4 16 7 16}
391}
392
393SQL {BEGIN;}
394SQL {DELETE FROM abc WHERE oid %2}
395TEST 22 {
396  do_test $testid {
397    execsql {SELECT a, count(*) FROM abc GROUP BY a;}
398  } {1 8 4 8 7 8}
399}
400SQL {DELETE FROM abc}
401TEST 23 {
402  do_test $testid {
403    execsql {SELECT * FROM abc}
404  } {}
405}
406SQL {ROLLBACK;}
407TEST 24 {
408  do_test $testid {
409    execsql {SELECT a, count(*) FROM abc GROUP BY a;}
410  } {1 16 4 16 7 16}
411}
412
413# Test some schema modifications inside of a transaction. These should all
414# cause transaction rollback if they fail. Also query a view, to cover a bit
415# more code.
416#
417PREP {DROP VIEW abc_v;}
418TEST 25 {
419  do_test $testid {
420    execsql {
421      SELECT name, tbl_name FROM sqlite_master;
422    }
423  } {abc abc abc_i abc}
424}
425SQL {BEGIN;}
426SQL {CREATE TABLE def(d, e, f);}
427SQL {CREATE TABLE ghi(g, h, i);}
428TEST 26 {
429  do_test $testid {
430    execsql {
431      SELECT name, tbl_name FROM sqlite_master;
432    }
433  } {abc abc abc_i abc def def ghi ghi}
434}
435SQL {CREATE VIEW v1 AS SELECT * FROM def, ghi}
436SQL {CREATE UNIQUE INDEX ghi_i1 ON ghi(g);}
437TEST 27 {
438  do_test $testid {
439    execsql {
440      SELECT name, tbl_name FROM sqlite_master;
441    }
442  } {abc abc abc_i abc def def ghi ghi v1 v1 ghi_i1 ghi}
443}
444SQL {INSERT INTO def VALUES('a', 'b', 'c')}
445SQL {INSERT INTO def VALUES(1, 2, 3)}
446SQL -norollback {INSERT INTO ghi SELECT * FROM def}
447TEST 28 {
448  do_test $testid {
449    execsql {
450      SELECT * FROM def, ghi WHERE d = g;
451    }
452  } {a b c a b c 1 2 3 1 2 3}
453}
454SQL {COMMIT}
455TEST 29 {
456  do_test $testid {
457    execsql {
458      SELECT * FROM v1 WHERE d = g;
459    }
460  } {a b c a b c 1 2 3 1 2 3}
461}
462
463# Test a simple multi-file transaction
464#
465file delete -force test2.db
466ifcapable attach {
467  SQL {ATTACH 'test2.db' AS aux;}
468  SQL {BEGIN}
469  SQL {CREATE TABLE aux.tbl2(x, y, z)}
470  SQL {INSERT INTO tbl2 VALUES(1, 2, 3)}
471  SQL {INSERT INTO def VALUES(4, 5, 6)}
472  TEST 30 {
473    do_test $testid {
474      execsql {
475        SELECT * FROM tbl2, def WHERE d = x;
476      }
477    } {1 2 3 1 2 3}
478  }
479  SQL {COMMIT}
480  TEST 31 {
481    do_test $testid {
482      execsql {
483        SELECT * FROM tbl2, def WHERE d = x;
484      }
485    } {1 2 3 1 2 3}
486  }
487}
488
489# Test what happens when a malloc() fails while there are other active
490# statements. This changes the way sqlite3VdbeHalt() works.
491TEST 32 {
492  if {![info exists ::STMT32]} {
493    set sql "SELECT name FROM sqlite_master"
494    set ::STMT32 [sqlite3_prepare $::DB $sql -1 DUMMY]
495    do_test $testid {
496      sqlite3_step $::STMT32
497    } {SQLITE_ROW}
498  }
499}
500SQL BEGIN
501TEST 33 {
502  do_test $testid {
503    execsql {SELECT * FROM ghi}
504  } {a b c 1 2 3}
505}
506SQL -norollback {
507  -- There is a unique index on ghi(g), so this statement may not cause
508  -- an automatic ROLLBACK. Hence the "-norollback" switch.
509  INSERT INTO ghi SELECT '2'||g, h, i FROM ghi;
510}
511TEST 34 {
512  if {[info exists ::STMT32]} {
513    do_test $testid {
514      sqlite3_finalize $::STMT32
515    } {SQLITE_OK}
516    unset ::STMT32
517  }
518}
519SQL COMMIT
520
521#
522# End of test program declaration
523#--------------------------------------------------------------------------
524
525proc run_test {arglist iRepeat {pcstart 0} {iFailStart 1}} {
526  if {[llength $arglist] %2} {
527    error "Uneven number of arguments to TEST"
528  }
529
530  for {set i 0} {$i < $pcstart} {incr i} {
531    set k2 [lindex $arglist [expr 2 * $i]]
532    set v2 [lindex $arglist [expr 2 * $i + 1]]
533    set ac [sqlite3_get_autocommit $::DB]        ;# Auto-Commit
534    switch -- $k2 {
535      -sql  {db eval [lindex $v2 1]}
536      -prep {db eval $v2}
537    }
538    set nac [sqlite3_get_autocommit $::DB]       ;# New Auto-Commit
539    if {$ac && !$nac} {set begin_pc $i}
540  }
541
542  db rollback_hook [list incr ::rollback_hook_count]
543
544  set iFail $iFailStart
545  set pc $pcstart
546  while {$pc*2 < [llength $arglist]} {
547
548    # Id of this iteration:
549    set k [lindex $arglist [expr 2 * $pc]]
550    set iterid "pc=$pc.iFail=$iFail$k"
551    set v [lindex $arglist [expr 2 * $pc + 1]]
552
553    switch -- $k {
554
555      -test {
556        foreach {id script} $v {}
557        incr pc
558      }
559
560      -sql {
561        set ::rollback_hook_count 0
562
563        set ac [sqlite3_get_autocommit $::DB]        ;# Auto-Commit
564        sqlite3_memdebug_fail $iFail -repeat 0
565        set rc [catch {db eval [lindex $v 1]} msg]   ;# True error occurs
566        set nac [sqlite3_get_autocommit $::DB]       ;# New Auto-Commit
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 -benigncnt nBenign]
579        if {$rc == 0} {
580            # Successful execution of sql. The number of failed malloc()
581            # calls should be equal to the number of benign failures.
582            # Otherwise a malloc() failed and the error was not reported.
583            #
584            if {$nFail!=$nBenign} {
585              error "Unreported malloc() failure"
586            }
587
588            if {$ac && !$nac} {
589              # Before the [db eval] the auto-commit flag was set, now it
590              # is clear. We can deduce that a "BEGIN" statement has just
591              # been successfully executed.
592              set begin_pc $pc
593            }
594
595            incr pc
596            set iFail 1
597            integrity_check "malloc3-(integrity).$iterid"
598        } elseif {[regexp {.*out of memory} $msg] || [db errorcode] == 3082} {
599            # Out of memory error, as expected.
600            #
601            integrity_check "malloc3-(integrity).$iterid"
602            incr iFail
603            if {$nac && !$ac} {
604
605              if {![lindex $v 0] && [db errorcode] != 3082} {
606                # error "Statement \"[lindex $v 1]\" caused a rollback"
607              }
608
609              for {set i $begin_pc} {$i < $pc} {incr i} {
610                set k2 [lindex $arglist [expr 2 * $i]]
611                set v2 [lindex $arglist [expr 2 * $i + 1]]
612                set catchupsql ""
613                switch -- $k2 {
614                  -sql  {set catchupsql [lindex $v2 1]}
615                  -prep {set catchupsql $v2}
616                }
617                db eval $catchupsql
618              }
619            }
620        } else {
621            error $msg
622        }
623
624        while {[lindex $arglist [expr 2 * ($pc -1)]] == "-test"} {
625          incr pc -1
626        }
627      }
628
629      -prep {
630        db eval $v
631        incr pc
632      }
633
634      -debug {
635        eval $v
636        incr pc
637      }
638
639      default { error "Unknown switch: $k" }
640    }
641  }
642}
643
644# Turn of the Tcl interface's prepared statement caching facility. Then
645# run the tests with "persistent" malloc failures.
646sqlite3_extended_result_codes db 1
647db cache size 0
648run_test $::run_test_script 1
649
650# Close and reopen the db.
651db close
652file delete -force test.db test.db-journal test2.db test2.db-journal
653sqlite3 db test.db
654sqlite3_extended_result_codes db 1
655set ::DB [sqlite3_connection_pointer db]
656
657# Turn of the Tcl interface's prepared statement caching facility in
658# the new connnection. Then run the tests with "transient" malloc failures.
659db cache size 0
660run_test $::run_test_script 0
661
662sqlite3_memdebug_fail -1
663finish_test
664