# 2011 March 29
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
#

set testdir [file dirname $argv0]
source $testdir/tester.tcl
source $testdir/lock_common.tcl
source $testdir/malloc_common.tcl

if {[llength [info commands test_syscall]]==0} {
  finish_test
  return
} 
set testprefix syscall


#-------------------------------------------------------------------------
# Tests for the xSetSystemCall method.
#
do_test 1.1.1 {
  list [catch { test_syscall reset open } msg] $msg
} {0 {}}
do_test 1.1.2 {
  list [catch { test_syscall reset nosuchcall } msg] $msg
} {1 SQLITE_NOTFOUND}
do_test 1.1.3 {
  list [catch { test_syscall reset open } msg] $msg
} {0 {}}
do_test 1.1.4 {
  list [catch { test_syscall reset ""} msg] $msg
} {1 SQLITE_NOTFOUND}

do_test 1.2 { test_syscall reset } {}

do_test 1.3.1 { test_syscall install {open getcwd access} } {}
do_test 1.3.2 { test_syscall reset } {}

#-------------------------------------------------------------------------
# Tests for the xGetSystemCall method.
#
do_test 2.1.1 { test_syscall exists open } 1
do_test 2.1.2 { test_syscall exists nosuchcall } 0

#-------------------------------------------------------------------------
# Tests for the xNextSystemCall method.
#
set syscall_list [list                                \
    open close access getcwd stat fstat ftruncate     \
    fcntl read pread write pwrite fchmod              \
]
if {[test_syscall exists fallocate]} {lappend syscall_list fallocate}
do_test 3.1 { test_syscall list } $syscall_list

#-------------------------------------------------------------------------
# This test verifies that if a call to open() fails and errno is set to
# EINTR, the call is retried. If it succeeds, execution continues as if
# nothing happened. 
#
test_syscall reset
forcedelete test.db2
do_execsql_test 4.1 {
  CREATE TABLE t1(x, y);
  INSERT INTO t1 VALUES(1, 2);
  ATTACH 'test.db2' AS aux;
  CREATE TABLE aux.t2(x, y);
  INSERT INTO t2 VALUES(3, 4);
}

db_save_and_close
test_syscall install open
foreach jrnl [list wal delete] {
  for {set i 1} {$i < 20} {incr i} {
    db_restore_and_reopen
    test_syscall fault $i 0
    test_syscall errno open EINTR
  
    do_test 4.2.$jrnl.$i {
      sqlite3 db test.db
      execsql { ATTACH 'test.db2' AS aux }
      execsql "PRAGMA main.journal_mode = $jrnl"
      execsql "PRAGMA aux.journal_mode = $jrnl"
      execsql {
        BEGIN;
          INSERT INTO t1 VALUES(5, 6);
          INSERT INTO t2 VALUES(7, 8);
        COMMIT;
      }

      db close
      sqlite3 db test.db
      execsql { ATTACH 'test.db2' AS aux }
      execsql {
        SELECT * FROM t1;
        SELECT * FROM t2;
      }
    } {1 2 5 6 3 4 7 8}
  }

}



finish_test
