Revision: 201015
authorDremov Kirill (Nokia-D-MSW/Tampere) <kirill.dremov@nokia.com>
Fri, 16 Apr 2010 16:49:27 +0300
changeset 15 3eacc0623088
parent 14 15018f1726c7
child 17 55f2396f6d25
Revision: 201015 Kit: 201015
featuremgmt/featuremgr/engineering/File Specification/FeatDB_XMLDataModel.EAP
featuremgmt/featuremgr/engineering/File Specification/FeatDB_example.xml
featuremgmt/featuremgr/engineering/File Specification/featuredatabase.dtd
featuremgmt/featuremgr/src/clientdll/featmgrclient.cpp
featuremgmt/featuremgr/src/clientdll/featmgrclient.h
featuremgmt/featuremgr/src/clientdll/featmgrtlsdata.cpp
featuremgmt/featuremgr/src/clientdll/featmgrtlsdata.h
featuremgmt/featuremgr/src/clientdll/featureclient.h
featuremgmt/featuremgr/src/clientdll/featurenotifier.cpp
featuremgmt/featuremgr/src/featdiscovery/featdiscovery.cpp
featuremgmt/featuremgr/src/serverexe/featmgrfeatureregistry.cpp
featuremgmt/featuremgr/src/serverexe/featmgrfeatureregistry.h
featuremgmt/featuremgr/src/serverexe/featmgrserver.cpp
featuremgmt/featuremgr/src/serverexe/featmgrsession.cpp
featuremgmt/featuremgr/test/rtest/src/t_fmgrbadclient.cpp
featuremgmt/featuremgr/test/rtest/src/t_fmgroom.cpp
featuremgmt/featuremgr/test/rtest/src/t_fmgrstartup.cpp
featuremgmt/featuremgr/test/rtest/src/t_fmgrswi.cpp
featuremgmt/featuremgr/test/tef/tef_efm_unit/src/efm_unit_teststeps.cpp
loggingservices/filelogger/INC/FLOGGER.H
loggingservices/filelogger/INC/FLOGGER.INL
loggingservices/filelogger/group/BLD.INF
persistentstorage/centralrepository/cenrepsrv/obsrvr_noc.cpp
persistentstorage/centralrepository/cenrepsrv/shrepos.cpp
persistentstorage/centralrepository/cenrepsrv/srvrepos_noc.cpp
persistentstorage/centralrepository/common/inc/operations.h
persistentstorage/centralrepository/test/t_cenrep.cpp
persistentstorage/dbms/tdbms/t_dbood.cpp
persistentstorage/sql/GROUP/BLD.INF
persistentstorage/sql/GROUP/sqltests.bat
persistentstorage/sql/GROUP/sqltests.iby
persistentstorage/sql/GROUP/t_sqlfilesrvcrash1.mmp
persistentstorage/sql/GROUP/t_sqlfilesrvcrash2.mmp
persistentstorage/sql/GROUP/t_sqlfserr.mmp
persistentstorage/sql/GROUP/t_sqlstartup.mmp
persistentstorage/sql/INC/SqlDb.h
persistentstorage/sql/OsLayer/FileBuf64.cpp
persistentstorage/sql/OsLayer/FileBuf64.h
persistentstorage/sql/OsLayer/os_symbian.cpp
persistentstorage/sql/SQLite/parse.h
persistentstorage/sql/SQLite/printf.c
persistentstorage/sql/SQLite364/parse.h
persistentstorage/sql/SQLite364/printf.c
persistentstorage/sql/SRC/Client/SqlDbSession.cpp
persistentstorage/sql/SRC/Client/SqlStatementImpl.cpp
persistentstorage/sql/SRC/Server/SqlBur.cpp
persistentstorage/sql/SRC/Server/SqlBur.h
persistentstorage/sql/SRC/Server/SqlSrvAuthorizer.cpp
persistentstorage/sql/SRC/Server/SqlSrvGetFirstSqlStmt.cpp
persistentstorage/sql/SRC/Server/SqlSrvMain.cpp
persistentstorage/sql/SRC/Server/SqlSrvSession.cpp
persistentstorage/sql/SRC/Server/SqlSrvSession.h
persistentstorage/sql/SRC/Server/SqlSrvUtil.cpp
persistentstorage/sql/TEST/t_sqlapi.cpp
persistentstorage/sql/TEST/t_sqlapi2.cpp
persistentstorage/sql/TEST/t_sqlattach.cpp
persistentstorage/sql/TEST/t_sqldefect.cpp
persistentstorage/sql/TEST/t_sqlfilesrvcrash1.cpp
persistentstorage/sql/TEST/t_sqlfilesrvcrash2.cpp
persistentstorage/sql/TEST/t_sqlfserr.cpp
persistentstorage/sql/TEST/t_sqlood.cpp
persistentstorage/sql/TEST/t_sqloslayer.cpp
persistentstorage/sql/TEST/t_sqlprivcage.cpp
persistentstorage/sql/TEST/t_sqlsecurity2.cpp
persistentstorage/sql/TEST/t_sqlsecurity3.cpp
persistentstorage/sql/TEST/t_sqlsecurity4.cpp
persistentstorage/sql/TEST/t_sqlsecurity5.cpp
persistentstorage/sql/TEST/t_sqlstartup.cpp
persistentstorage/sql/TEST/testexecute/SQLite/data/{102827c7}sec1.db- AS fred; delete from names;
persistentstorage/sqlite3api/OsLayer/FileBuf64.cpp
persistentstorage/sqlite3api/OsLayer/FileBuf64.h
persistentstorage/sqlite3api/OsLayer/os_symbian_mt.cpp
persistentstorage/sqlite3api/SQLite/fts1.h
persistentstorage/sqlite3api/SQLite/parse.h
persistentstorage/sqlite3api/SQLite/printf.c
persistentstorage/sqlite3api/TEST/TCL/tcldistribution/compat/opendir.c
persistentstorage/sqlite3api/TEST/TCL/tcldistribution/generic/regerrs.h
persistentstorage/sqlite3api/TEST/TCL/tcldistribution/mac/MW_TclAppleScriptHeader.h
persistentstorage/sqlite3api/TEST/TCL/tcldistribution/mac/MW_TclBuildLibHeader.h
persistentstorage/sqlite3api/TEST/TCL/tcldistribution/mac/MW_TclHeader.h
persistentstorage/sqlite3api/TEST/TCL/tcldistribution/mac/MW_TclStaticHeader.h
persistentstorage/sqlite3api/TEST/TCL/tcldistribution/mac/MW_TclTestHeader.h
persistentstorage/sqlite3api/TEST/TCL/tcldistribution/unix/tclUnixCompat.c
persistentstorage/sqlite3api/TEST/TCL/tcldistribution/win/buildall.vc.bat
persistentstorage/sqlite3api/TEST/TclScript/crashtest1.c
traceservices/commsdebugutility/INC/commsdebugutility.h
traceservices/commsdebugutility/group/BLD.INF
traceservices/tracefw/integ_test/ost/TEF/traces/OstTraceDefinitions.h
Binary file featuremgmt/featuremgr/engineering/File Specification/FeatDB_XMLDataModel.EAP has changed
--- a/featuremgmt/featuremgr/engineering/File Specification/FeatDB_example.xml	Fri Mar 19 10:00:55 2010 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,40 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE featuredatabase SYSTEM "featuredatabase.dtd">
-<featuredatabase>
-	<!-- Multiple featureset is possible and one featureset generate one set of oby and header files  -->
-	<featureset ibyname="feature.iby" hfilename="publicfeatureUID.h" namespace="NOemFeature">
-		<!-- Following header info goes to generated .h file  -->
-		<hfileheader interfacestatus="@released" interfacevisibility="@publishedPartner">
-				// publicfeatureUID.h
-				//
-				// Copyright (c) Symbian Software Ltd 2007.  All rights reserved.
-				//.......................................................................................
-		</hfileheader>
-		<!-- features an  -->
-		<feature uid="0x10279806" statusflags="0x0001" name="Fax" userdata="0x0001">
-			<hrhmacro exclude="SYMBIAN_EXCLUDE_FAX"/>
-			<comment>
-					/**
-					Feature = FAX,  status = "Supported" this feature should go to SDK
-					*/
-				</comment>
-		</feature>
-		<feature uid="0x10279808" statusflags="0x0001" name="Bluetooth" userdata="0x0001">
-			<hrhmacro include="SYMBIAN_INCLUDE_INFRARED"/>
-			<comment>
-				/**
-					Feature = FAX,  status = "Supported" this feature should go to SDK
-					*/
-				</comment>
-		</feature>
-	</featureset>
-	<!-- DSR UID ranges allocated for features  that default to reporting "feature supported"  -->
-	<defaultfeaturerange loweruid="0x10279806" higheruid="0x10281805">
-		<comment>
-		/**
-			The UID ranges are allocated for features that default to reporting "feature supported"
-			*/
-		</comment>
-	</defaultfeaturerange>
-	
-</featuredatabase>
--- a/featuremgmt/featuremgr/engineering/File Specification/featuredatabase.dtd	Fri Mar 19 10:00:55 2010 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,31 +0,0 @@
-<!ELEMENT hrhmacro EMPTY>
-<!ATTLIST hrhmacro
-	exclude CDATA #IMPLIED
-	include CDATA #IMPLIED
-	infeaturesetiby CDATA #IMPLIED>
-	
-<!ELEMENT hfileheader (#PCDATA)>
-<!ATTLIST hfileheader
-	interfacestatus CDATA #REQUIRED
-	interfacevisibility CDATA #REQUIRED>
-	
-<!ELEMENT featureset ((hfileheader?, feature+))>
-<!ATTLIST featureset
-	hfilename CDATA #IMPLIED
-	ibyname CDATA #IMPLIED
-	namespace CDATA #IMPLIED>
-	
-<!ELEMENT featuredatabase ((featureset+, defaultfeaturerange*))>
-<!ELEMENT feature ((hrhmacro?, comment?))>
-<!ATTLIST feature
-	name CDATA #REQUIRED
-	statusflags CDATA #REQUIRED
-	uid CDATA #REQUIRED
-	userdata CDATA #IMPLIED>
-	
-<!ELEMENT defaultfeaturerange ((comment?))>
-<!ATTLIST defaultfeaturerange
-	higheruid CDATA #REQUIRED
-	loweruid CDATA #REQUIRED>
-	
-<!ELEMENT comment (#PCDATA)>
--- a/featuremgmt/featuremgr/src/clientdll/featmgrclient.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/featuremgmt/featuremgr/src/clientdll/featmgrclient.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -384,16 +384,12 @@
 // RFeatMgrClient::ReRequestNotification(TUid&, TRequestStatus&)
 // -----------------------------------------------------------------------------
 //
-TInt RFeatMgrClient::ReRequestNotification( TUid& aFeatUid, TRequestStatus& aStatus )
+void RFeatMgrClient::ReRequestNotification( TUid& aFeatUid, TRequestStatus& aStatus )
     {
     TPckgBuf<TInt> pckg;
-    TInt retval( KErrNone );
-    
-	iFeaturePckg.Set( (TUint8*) &aFeatUid.iUid, sizeof(TUid), sizeof(TUid) );
-	TIpcArgs args( &iFeaturePckg );
-	SendReceive( EFeatMgrReqNotify, args, aStatus );
-
-    return retval;
+    iFeaturePckg.Set( (TUint8*) &aFeatUid.iUid, sizeof(TUid), sizeof(TUid) );
+	  TIpcArgs args( &iFeaturePckg );
+  	SendReceive( EFeatMgrReqNotify, args, aStatus );
     }
 
 // -----------------------------------------------------------------------------
--- a/featuremgmt/featuremgr/src/clientdll/featmgrclient.h	Fri Mar 19 10:00:55 2010 +0200
+++ b/featuremgmt/featuremgr/src/clientdll/featmgrclient.h	Fri Apr 16 16:49:27 2010 +0300
@@ -75,7 +75,7 @@
         TInt RequestNotification( RFeatureUidArray& aFeatures, TUid& aFeatUid, 
             TRequestStatus& aStatus );
 
-        TInt ReRequestNotification( TUid& aFeatUid, TRequestStatus& aStatus );
+        void ReRequestNotification( TUid& aFeatUid, TRequestStatus& aStatus );
         
         TInt RequestNotifyCancel( TUid aFeature ) const;
 
--- a/featuremgmt/featuremgr/src/clientdll/featmgrtlsdata.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/featuremgmt/featuremgr/src/clientdll/featmgrtlsdata.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -225,9 +225,9 @@
 // CFeatMgrTlsData::ReRequestNotification(TUid&, TRequestStatus&)
 // -----------------------------------------------------------------------------
 //
-TInt CFeatMgrTlsData::ReRequestNotification( TUid& aFeatUid, TRequestStatus& aStatus )
+void CFeatMgrTlsData::ReRequestNotification( TUid& aFeatUid, TRequestStatus& aStatus )
     {
-    return iFeatMgrClient.ReRequestNotification( aFeatUid, aStatus );
+    iFeatMgrClient.ReRequestNotification( aFeatUid, aStatus );
     }
         
 
--- a/featuremgmt/featuremgr/src/clientdll/featmgrtlsdata.h	Fri Mar 19 10:00:55 2010 +0200
+++ b/featuremgmt/featuremgr/src/clientdll/featmgrtlsdata.h	Fri Apr 16 16:49:27 2010 +0300
@@ -100,7 +100,7 @@
         TInt RequestNotification( RFeatureUidArray& aFeatures, TUid& aFeatUid, 
                 TRequestStatus& aStatus );
 
-        TInt ReRequestNotification( TUid& aFeatUid, TRequestStatus& aStatus );
+        void ReRequestNotification( TUid& aFeatUid, TRequestStatus& aStatus );
 
         TInt RequestNotifyCancel( TUid aFeature ) const;
 
--- a/featuremgmt/featuremgr/src/clientdll/featureclient.h	Fri Mar 19 10:00:55 2010 +0200
+++ b/featuremgmt/featuremgr/src/clientdll/featureclient.h	Fri Apr 16 16:49:27 2010 +0300
@@ -153,7 +153,7 @@
          * @param aStatus Client request to be signalled asynchronously.
          * @return One of the Symbian OS system-wide error codes.
          */
-        virtual TInt ReRequestNotification( TUid& aFeatUid, TRequestStatus& aStatus ) = 0;
+        virtual void ReRequestNotification( TUid& aFeatUid, TRequestStatus& aStatus ) = 0;
         
         /**
         * Cancel notification request for single feature's changes.
--- a/featuremgmt/featuremgr/src/clientdll/featurenotifier.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/featuremgmt/featuremgr/src/clientdll/featurenotifier.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -76,6 +76,11 @@
     iFeatMgrClient = new (ELeave) RFeatMgrClient;
     // Connect to Feature Manager server
     TInt err( iFeatMgrClient->Connect() );
+    if (err!=KErrNone)
+      {
+      delete iFeatMgrClient;
+      iFeatMgrClient=NULL;
+      }
     User::LeaveIfError(err);
 
     CActiveScheduler::Add( this );
@@ -112,12 +117,20 @@
         }
 
     iFeatures.Reset();
-    iFeatures.Append( aFeature );
-    TInt err = iFeatMgrClient->RequestNotification( iFeatures, iFeatureChanged, iStatus );
+    TInt err=iFeatures.Append( aFeature );
+    if (err!=KErrNone)
+      {
+      return err;
+      }
+    err = iFeatMgrClient->RequestNotification( iFeatures, iFeatureChanged, iStatus );
     if ( err == KErrNone )
     	{
         SetActive();
      	}
+    else
+      {
+      iFeatures.Reset();
+      }
      	    
     return err;
     }
@@ -135,7 +148,7 @@
 
     iFeatures.Reset();
     TInt count = aFeatures.Count();
-    
+    TInt err=KErrNone;
     for(TInt i = 0; i < count; i++ )
         {
         // Do not append duplicate entries
@@ -143,16 +156,24 @@
         TInt index = iFeatures.Find( uid, FindByUid );
         if( index == KErrNotFound )
             {
-            iFeatures.Append( uid );
+            err=iFeatures.Append( uid );
+            if (err!=KErrNone)
+              {
+              iFeatures.Reset();
+              return err;
+              }
             }
         }
 
-    TInt err = iFeatMgrClient->RequestNotification( iFeatures, iFeatureChanged, iStatus );
+    err = iFeatMgrClient->RequestNotification( iFeatures, iFeatureChanged, iStatus );
     if ( err == KErrNone )
     	{
         SetActive();
      	}
-    
+    else
+      {
+      iFeatures.Reset();
+      }
     return err;
     }
     
--- a/featuremgmt/featuremgr/src/featdiscovery/featdiscovery.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/featuremgmt/featuremgr/src/featdiscovery/featdiscovery.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -46,6 +46,7 @@
     TInt err;
     TFeatureStat feature;
     feature.iFeatureID = aFeature;
+    feature.iSupported=EFalse;
     
     err = iStatus.Append( feature );
     if( err == KErrNone )
--- a/featuremgmt/featuremgr/src/serverexe/featmgrfeatureregistry.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/featuremgmt/featuremgr/src/serverexe/featmgrfeatureregistry.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -191,7 +191,7 @@
 	        flags.Set( EFeatureRuntime );
 	
 	        //Check the feature falg is valid
-	        TRAP(err, err = ValidateRuntimeFeatureFlagL(flags));
+	        TRAP(err,ValidateRuntimeFeatureFlagL(flags));
 	        if (err != KErrNone)
 	            return err;
 	
@@ -607,7 +607,7 @@
 
     if ((err == KErrCorrupt) || (err == KErrArgument))
     	{
-    	iFs.Delete(path);
+    	User::LeaveIfError(iFs.Delete(path));
     	aFeaturesReady = ETrue;
     	}
     else if ( err != KErrNone && err != KErrNotFound && err != KErrPathNotFound )
@@ -866,7 +866,7 @@
         // Write header and entry
         RFeatureServerArray temp(1);
         CleanupClosePushL( temp );
-        temp.Append( aFeature );
+        temp.AppendL( aFeature );
         WriteHeaderAndEntriesL( writeStream, temp );
         CleanupStack::PopAndDestroy( &temp );
         CleanupStack::PopAndDestroy( &writeStream );
@@ -961,13 +961,14 @@
         {
         aArray[i].ExternalizeL( aStream );
         }
+    aStream.CommitL();
     }
 
 // -----------------------------------------------------------------------------
 // CFeatMgrFeatureRegistry::MergePluginFeatures
 // -----------------------------------------------------------------------------
 //  
-void CFeatMgrFeatureRegistry::MergePluginFeatures( 
+void CFeatMgrFeatureRegistry::MergePluginFeaturesL( 
         RArray<FeatureInfoCommand::TFeature>& aList )
     {
     FUNC_LOG
@@ -1006,6 +1007,7 @@
             TInt err = iFeatureList.InsertInOrder( newFeature, FindByUid );
             INFO_LOG2( "CFeatMgrFeatureRegistry::MergePluginFeatures - 0x%08x insert result %d",
                 newFeature.FeatureUid().iUid, err );
+            User::LeaveIfError(err);
             }
         }
     }
@@ -1014,7 +1016,7 @@
 // CFeatMgrFeatureRegistry::MergePluginFeatures
 // -----------------------------------------------------------------------------
 //  
-void CFeatMgrFeatureRegistry::MergePluginFeatures( RFeatureArray& aList )
+void CFeatMgrFeatureRegistry::MergePluginFeaturesL( RFeatureArray& aList )
     {
     FUNC_LOG
     
@@ -1048,6 +1050,7 @@
             TInt err = iFeatureList.InsertInOrder( newFeature, FindByUid );
             INFO_LOG2( "CFeatMgrFeatureRegistry::MergePluginFeatures - 0x%08x insert result %d",
                 newFeature.FeatureUid().iUid, err );
+            User::LeaveIfError(err);
             }
         }
     }
@@ -1107,9 +1110,8 @@
  * The following are the rules to check for errors in the run time defined feature flags
  * Rule 1)Blacklisting of a run-time defined feature flag is an error 
  * Rule 2)Un-initialised feature flag should be modifiable.   
- * Funtion returns KErrArgument if a rule is broken otherwise KErrNone
  */
-TInt CFeatMgrFeatureRegistry::ValidateRuntimeFeatureFlagL(TBitFlags32 aFlags)
+void CFeatMgrFeatureRegistry::ValidateRuntimeFeatureFlagL(TBitFlags32 aFlags)
 	{
 	
 	//Rule 1 (Blacklisting of run-time defined feature aFlags is not allowed)
@@ -1125,8 +1127,6 @@
 	 	//error 
 	 	User::Leave( KErrArgument );
 	 	}
-	
-	return KErrNone;	
 	}
 
 
@@ -1136,7 +1136,7 @@
  * to discover if any changes have taken place: then it will handle the required
  * notifications for new, deleted and changed featuers.
  */
-TInt CFeatMgrFeatureRegistry::HandleRestoredFeatureNotificationsL( void )
+void CFeatMgrFeatureRegistry::HandleRestoredFeatureNotificationsL()
 	{
 	// All comparisons are between the new list iFeatureList and the old list iFeatureListBackup
 	TInt new_count = iFeatureList.Count();
@@ -1161,7 +1161,7 @@
 			if( KErrNotFound == index )
 				{
 				// Recently added feature
-				added.Append( iFeatureList[i] );
+				added.AppendL( iFeatureList[i] );
 				}
 			else
 				{
@@ -1177,7 +1177,7 @@
 				if( !( old_flags == new_flags) || !( old_data == new_data) )
 					{
 					// changed in the "new" iFeatureList array
-					changed.Append( iFeatureList[i] );
+					changed.AppendL( iFeatureList[i] );
 					}
 				}
 		
@@ -1199,7 +1199,7 @@
 			if( KErrNotFound == index )
 				{
 				// Recently removed feature
-				removed.Append( iFeatureListBackup[i] );
+				removed.AppendL( iFeatureListBackup[i] );
 				}
 			// the else has already been completed in previous loop
 		
@@ -1233,8 +1233,6 @@
         TFeatureChangeType changeType( EFeatureFeatureDeleted );
         iObserver.HandleFeatureChange( entry, changeType );
         }
-	
-	return( 0 );
 	}
 
 // -----------------------------------------------------------------------------
--- a/featuremgmt/featuremgr/src/serverexe/featmgrfeatureregistry.h	Fri Mar 19 10:00:55 2010 +0200
+++ b/featuremgmt/featuremgr/src/serverexe/featmgrfeatureregistry.h	Fri Apr 16 16:49:27 2010 +0300
@@ -108,12 +108,12 @@
         /**
         * Merges features to common feature array from plugin.
         */
-        void MergePluginFeatures( RArray<FeatureInfoCommand::TFeature>& aList );
+        void MergePluginFeaturesL( RArray<FeatureInfoCommand::TFeature>& aList );
 
         /**
         * Merges features to common feature array from plugin.
         */
-        void MergePluginFeatures( RFeatureArray& aList );
+        void MergePluginFeaturesL( RFeatureArray& aList );
 
         /**
         * Returns feature support status.
@@ -161,7 +161,7 @@
 		 * This function will handle the required notifications for new, deleted and changed features
 		 * after a restore operation has taken place.
          */ 
-        TInt HandleRestoredFeatureNotificationsL( void );
+        void HandleRestoredFeatureNotificationsL();
         
         /**
 		 * Returns the fully qualified path and filename for the runtime feature data file.
@@ -243,7 +243,7 @@
         void ValidateHeaderL( RFileReadStream& stream, TUint32& count, TUint32& countDSRs );
         void WriteHeaderAndEntriesL( RFileWriteStream &aStream, RFeatureServerArray& aArray );
         TInt ValidateFeatureFlag(TBitFlags32 aFlags);
-        TInt ValidateRuntimeFeatureFlagL(TBitFlags32 aFlags);
+        void ValidateRuntimeFeatureFlagL(TBitFlags32 aFlags);
         
      private:
         
--- a/featuremgmt/featuremgr/src/serverexe/featmgrserver.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/featuremgmt/featuremgr/src/serverexe/featmgrserver.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -226,7 +226,6 @@
         } 
     
     delete iTimer;
-    iFs.Close();
     iPluginList.Close();
     
     // De register Backup and Restore and cleanup memory
@@ -239,6 +238,7 @@
     	}
     
     delete iRegistry;
+    iFs.Close();
     }
 
 
@@ -528,7 +528,7 @@
         {
         if ( iPluginList[i].iPluginHandler == aPluginHandler )
             {
-            iRegistry->MergePluginFeatures( aFeatureList );
+            iRegistry->MergePluginFeaturesL( aFeatureList );
             // Send command to load enhanced feature info
             TRAPD( err, iPluginList[i].iPluginHandler->SendCommandL( 
                 FeatureInfoCommand::ELoadEnhancedFeatureInfoCmdId ) );
@@ -572,7 +572,7 @@
         {
         if ( iPluginList[i].iPluginHandler == aPluginHandler )
             {
-            iRegistry->MergePluginFeatures( aFeatureList );
+            iRegistry->MergePluginFeaturesL( aFeatureList );
             // Send another command if something left to process
             iPluginList[i].iPluginReady = ETrue;
             }
@@ -820,8 +820,6 @@
 void CFeatMgrServer::HandleRestoredNotificationsL( void )
 	{
 	iRegistry->HandleRestoredFeatureNotificationsL();
-	
-	return;
 	}
 
 /**
--- a/featuremgmt/featuremgr/src/serverexe/featmgrsession.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/featuremgmt/featuremgr/src/serverexe/featmgrsession.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -143,7 +143,18 @@
         else
             {
             INFO_LOG( "CFeatMgrSession::ServiceL() - plugins not ready" );
-            iList.AddLast( *CFeatMgrPendingRequest::NewL( aMessage ) );
+            CFeatMgrPendingRequest* request=NULL;
+            TRAPD(error,request=CFeatMgrPendingRequest::NewL( aMessage ));
+            if (error!=KErrNone)
+              {
+              LOG_IF_ERROR1( error, "CFeatMgrSession::ServiceL(): Error in Adding Pending Request: %d", error );
+              //cannot create pending request so need to indicate to the client rather than letting the cient wait forever.
+              aMessage.Complete(error);              
+              }
+            else
+              {
+              iList.AddLast(*request);
+              }
             }
         }
     else
--- a/featuremgmt/featuremgr/test/rtest/src/t_fmgrbadclient.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/featuremgmt/featuremgr/test/rtest/src/t_fmgrbadclient.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -20,8 +20,8 @@
 #include "featurepanics.h"
 #include <featurecontrol.h>
 #include <featurenotifier.h>
-#include "..\src\inc\featmgrconfiguration.h"
-#include "..\src\inc\featmgrclientserver.h"
+#include "../src/inc/featmgrconfiguration.h"
+#include "../src/inc/featmgrclientserver.h"
 
 using namespace NFeature;
 
--- a/featuremgmt/featuremgr/test/rtest/src/t_fmgroom.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/featuremgmt/featuremgr/test/rtest/src/t_fmgroom.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -39,8 +39,7 @@
 static TInt TheProcessHandleCount = 0;
 static TInt TheThreadHandleCount = 0;
 static TInt TheAllocatedCellsCount = 0;
-
-#ifdef EXTENDED_FEATURE_MANAGER_TEST
+#ifdef _DEBUG
 static const TInt KBurstRate = 20;
 #endif
 
--- a/featuremgmt/featuremgr/test/rtest/src/t_fmgrstartup.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/featuremgmt/featuremgr/test/rtest/src/t_fmgrstartup.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -23,8 +23,10 @@
 static TInt TheAllocatedCellsCount = 0;
 
 #ifdef EXTENDED_FEATURE_MANAGER_TEST
+#ifdef _DEBUG
 static const TInt KBurstRate = 20;
 #endif
+#endif
 
 ///////////////////////////////////////////////////////////////////////////////////////
 
--- a/featuremgmt/featuremgr/test/rtest/src/t_fmgrswi.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/featuremgmt/featuremgr/test/rtest/src/t_fmgrswi.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -21,7 +21,7 @@
 #include <featureuids.h>
 #include <featurecontrol.h>
 #include <featdiscovery.h>
-#include "..\src\inc\featmgrconfiguration.h"
+#include "../src/inc/featmgrconfiguration.h"
 
 ///////////////////////////////////////////////////////////////////////////////////////
 
--- a/featuremgmt/featuremgr/test/tef/tef_efm_unit/src/efm_unit_teststeps.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/featuremgmt/featuremgr/test/tef/tef_efm_unit/src/efm_unit_teststeps.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -285,7 +285,7 @@
 TVerdict CServerMergePluginFeaturesTestStep::doTestStepL()
 	{
 	// This is a void method, so we can't actually check directly if this worked
-	ifeatureSet->MergePluginFeatures(irfa);
+	ifeatureSet->MergePluginFeaturesL(irfa);
 
 	// .. so get the supported features in this array and check
 	RFeatureUidArray rf;
@@ -363,7 +363,7 @@
 TVerdict CServerMergePluginFeaturesTestStep2::doTestStepL()
 	{
 	// This is a void method, so we can't actually check directly if this worked
-	ifeatureSet->MergePluginFeatures(ifc);
+	ifeatureSet->MergePluginFeaturesL(ifc);
 
 	// .. so get the supported features in this array and check
 	RFeatureUidArray rf;
--- a/loggingservices/filelogger/INC/FLOGGER.H	Fri Mar 19 10:00:55 2010 +0200
+++ b/loggingservices/filelogger/INC/FLOGGER.H	Fri Apr 16 16:49:27 2010 +0300
@@ -16,31 +16,35 @@
 //
 
 /**
- @file
- @internalTechnology
+@file
+@publishedAll
+@deprecated Migrate to Open System Trace Instrumentation API instead
 */
 
-
-
 #ifndef __FLOGGER_H__
 #define __FLOGGER_H__
 
 #include <e32base.h>
 
 /** Maximum log buffer size.
-@internalTechnology */
+@publishedAll
+@deprecated Migrate to Open System Trace Instrumentation API instead
+*/
 const TInt KLogBufferSize=150;
 
 // [All of this start up stuff copied from DBMS]
 
 class FLogger
 /** Controls the flogger server.
-@internalComponent */
+@publishedAll
+@deprecated Migrate to Open System Trace Instrumentation API instead
+*/
 	{
 public:
 	class TSignal
 /**
-@internalComponent
+@publishedAll
+@deprecated Migrate to Open System Trace Instrumentation API instead
 */
 		{
 		friend class FLogger;
@@ -67,7 +71,9 @@
 
 
 /** The mode used to write to the log file.
-@internalTechnology */
+@publishedAll
+@deprecated Migrate to Open System Trace Instrumentation API instead
+*/
 enum TFileLoggingMode 
 	{
 	/** Log file mode has not been explicitly set. */
@@ -82,7 +88,9 @@
 
 NONSHARABLE_CLASS(TLogFormatter16Overflow) :public TDes16Overflow
 /** Unicode overflow handler.
-@internalComponent */
+@publishedAll
+@deprecated Migrate to Open System Trace Instrumentation API instead
+*/
 	{
 public:
 	virtual void Overflow(TDes16& aDes);
@@ -90,7 +98,9 @@
 
 NONSHARABLE_CLASS(TLogFormatter8Overflow) :public TDes8Overflow
 /** Overflow handler.
-@internalComponent */
+@publishedAll
+@deprecated Migrate to Open System Trace Instrumentation API instead
+*/
 	{
 public:
 	virtual void Overflow(TDes8& aDes);
@@ -98,7 +108,9 @@
 
 class TLogFormatter
 /** Formatting methods for log file data.
-@internalComponent */
+@publishedAll
+@deprecated Migrate to Open System Trace Instrumentation API instead
+*/
 	{
 public:
 	TLogFormatter();
@@ -120,7 +132,9 @@
 
 class TLogFile
 /** General access to packaged log files.
-@internalComponent */
+@publishedAll
+@deprecated Migrate to Open System Trace Instrumentation API instead
+*/
 	{
 public:
 	TLogFile();
@@ -146,7 +160,9 @@
 
 The file logger API contains both static and non-static versions of access 
 functions to the file logging system. 
-@internalTechnology */
+@publishedAll
+@deprecated Migrate to Open System Trace Instrumentation API instead
+*/
 	{
 public:
 	IMPORT_C RFileLogger();
--- a/loggingservices/filelogger/INC/FLOGGER.INL	Fri Mar 19 10:00:55 2010 +0200
+++ b/loggingservices/filelogger/INC/FLOGGER.INL	Fri Apr 16 16:49:27 2010 +0300
@@ -14,8 +14,9 @@
 //
 
 /**
- @file
- @internalTechnology
+@file
+@publishedAll
+@deprecated Migrate to Open System Trace Instrumentation API instead
 */
 
 #ifndef __FLOGGER_INL__
--- a/loggingservices/filelogger/group/BLD.INF	Fri Mar 19 10:00:55 2010 +0200
+++ b/loggingservices/filelogger/group/BLD.INF	Fri Apr 16 16:49:27 2010 +0300
@@ -23,8 +23,8 @@
 
 PRJ_EXPORTS
 
-../INC/FLOGGER.H SYMBIAN_OS_LAYER_PLATFORM_EXPORT_PATH(flogger.h)
-../INC/FLOGGER.INL SYMBIAN_OS_LAYER_PLATFORM_EXPORT_PATH(flogger.inl)
+../INC/FLOGGER.H SYMBIAN_OS_LAYER_PUBLIC_EXPORT_PATH(flogger.h)
+../INC/FLOGGER.INL SYMBIAN_OS_LAYER_PUBLIC_EXPORT_PATH(flogger.inl)
 
 ../group/flogger.iby	/epoc32/rom/include/flogger.iby
 
--- a/persistentstorage/centralrepository/cenrepsrv/obsrvr_noc.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/centralrepository/cenrepsrv/obsrvr_noc.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -312,9 +312,8 @@
 		if (err==KErrNotFound)
 			{
 			//new entry
-			TMultiRofsList newEntry(TUid::Uid(uidNum));
-			newEntry.iMountFlagList.AppendL(newFlag);
-			iMultiRofsUidList.InsertInOrderL(newEntry,reposSortOrder);
+			find.iMountFlagList.AppendL(newFlag);
+			iMultiRofsUidList.InsertInOrderL(find,reposSortOrder);
 			}
 		else
 			{
@@ -453,7 +452,6 @@
 	and not corrupted
 	*/
 	TSettingsAccessPolicy defaultTs=aOverrideRepository->GetDefaultAccessPolicy();
-	//lets panic first on debug mode only
 	//here we panic immediately if there is any defined in the range meta/policy(we can check individually if
 	//they do override later on,we will assume any definiton of global policy is invalid here
 	if (   aOverrideRepository->Owner() != aCoreRepository->iSimRep->Owner()
@@ -505,7 +503,10 @@
 	
 	}	
 
-//Function on initialising a repository of multi ROFS files
+/**Function on initialising a repository of multi ROFS files
+aCoreInitialized indicate whether there is already existing keyspace file in the core layer
+otherwise the first one in the rofs layer will be the core repository
+*/ 
 void CObservable::MergeMultiRofsL(TBool aCoreInitialized,CSharedRepository* aCoreRepository,const RArray<TRofsFlag>& aOverridingFileList)
 	{
 	//load all the files and construct an array of CHeapRepository to merge content into it
@@ -530,7 +531,8 @@
 				CIniFileIn* iniFile;
 				TInt err=CIniFileIn::NewLC(TServerResources::iFs,iniFile,repFileName);
 				User::LeaveIfError(err);
-				aCoreRepository->ReloadContentL(*iniFile,ETrue);
+				err=aCoreRepository->ReloadContentL(*iniFile,ETrue);
+				User::LeaveIfError(err);
 				CleanupStack::PopAndDestroy(iniFile);//iniFile
 				}
 			else
--- a/persistentstorage/centralrepository/cenrepsrv/shrepos.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/centralrepository/cenrepsrv/shrepos.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -496,6 +496,8 @@
 The current repository must be emptied (or must be empty already) before the call is made.
 @param aIniFile A reference to CIniFileIn object, which will be used to load
 				the repository content.
+@param aFirstLoad is used to indicate whether the file is reloaded for first time, this is used to prevent
+notification if not needed. For example file loading for merging purpose will not result in notification
 @return KErrCorrupt Corrupted repository file.
 		KErrNone	The repository content was seccessfully loaded into memory.
 		KErrNotFound Setting not found in the file.
--- a/persistentstorage/centralrepository/cenrepsrv/srvrepos_noc.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/centralrepository/cenrepsrv/srvrepos_noc.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -80,11 +80,9 @@
 /**
 Attempt to reset a single key to it's value in the file in the given location. Routine
 attempts to find a .cre file first. If ( and only if ) a cre file doesn't exist the 
-routine attempts to find a txt file.
-Note that it would be possible to use LoadRepositoryLC here but for the txt file
-that would take longer. This is because in LoadRepositoryLC the txt file is 
-completely processed. The Reset specific txt file opening code below is quicker because 
-it is just attempting to find the reset key.
+routine attempts to find a txt file. In the presence of multi rofs, it needs to perform
+merging of all the rom keyspaces first before doing a reset, hence we are not able to perform
+the reading line by line for efficiency purpose.
 */
 #ifdef SYMBIAN_CENTREP_SUPPORT_MULTIROFS	
 void CServerRepository::ResetFromIniFileL(TUint32 aId, 
@@ -113,6 +111,15 @@
 	CleanupStack::PopAndDestroy(rep);
 	}
 #else
+/**
+Attempt to reset a single key to it's value in the file in the given location. Routine
+attempts to find a .cre file first. If ( and only if ) a cre file doesn't exist the 
+routine attempts to find a txt file.
+Note that it would be possible to use LoadRepositoryLC here but for the txt file
+that would take longer. This is because in LoadRepositoryLC the txt file is 
+completely processed. The Reset specific txt file opening code below is quicker because 
+it is just attempting to find the reset key.
+*/
 void CServerRepository::ResetFromIniFileL(TUint32 aId, 
 										  TCentRepLocation aLocation,
 										  TBool& aKeyFound)
--- a/persistentstorage/centralrepository/common/inc/operations.h	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/centralrepository/common/inc/operations.h	Fri Apr 16 16:49:27 2010 +0300
@@ -63,6 +63,7 @@
 			{
 			// create a new placeholder and set as deleted
 			TServerSetting newSetting(key);
+			newSetting.SetMeta(settingToDelete.Meta());
 			newSetting.SetDeleted();
 			GetWritableSettingList().OrderedInsertL(newSetting);
 			}
--- a/persistentstorage/centralrepository/test/t_cenrep.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/centralrepository/test/t_cenrep.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -1,4 +1,4 @@
-// Copyright (c) 2004-2009 Nokia Corporation and/or its subsidiary(-ies).
+// Copyright (c) 2004-2010 Nokia Corporation and/or its subsidiary(-ies).
 // All rights reserved.
 // This component and the accompanying materials are made available
 // under the terms of "Eclipse Public License v1.0"
@@ -38,6 +38,8 @@
 
 const TUid KUidDriveCOnlyRepository = { 0x00000013 };
 
+const TUid KUidTestRepository3 = { 0x00000103 };
+
 //
 // Test repository 1
 //
@@ -2239,6 +2241,64 @@
 
 	CleanupStack::PopAndDestroy();
 	}
+
+/**
+@SYMTestCaseID          PDS-CENTRALREPOSITORY-CT-4113
+@SYMTestCaseDesc        Validates meta data is not lost before a transaction is committed
+                        when deleting a range of settings.
+@SYMTestPriority        High
+@SYMTestActions         1) Start a transaction.
+                        2) Delete a setting using the delete range function.
+                        3) Create a new setting (using the deleted key)
+                        4) Commit the transaction.
+                        5) Check the metadata of the setting.                     
+@SYMTestExpectedResults When deleting a range of settings in a keyspace, and then 
+                        creating a new setting (with a key of a previously deleted setting)
+                        the meta data should not be reset to 0, it should take on the default
+                        metadata, if it exists.
+@SYMDEF                 DEF144530
+*/
+LOCAL_C void RangeDeleteMetaL()
+    {
+    TheTest.Next(_L(" @SYMTestCaseID:PDS-CENTRALREPOSITORY-CT-4113 "));
+
+    TUint32 partialKey   = 0x0000004;
+    TUint32 mask         = 0xFFFFFFF;
+    TUint32 meta = 0;
+    TUint32 expectedMeta = 0x10; // 16 
+    TUint32 keyCount = 0;
+    TUint32 expectedKeyCount = 1;
+    TUint32 error;
+
+    CRepository* repository;
+    User::LeaveIfNull(repository = CRepository::NewL(KUidTestRepository3)); // 00000103.txt
+    
+    repository->StartTransaction(CRepository::EReadWriteTransaction);
+
+    // Only want to delete 1 specific key, using the range delete function.
+    TInt ret = repository->Delete(partialKey, mask, error);
+    // We don't care about 'error' if 'ret==KErrNone'.
+    TEST2(ret, KErrNone);  
+    
+    // Create a new setting that is the same key and type as the deleted one.
+    ret = repository->Create(partialKey, 200); 
+    TEST2(ret, KErrNone);
+    
+    ret = repository->CommitTransaction(keyCount);
+    TEST2(ret, KErrNone);
+    // Confirm only 1 setting was updated.
+    TEST2(keyCount, expectedKeyCount);
+    
+    // Check the meta data of the newly created setting. It should be the 
+    // the same as the defaultmeta value in the keyspace.
+    ret = repository->GetMeta(partialKey, meta);
+    TEST2(ret, KErrNone);
+    TEST2(meta, expectedMeta);
+    
+    delete repository;
+    }
+
+
 /**
 @SYMTestCaseID			SYSLIB-CENTRALREPOSITORY-CT-0494
 @SYMTestCaseDesc		Tests the various functions on CentralRepository
@@ -2292,7 +2352,10 @@
 
 	TheTest.Next(_L("Notify-only client optimizations"));
 	NotifyOnlyL();
-
+	
+	TheTest.Next(_L("Meta data after a Range Delete in transaction"));
+    RangeDeleteMetaL();
+    
 	TheTest.End();
 	}
 
--- a/persistentstorage/dbms/tdbms/t_dbood.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/dbms/tdbms/t_dbood.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -191,6 +191,10 @@
 static void SetupTestDirectory()
     {
 	TInt err = TheFs.MkDir(KTestDatabase);
+	if(err != KErrNone)
+	    {
+	    RDebug::Print(_L("*** SetupTestDirectory(), RFs::MkDir(), err=%d\r\n"), err);
+	    }
 	TEST(err == KErrNone || err == KErrAlreadyExists);
 	}
 
--- a/persistentstorage/sql/GROUP/BLD.INF	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/GROUP/BLD.INF	Fri Apr 16 16:49:27 2010 +0300
@@ -102,6 +102,11 @@
 t_sqlauthorizer.mmp
 t_sqlfilebuf64.mmp
 t_sqldb64.mmp manual
+t_sqlstartup.mmp
+#ifndef WINS //hardware only
+t_sqlfilesrvcrash1.mmp manual
+t_sqlfilesrvcrash2.mmp manual
+#endif
 t_sqlenvdestroy.mmp
 
 
--- a/persistentstorage/sql/GROUP/sqltests.bat	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/GROUP/sqltests.bat	Fri Apr 16 16:49:27 2010 +0300
@@ -58,4 +58,5 @@
 T_SQLBLOB.EXE
 T_SQLFILEBUF64.EXE
 T_SQLAUTHORIZER.EXE
+T_SQLSTARTUP.EXE
 T_SQLENVDESTROY.EXE
--- a/persistentstorage/sql/GROUP/sqltests.iby	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/GROUP/sqltests.iby	Fri Apr 16 16:49:27 2010 +0300
@@ -103,7 +103,10 @@
 file=ABI_DIR\BUILD_DIR\T_SQLBLOB.EXE	\TEST\T_SQLBLOB.EXE
 file=ABI_DIR\BUILD_DIR\T_SQLAUTHORIZER.EXE \TEST\T_SQLAUTHORIZER.EXE
 file=ABI_DIR\BUILD_DIR\T_SQLFILEBUF64.EXE 	\TEST\T_SQLFILEBUF64.EXE
-file=ABI_DIR\BUILD_DIR\T_SQLDB64.EXE 	\TEST\T_SQLDB64.EXE
+file=ABI_DIR\BUILD_DIR\T_SQLSTARTUP.EXE 	\TEST\T_SQLSTARTUP.EXE
+file=ABI_DIR\BUILD_DIR\T_SQLDB64.EXE	\TEST\T_SQLDB64.EXE
+file=ABI_DIR\BUILD_DIR\T_SQLFILESRVCRASH1.EXE	\TEST\T_SQLFILESRVCRASH1.EXE
+file=ABI_DIR\BUILD_DIR\T_SQLFILESRVCRASH2.EXE 	\TEST\T_SQLFILESRVCRASH2.EXE
 file=ABI_DIR\BUILD_DIR\T_SQLENVDESTROY.EXE	\TEST\T_SQLENVDESTROY.EXE
 
 #endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/persistentstorage/sql/GROUP/t_sqlfilesrvcrash1.mmp	Fri Apr 16 16:49:27 2010 +0300
@@ -0,0 +1,32 @@
+// Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+TARGET        	t_sqlfilesrvcrash1.exe
+TARGETTYPE    	exe
+CAPABILITY      All -TCB
+
+USERINCLUDE   	.
+OS_LAYER_SYSTEMINCLUDE_SYMBIAN
+
+SOURCEPATH    	../TEST
+SOURCE 			t_sqlfilesrvcrash1.cpp
+
+LIBRARY 		euser.lib 
+LIBRARY			sqldb.lib 
+LIBRARY			efsrv.lib
+
+VENDORID		0x70000001
+
+SMPSAFE
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/persistentstorage/sql/GROUP/t_sqlfilesrvcrash2.mmp	Fri Apr 16 16:49:27 2010 +0300
@@ -0,0 +1,33 @@
+// Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+#include "sqlite_macro.mmh"
+
+TARGET        	t_sqlfilesrvcrash2.exe
+TARGETTYPE    	exe
+CAPABILITY      NONE
+
+USERINCLUDE   	.
+OS_LAYER_SYSTEMINCLUDE_SYMBIAN
+
+SOURCEPATH    	../TEST
+SOURCE t_sqlfilesrvcrash2.cpp
+
+LIBRARY 		euser.lib 
+LIBRARY			sqldb.lib 
+LIBRARY			efsrv.lib
+
+VENDORID		0x70000001
+
+SMPSAFE
\ No newline at end of file
--- a/persistentstorage/sql/GROUP/t_sqlfserr.mmp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/GROUP/t_sqlfserr.mmp	Fri Apr 16 16:49:27 2010 +0300
@@ -44,6 +44,7 @@
 LIBRARY			hal.lib 
 STATICLIBRARY	sqlite.lib 
 
+UID				0 0x212A2C27
 VENDORID		0x70000001
 
 SMPSAFE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/persistentstorage/sql/GROUP/t_sqlstartup.mmp	Fri Apr 16 16:49:27 2010 +0300
@@ -0,0 +1,81 @@
+// Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+TARGET			t_sqlstartup.exe
+TARGETTYPE		EXE
+CAPABILITY      ProtServ AllFiles
+
+EPOCFIXEDPROCESS
+
+#ifdef WINSCW
+EPOCHEAPSIZE 0x00020000 0x00600000
+#else
+EPOCHEAPSIZE 0x00020000 0x02000000
+#endif
+
+EPOCSTACKSIZE	0x3000
+
+UID		    0 0x10281E17
+
+MACRO SQLSRV_STARTUP_TEST
+
+USERINCLUDE 	.
+USERINCLUDE 	../INC
+USERINCLUDE 	../SRC/Common
+USERINCLUDE 	../SRC/Common/IPC
+USERINCLUDE 	../SRC/Common/Trace
+USERINCLUDE 	../SRC/Server
+USERINCLUDE 	../SRC/Server/Compact
+USERINCLUDE 	../SRC/Server/IPC
+USERINCLUDE 	../SRC/Security
+USERINCLUDE 	../SQLite
+USERINCLUDE 	../OsLayer
+OS_LAYER_SYSTEMINCLUDE_SYMBIAN
+OS_LAYER_ESTLIB_SYSTEMINCLUDE
+
+SOURCEPATH		../TEST
+SOURCE			t_sqlstartup.cpp
+
+SOURCEPATH		../SRC/Common
+SOURCE			SqlBufFlat.cpp
+SOURCE			SqlUtil.cpp
+
+SOURCEPATH		../SRC/Server
+SOURCE			SqlBur.cpp
+SOURCE			SqlSrvConfig.cpp
+SOURCE			SqlSrvMain.cpp
+SOURCE			SqlSrvDriveSpace.cpp
+SOURCE			SqlSrvStrings.cpp
+SOURCE			SqlSrvStatementUtil.cpp
+SOURCE			SqlSrvSecurityMap.cpp
+SOURCE			SqlSrvUtil.cpp
+
+SOURCEPATH		../SRC/Server/Compact
+SOURCE			SqlCompact.cpp
+SOURCE			SqlCompactConn.cpp
+SOURCE			SqlCompactEntry.cpp
+SOURCE			SqlCompactTimer.cpp
+
+LIBRARY			estlib.lib 
+LIBRARY			hal.lib 
+LIBRARY			euser.lib 
+LIBRARY			efsrv.lib
+LIBRARY			estor.lib 
+LIBRARY			abclient.lib
+STATICLIBRARY	sqlite.lib
+
+VENDORID		0x70000001
+
+SMPSAFE
--- a/persistentstorage/sql/INC/SqlDb.h	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/INC/SqlDb.h	Fri Apr 16 16:49:27 2010 +0300
@@ -167,6 +167,10 @@
 Note that in the cases where an 'overriding' security policy was not originally assigned,
 then the security policy returned will simply be the default security policy.
 
+Note: The database security policies are used to control the access to the objects (tables, indexes, triggers, views)
+in the main database. The access to the temporary tables, indexes, etc. is not a subject of any restrictions, e.g.
+a client with "read" database security policy only can create and use temporary tables, views, indexes, triggers.
+
 @see TSecurityPolicy
 @see RSqlDatabase
 @see RSqlSecurityPolicy::SetDbPolicy()
--- a/persistentstorage/sql/OsLayer/FileBuf64.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/OsLayer/FileBuf64.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -192,44 +192,6 @@
 #endif//_DEBUG
 
 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-///////////////////////////        MFileInitializer64    /////////////////////////////////////////////////////////////
-//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-
-/**
-MFileInitializer64 interface provides only one abstract method - Init() that is used during the initialization of
-the RFileBuf64 objects.
-Here is what is the problem MFileInitializer64 tries to solve.
-RFileBuf64 has 4 different "resource acquisition" methods - Create(), Open(), Temp() and AdoptFromClient().
-They perform different actions and have different input arguments.
-This is the variable part of the RFileBuf64 initialization.
-Apart from that, RFileBuf64 has a "fixed" initialization part that does not change whatever the variable part is.
-If MFileInitializer64 interface is not used then the following chunk of code has to be duplicated 4 times:
-@code
-	TInt err = do_fixed_init();
-	if(err == KErrNone)
-		{
-		err = do_variable_init();
-		if(err != KErrNone)
-			{
-			revert_fixed_init();
-			}
-		}
-	return err;
-@endcode
-In order to avoid the code duplication, the fixed part of the initialization is moved to RFileBuf64::DoInit(), which
-is given a reference to a MFileInitializer64 derived class that performas the variable part of the initialization.
-4 different MFileInitializer64 derived classes are provided for the 4 different "resource acquisition" methods.
-All they store the variable part of the RFileBuf64 initialization parameters and implement MFileInitializer64::Init().
-
-@see RFileBuf64::DoInit()
-@internalComponent
-*/
-struct MFileInitializer64
-	{
-	virtual TInt Init(RFile64& aFile) = 0;
-	};
-	
-//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 ///////////////////////////        RFileBuf64    /////////////////////////////////////////////////////////////////////
 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 	
@@ -262,7 +224,6 @@
 
 @see TFileMode
 @see RFile64::Create()
-@see MFileInitializer64
 
 @panic FBuf64  7 In _DEBUG mode - Invalid aFs object (null file session handle).
 @panic FBuf64 10 In _DEBUG mode - Invalid file name length (zero file name length).
@@ -272,24 +233,12 @@
 	__FBUF64_ASSERT(aFs.Handle() != 0, EFBufPanicFsHandle);
 	__FBUF64_ASSERT(aFileName.Length() > 0, EFBufPanicFileNameLen);
 	
-	struct TFileCreateInitializer64 : public MFileInitializer64
-		{
-		inline TFileCreateInitializer64(RFs& aFs, const TDesC& aFileName, TUint aFileMode) :
-			iFs(aFs),
-			iFileName(aFileName),
-			iFileMode(aFileMode)
-			{
-			}
-		virtual TInt Init(RFile64& aFile)
-			{
-			return aFile.Create(iFs, iFileName, iFileMode);
-			}
-		RFs& 			iFs;
-		const TDesC& 	iFileName;
-		TUint 			iFileMode;
-		} initializer(aFs, aFileName, aFileMode);
-		
-	return DoInit(initializer);
+	TInt err = DoPreInit();
+	if(err == KErrNone)
+	    {
+	    err = iFile.Create(aFs, aFileName, aFileMode);
+	    }
+	return DoPostInit(err);
 	}
 
 /**
@@ -306,7 +255,6 @@
 
 @see TFileMode
 @see RFile64::Open()
-@see MFileInitializer64
 
 @panic FBuf64  7 In _DEBUG mode - Invalid aFs object (null file session handle).
 @panic FBuf64 10 In _DEBUG mode - Invalid file name length (zero file name length).
@@ -316,24 +264,12 @@
 	__FBUF64_ASSERT(aFs.Handle() != 0, EFBufPanicFsHandle);
 	__FBUF64_ASSERT(aFileName.Length() > 0, EFBufPanicFileNameLen);
 	
-	struct TFileOpenInitializer64 : public MFileInitializer64
-		{
-		inline TFileOpenInitializer64(RFs& aFs, const TDesC& aFileName, TUint aFileMode) :
-			iFs(aFs),
-			iFileName(aFileName),
-			iFileMode(aFileMode)
-			{
-			}
-		virtual TInt Init(RFile64& aFile)
-			{
-			return aFile.Open(iFs, iFileName, iFileMode);
-			}
-		RFs& 			iFs;
-		const TDesC& 	iFileName;
-		TUint 			iFileMode;
-		} initializer(aFs, aFileName, aFileMode);
-
-	return DoInit(initializer);
+    TInt err = DoPreInit();
+    if(err == KErrNone)
+        {
+        err = iFile.Open(aFs, aFileName, aFileMode);
+        }
+    return DoPostInit(err);
 	}
 
 /**
@@ -352,7 +288,6 @@
 
 @see TFileMode
 @see RFile64::Temp()
-@see MFileInitializer64
 
 @panic FBuf64  7 In _DEBUG mode - Invalid aFs object (null file session handle).
 */
@@ -360,26 +295,12 @@
 	{
 	__FBUF64_ASSERT(aFs.Handle() != 0, EFBufPanicFsHandle);
 	
-	struct TFileTempInitializer64 : public MFileInitializer64
-		{
-		inline TFileTempInitializer64(RFs& aFs, const TDesC& aPath, TFileName& aFileName, TUint aFileMode) :
-			iFs(aFs),
-			iPath(aPath),
-			iFileName(aFileName),
-			iFileMode(aFileMode)
-			{
-			}
-		virtual TInt Init(RFile64& aFile)
-			{
-			return aFile.Temp(iFs, iPath, iFileName, iFileMode);
-			}
-		RFs& 			iFs;
-		const TDesC& 	iPath;
-		TFileName& 		iFileName;
-		TUint 			iFileMode;
-		} initializer(aFs, aPath, aFileName, aFileMode);
-	
-	return DoInit(initializer);
+    TInt err = DoPreInit();
+    if(err == KErrNone)
+        {
+        err = iFile.Temp(aFs, aPath, aFileName, aFileMode);
+        }
+    return DoPostInit(err);
 	}
 
 /**
@@ -398,7 +319,6 @@
 
 @see TFileMode
 @see RFile64::AdoptFromClient()
-@see MFileInitializer64
 @see KMaxMessageArguments
 
 @panic FBuf64  8 In _DEBUG mode - Invalid aMsg object (null message handle).
@@ -411,24 +331,12 @@
 	__FBUF64_ASSERT(aFsIndex >= 0 && aFsIndex < KMaxMessageArguments, EFBufPanicMsgIndex);
 	__FBUF64_ASSERT(aFileIndex >= 0 && aFileIndex < KMaxMessageArguments, EFBufPanicMsgIndex);
 	
-	struct TFileAdoptInitializer64 : public MFileInitializer64
-		{
-		inline TFileAdoptInitializer64(const RMessage2& aMsg, TInt aFsIndex, TInt aFileIndex) :
-			iMsg(aMsg),
-			iFsIndex(aFsIndex),
-			iFileIndex(aFileIndex)
-			{
-			}
-		virtual TInt Init(RFile64& aFile)
-			{
-			return aFile.AdoptFromClient(iMsg, iFsIndex, iFileIndex);
-			}
-		const RMessage2&	iMsg;
-		TInt 				iFsIndex;
-		TInt				iFileIndex;
-		} initializer(aMsg, aFsIndex, aFileIndex);
-	
-	return DoInit(initializer);
+    TInt err = DoPreInit();
+    if(err == KErrNone)
+        {
+        err = iFile.AdoptFromClient(aMsg, aFsIndex, aFileIndex);
+        }
+    return DoPostInit(err);
 	}
 
 /**
@@ -452,6 +360,16 @@
 
 /**
 Calculates and sets optimal read-ahead buffer size.
+aBlockSize and aReadRecBufSize values are retrieved by the caller from the file system.
+
+Initialization rules:
+Rule 1: If aReadRecBufSize is positive, bigger than the default read-ahead and 
+        a power of two then the read-ahead value will be
+        initialized with aReadRecBufSize (if aReadRecBufSize is less than the buffer capacity otherwise
+        the buffer capacity will be used as a read-ahead value). 
+Rule 2: If rule#1 is not applicable then the same checks, as in rule#1, are performed this time for aBlockSize.
+        If aBlockSize passes the checks then it will be used as a read-ahead value. 
+
 
 @param aBlockSize The size of a file block in bytes
 @param aReadRecBufSize The recommended buffer size for optimised reading performance
@@ -516,7 +434,7 @@
 	TInt len = aDes.MaxLength();
 	if(len > iCapacity)
 		{
-		if((aFilePos + len) > iFilePos && !(aFilePos >= (iFilePos + iLength)))
+		if((aFilePos + len) > iFilePos && aFilePos < (iFilePos + iLength))
 			{//Write the pending data if the iDirty flag is set, otherwise preserve the buffer content.
 			err = DoFileWrite1(aFilePos);
 			}
@@ -532,13 +450,13 @@
 	TUint8* outptr = const_cast <TUint8*> (aDes.Ptr());
 	while(len > 0 && err == KErrNone && aFilePos < iFileSize)
 		{
-		//1. If part of all of the data is in the buffer - copy the data to the target location
+		//1. If part or all of the data is in the buffer - copy the data to the target location
 		if(aFilePos >= iFilePos && aFilePos < (iFilePos + iLength))
 			{
-			TInt l = Min(len, (iFilePos + iLength - aFilePos));
-			outptr = Mem::Copy(outptr, iBase + (aFilePos - iFilePos), l);
-			len -= l;
-			aFilePos += l;
+			TInt blocklen = Min(len, (iFilePos + iLength - aFilePos));
+			outptr = Mem::Copy(outptr, iBase + (aFilePos - iFilePos), blocklen);
+			len -= blocklen;
+			aFilePos += blocklen;
 			}
 		//2. Perform a read-ahead operation
 		else
@@ -550,7 +468,7 @@
 				break;	
 				}
 			if(iNextReadFilePos != aFilePos)
-				{//Direct "file read" operation
+				{//Guessed read ahead was wrong. Direct "file read" operation
 				iNextReadFilePosHits = 0;
 				TPtr8 ptr2(outptr, len);
 				err = iFile.Read(aFilePos, ptr2);
@@ -804,31 +722,38 @@
 	}
 
 /**
-Performs the fixed part of the RFileBuf64 initialization and then calls MFileInitializer64::Init() to perform
-the variable part of the initialization.
+Initializes RFileBuf64 data members with their initial values.   
+Allocates memory for the file buffer. 
+ 
+@return KErrNone if successful, 
+        KErrNoMemory out of memory;
+*/
+TInt RFileBuf64::DoPreInit()
+    {
+    DoDiscard();
+    iReadAheadSize = RFileBuf64::KDefaultReadAheadSize;
+    iBase = static_cast <TUint8*> (User::Alloc(iCapacity));
+    return iBase ? KErrNone : KErrNoMemory; 
+    }
 
-@param aFileInitializer A reference to an initializer object that implements MFileInitializer64::Init()
+/**
+Performs post-initialization of the RFileBuf64 object.   
+If aInitErr is not KErrNone, then the buffer memory will be released.
+The function returns the aInitErr value to the caller. 
 
+@param aInitErr The result of the performed before the call RFileBuf64 initialization.
+ 
 @return KErrNone if successful, otherwise one of the other system-wide error codes.
 */
-TInt RFileBuf64::DoInit(MFileInitializer64& aFileInitializer)
-	{
-	DoDiscard();
-	iReadAheadSize = RFileBuf64::KDefaultReadAheadSize;
-	TInt err = KErrNoMemory;
-	iBase = static_cast <TUint8*> (User::Alloc(iCapacity));
-	if(!iBase)
-		{
-		return KErrNoMemory;	
-		}
-	err = aFileInitializer.Init(iFile);
-	if(err != KErrNone)
-		{
-		User::Free(iBase);
-		iBase = 0;
-		}
-	return err;
-	}
+TInt RFileBuf64::DoPostInit(TInt aInitErr)
+    {
+    if(aInitErr != KErrNone)
+        {
+        User::Free(iBase);
+        iBase = 0;
+        }
+    return aInitErr;
+    }
 
 /**
 Discards the content of the RFileBuf64 object returning it to the state as if it has just been created. 
--- a/persistentstorage/sql/OsLayer/FileBuf64.h	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/OsLayer/FileBuf64.h	Fri Apr 16 16:49:27 2010 +0300
@@ -18,9 +18,6 @@
 #include <f32file.h>
 #include <f32file64.h>
 
-//Forward declaration
-struct MFileInitializer64;
-
 /**
 The RFileBuf64 class provides buffered file read/write operations on a single RFile64 object.
 RFileBuf64::Read() and RFileBuf64::Write() methods may boost the performance of the read/write file operations up to 30% 
@@ -47,37 +44,41 @@
 	  In details, to create a file and access it through a RFileBuf64 object:
 	  
 	  	RFs fs;
-	  	//initialize the file session
+        TInt err = fs.Connect();
+        //check the error
 	  	...
 	  	RFileBuf64 fbuf(<N>);									//<N> is the buffer capacity in bytes
-	  	TInt err = fbuf.Create(fs, <file name>, <file mode>);
+	  	err = fbuf.Create(fs, <file name>, <file mode>);
 	  	//check the error
 	  	
 	  To open an existing file and access it through a RFileBuf64 object:
 
 	  	RFs fs;
-	  	//initialize the file session
+        TInt err = fs.Connect();
+        //check the error
 	  	...
 	  	RFileBuf64 fbuf(<N>);									//<N> is the buffer capacity in bytes
-	  	TInt err = fbuf.Open(fs, <file name>, <file mode>);
+	  	err = fbuf.Open(fs, <file name>, <file mode>);
 	  	//check the error
 	  
 	  To create a temporary file and access it through a RFileBuf64 object:
 
 	  	RFs fs;
-	  	//initialize the file session
+        TInt err = fs.Connect();
+        //check the error
 	  	...
 	  	RFileBuf64 fbuf(<N>);									//<N> is the buffer capacity in bytes
-	  	TInt err = fbuf.Temp(fs, <path>, <file name>, <file mode>);
+	  	err = fbuf.Temp(fs, <path>, <file name>, <file mode>);
 	  	//check the error
 	  
 	  To open a file from handle and access it through a RFileBuf64 object:
 
 	  	RFs fs;
-	  	//initialize the file session
+        TInt err = fs.Connect();
+        //check the error
 	  	...
 	  	RFileBuf64 fbuf(<N>);									//<N> is the buffer capacity in bytes
-	  	TInt err = fbuf.AdoptFromClient(<msg>, <fs handle index>, <file handle index>);
+	  	err = fbuf.AdoptFromClient(<msg>, <fs handle index>, <file handle index>);
 	  	//check the error
 
 	- if the RFileBuf64 object is initialised successfully, now the public RFileBuf64 methods can be called to perform
@@ -99,7 +100,7 @@
 @endcode
 
 Implementation notes: the current RFileBuf64 implementation is optimised for use by the SQLite OS porting layer.
-	After a detailed investigation of the performed by SQLite file read/write operations it was found that buffering of
+	After investigation of SQLite file read/write operations it was found that buffering of
 	two or more logical file writes into a single physical file write has a positive impact (as expected) on the performance 
 	of the database write operations. But the picture is quite different for the file read operations. The database data is
 	organised in pages with fixed size. After a database is created and set of insert/update/delete operations is performed 
@@ -160,7 +161,8 @@
 
 private:
 	void Invariant() const;
-	TInt DoInit(MFileInitializer64& aFileInitializer);
+	TInt DoPreInit();
+	TInt DoPostInit(TInt aInitErr);
 	void DoDiscard();
 	TInt DoFileSize();
 	TInt DoSetFileSize(TInt64 aFileSize);
--- a/persistentstorage/sql/OsLayer/os_symbian.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/OsLayer/os_symbian.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -1,4 +1,4 @@
-// Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+// Copyright (c) 2005-2010 Nokia Corporation and/or its subsidiary(-ies).
 // All rights reserved.
 // This component and the accompanying materials are made available
 // under the terms of "Eclipse Public License v1.0"
@@ -700,11 +700,7 @@
 	TFileName	iSysPrivDir;//"<system drive>:\" + process's private data path. Initialized in sqlite3SymbianFsOpen().
 							//Used for storing sqlite temporary files.
 	TInt64		iSeed;
-	RAllocator*	iAllocator;
 
-	enum {KZeroBufSize = SQLITE_DEFAULT_SECTOR_SIZE};
-    TBuf8<KZeroBufSize> iZeroBuf;
-	
 private:	
 	static COsLayerData* 	iOsLayerData;
 	TInt					iStoredOsErrorCode;	//Contains the last OS error code.
@@ -712,6 +708,17 @@
 	TBool					iReadOnly;			//Fh data
 	};
 
+/**
+This functon returns a reference to the current thread allocator object.
+The static RAllocator& variable will be initialized once at the moment when the function is called for 
+first time. 
+*/
+static RAllocator& Allocator()
+    {
+    static RAllocator& allocator = User::Allocator();
+    return allocator;
+    }
+
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 ///////////////////////////////////       TDbFile struct declaration      /////////////////////////////////////////////////////
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -819,7 +826,7 @@
 	static TInt DoGetDeviceCharacteristics(const TDriveInfo& aDriveInfo, const TVolumeIOParamInfo& aVolumeInfo);
 	static TInt DoGetSectorSize(const TDriveInfo& aDriveInfo, const TVolumeIOParamInfo& aVolumeInfo);
 	static TInt DoGetDeviceCharacteristicsAndSectorSize(TDbFile& aDbFile, TInt& aRecReadBufSize);
-	
+	static TInt DoFileSizeCorruptionCheck(TDbFile& aDbFile, const TDesC& aFname, TInt aFmode);
 	};
 
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -1042,7 +1049,6 @@
 Initializes the COsLayerData data members with their default values.
 */
 inline COsLayerData::COsLayerData() :
-	iAllocator(0),
 	iStoredOsErrorCode(KErrNone),
 	iMessage(0),
 	iReadOnly(EFalse)
@@ -1050,7 +1056,6 @@
 	TTime now;
 	now.UniversalTime();
 	iSeed = now.Int64();
-   	iZeroBuf.FillZ(COsLayerData::KZeroBufSize);
 	}
 
 /**
@@ -1084,7 +1089,6 @@
 */
 TInt COsLayerData::DoCreate()
 	{
-	iAllocator = &User::Allocator();
 	__FS_CALL(EFsOpFsConnect, 0);
 	TInt err = iFs.Connect();
 	if(err != KErrNone)
@@ -1447,8 +1451,7 @@
 SQLite OS porting layer API.
 
 Closes the file referred by aDbFile parameter.
-If aDbFile, which is actually a pointer to a TDbFile instance, the iFullName data member is not NULL, 
-then the file will be deleted.
+If aDbFile.iFullName data member is not NULL, then the file will be deleted.
 
 @param aDbFile A pointer to a TDbFile instance, than contains the file handle to be closed.
 
@@ -1465,7 +1468,8 @@
 	__FS_CALL(EFsOpFileClose, 0);
 	dbFile.iFileBuf.Close();
 	if(dbFile.iFullName)
-		{
+		{//"iFullName" will not be NULL only when TVfs::Open() is called with SQLITE_OPEN_DELETEONCLOSE flag.
+		 //That means - SQlite expects the file to be deleted after the file close operation. 
 		__FS_CALL(EFsOpFileDelete, 0);
 		(void)COsLayerData::Instance().iFs.Delete(*dbFile.iFullName);
 		delete dbFile.iFullName;
@@ -2107,6 +2111,64 @@
 /**
 SQLite OS porting layer API.
 
+The behaviour of the RFile/RFile64::SetSize operation is not atomic for non-rugged drives. 
+When RFile/RFile64::SetSize() is called 2 operations occurs:-
+
+1)The cluster chain of the file is updated.
+2)The new file size is added to the file cache.
+
+If a power loss occurs after a SetSize there is a chance that the cluster chain was updated 
+but the new file size is not yet flushed to the file. This puts the file into an inconsistent state.
+This is most likely to occur in the journal file where the time between a SetSize and Flush can 
+be long. 
+
+For this reason this check is added when the file is opened to see if the end of the file can 
+be read straight away, if an error is returned then it is assumed that the SetSize has not be 
+completed previously. In this case the file is deleted and re-created.
+ 
+@param aDbFile A pointer to a TDbFile instance, that contains the file handle.
+@param aFname A string of 16-bit wide characters containing name of the file to be checked.
+@param aFmode The mode in which the file is opened. These mode are documented in TFileMode.
+
+@return KErrNone,          The operation has completed succesfully;
+                           Note that other system-wide error codes may also be returned.
+@see TFileMode
+@see TVfs::Open()
+@see TDbFile
+*/
+/* static */ TInt TVfs::DoFileSizeCorruptionCheck(TDbFile& aDbFile, const TDesC& aFname, TInt aFmode)
+    {
+    const TInt KMinSize = 16;
+    TInt64 size;
+    TInt err = KErrNone ;
+    TBuf8<KMinSize> buf;
+
+    err = aDbFile.iFileBuf.Size(size);
+    if (err != KErrNone)
+        {
+        return err;
+        }
+    TBool IsMinFileSize = (size >= KMinSize);
+    
+    if (IsMinFileSize)
+        {
+        err = aDbFile.iFileBuf.Read(size - KMinSize, buf);
+        }
+    
+    if (err == KErrCorrupt || err == KErrEof || !IsMinFileSize)
+        {
+        COsLayerData& osLayerData = COsLayerData::Instance();
+    
+        aDbFile.iFileBuf.Close();
+        (void) osLayerData.iFs.Delete(aFname);
+        err = aDbFile.iFileBuf.Create(osLayerData.iFs, aFname, aFmode);
+        }
+    return err;
+    }
+
+/**
+SQLite OS porting layer API.
+
 Opens or creates a file which name is in the aFileName parameter.
 If the function succeeds, the file handle and other related information will be stored in the place pointed by the 
 aDbFile parameter, a memory block of sizeof(TDbFile) size for which is allocated by the caller.
@@ -2211,6 +2273,12 @@
 				{
 				__FS_CALL(EFsOpFileOpen, 0);
 				err = dbFile.iFileBuf.Open(osLayerData.iFs, fname, fmode);
+				
+				if(err == KErrNone && ((aFlags & SQLITE_OPEN_MAIN_JOURNAL) || (aFlags & SQLITE_OPEN_TEMP_JOURNAL) || 
+                        (aFlags & SQLITE_OPEN_SUBJOURNAL) || (aFlags & SQLITE_OPEN_MASTER_JOURNAL)))
+				    {
+                    err = TVfs::DoFileSizeCorruptionCheck(dbFile, fname, fmode);
+				    }
 				}
 			if((err != KErrNone && err != KErrNoMemory && err != KErrDiskFull) && (aFlags & SQLITE_OPEN_READWRITE))
 				{
@@ -2219,7 +2287,7 @@
 				fmode &= ~EFileWrite;
 				__FS_CALL(EFsOpFileOpen, 0);
    				err = dbFile.iFileBuf.Open(osLayerData.iFs, fname, fmode);
-   				}
+				}
 			if(err != KErrNone && prevErr == KErrAccessDenied)
 				{
 				err = KErrAccessDenied;
@@ -2237,6 +2305,11 @@
 		dbFile.iFileBuf.Close();	
 		delete dbFile.iFullName;
 		dbFile.iFullName = NULL;
+        if(!aFileName && fname.Length() > 0)
+            {//temporary file, the error is not KErrNone. Then delete the file (after a successfull 
+             //temporary file creation there could be a failed memory allocation)
+            (void)osLayerData.iFs.Delete(fname);
+            }
 		}
 	else
 		{
@@ -2550,7 +2623,7 @@
 extern "C" void* sqlite3SymbianMalloc(size_t aSize)
 	{
 	__MEM_CALL(EMemOpAlloc, aSize, 0);
-	return COsLayerData::Instance().iAllocator->Alloc(aSize);
+	return Allocator().Alloc(aSize);
 	}
 
 /**
@@ -2563,10 +2636,10 @@
 extern "C" void* sqlite3SymbianRealloc(void* aPtr, size_t aSize)
 	{
 #ifdef _SQLPROFILER
-	TInt size = COsLayerData::Instance().iAllocator->AllocLen(aPtr);
+	TInt size = Allocator().AllocLen(aPtr);
 	__MEM_CALL(EMemOpRealloc, aSize, size);
 #endif
-	return COsLayerData::Instance().iAllocator->ReAlloc(aPtr, aSize);
+	return Allocator().ReAlloc(aPtr, aSize);
 	}
 
 /**
@@ -2579,10 +2652,10 @@
 extern "C" void sqlite3SymbianFree(void* aPtr)
 	{
 #ifdef _SQLPROFILER
-	TInt size = COsLayerData::Instance().iAllocator->AllocLen(aPtr);
+	TInt size = Allocator().AllocLen(aPtr);
 	__MEM_CALL(EMemOpFree, size, 0);
 #endif
-	COsLayerData::Instance().iAllocator->Free(aPtr);
+	Allocator().Free(aPtr);
 	}
 
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
--- a/persistentstorage/sql/SQLite/parse.h	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/SQLite/parse.h	Fri Apr 16 16:49:27 2010 +0300
@@ -1,3 +1,20 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
 #define TK_SEMI                            1
 #define TK_EXPLAIN                         2
 #define TK_QUERY                           3
--- a/persistentstorage/sql/SQLite/printf.c	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/SQLite/printf.c	Fri Apr 16 16:49:27 2010 +0300
@@ -1,3 +1,19 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
 /*
 ** The "printf" code that follows dates from the 1980's.  It is in
 ** the public domain.  The original comments are included here for
--- a/persistentstorage/sql/SQLite364/parse.h	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/SQLite364/parse.h	Fri Apr 16 16:49:27 2010 +0300
@@ -1,3 +1,20 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
 #define TK_SEMI                            1
 #define TK_EXPLAIN                         2
 #define TK_QUERY                           3
--- a/persistentstorage/sql/SQLite364/printf.c	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/SQLite364/printf.c	Fri Apr 16 16:49:27 2010 +0300
@@ -1,3 +1,19 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
 /*
 ** The "printf" code that follows dates from the 1980's.  It is in
 ** the public domain.  The original comments are included here for
--- a/persistentstorage/sql/SRC/Client/SqlDbSession.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/SRC/Client/SqlDbSession.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -303,7 +303,11 @@
 */
 TInt RSqlDbSession::Connect(TSqlSrvFunction aFunction, const TDesC& aDbFileName, const TDesC8& aSecurityPolicyData, const TDesC8* aConfig)
 	{
+#ifdef SYSLIBS_TEST
+    const TInt KDefaultMsgBufLen = 4;
+#else	
 	const TInt KDefaultMsgBufLen = 128;
+#endif	
 	iLastErrorMessage = HBufC::New(KDefaultMsgBufLen);
 	if(!iLastErrorMessage)
 		{
--- a/persistentstorage/sql/SRC/Client/SqlStatementImpl.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/SRC/Client/SqlStatementImpl.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -652,10 +652,15 @@
 			}
 		TPtr8 ptr(reinterpret_cast <TUint8*> (const_cast <TUint16*> (aDest.Ptr())), aDest.MaxLength() * sizeof(TUint16));
 		err = iSqlStmtSession.ReadColumnValue(aColumnIndex, ptr);
-		if(err == KErrNone || err == KErrOverflow)
-			{
-			aDest.SetLength(ptr.Length() / sizeof(TUint16));
-			}
+		switch(err)
+		    {
+	        case KErrNone:
+	        case KErrOverflow:
+	            aDest.SetLength(ptr.Length() / sizeof(TUint16));
+	            break;
+	        default:
+	            break;
+		    }
 		}
 	else
 		{
--- a/persistentstorage/sql/SRC/Server/SqlBur.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/SRC/Server/SqlBur.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -17,26 +17,6 @@
 #include "SqlAssert.h"
 #include "SqlPanic.h"
 
-///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-//////////////                     Backup database file header format                           ///////////////////
-///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-
-////// No version (Version 0)
-//  8 chars          8 chars          8 chars             up to 256 characters (512 bytes)
-// <32-bit checksum><32-bit filesize><32-bit filenamelen><filename - UTF16 encoded>
-
-//////             Version 2
-//  8 chars          8 chars   4 chars     16 chars         8 chars             up to 256 characters (512 bytes)
-// <32-bit checksum><FFFFAA55><Version N#><64-bit filesize><32-bit filenamelen><filename - UTF16 encoded>
-
-const TInt KBackupHeaderVersion = 2;			//Current backup database file header version
-
-const TUint32 KMagicNum = 0xFFFFAA55;			//Magic number. If the "old database file size" field in the header
-												//has this value, then the header version is 2+
-const TInt KMaxHeaderSize = 256 + KMaxFileName;	//The size of the buffer used for the operations on the header
-
-///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-
 //Extracts and returns 32-bit integer from aNumBuf buffer.
 static TUint32 GetNumUint32L(const TDesC& aNumBuf)
 	{
@@ -115,9 +95,6 @@
 	// make sure the file list is released
 	iFileList.Reset();
 	
-	// the header buffer
-	delete iBuffer;
-	
 	// the file list array
 	iFileList.Close();
 	
@@ -125,10 +102,7 @@
 	iFile.Close();
 	
 	// nuke the active backup client
-	if(iActiveBackupClient)
-		{
-		delete iActiveBackupClient;
-		}
+    delete iActiveBackupClient;
 	}
 
 /** Standard two phase construction
@@ -142,9 +116,6 @@
 	// add us to the scheduler
 	CActiveScheduler::Add(this);
 
-	// a place for the header info
-	iBuffer=HBufC::NewL(KMaxHeaderSize);
-
 	// set active and request notification of changes to backup
 	// and restore publish/subscribe property
 	StartL();	
@@ -173,11 +144,8 @@
 */
 void CSqlBackupClient::StartL()
 	{
-	if(!IsActive())
-		{
-		TestBurStatusL();
-		NotifyChange();
-		}
+    TestBurStatusL();
+    NotifyChange();
 	}
 
 /** Resubscribe and wait for events
@@ -202,27 +170,16 @@
 		status&=KBURPartTypeMask;
 		switch(status)
 			{
-			case EBURUnset:
-				// same as EBURNormal
+			case EBURUnset: // same as EBURNormal
 			case EBURNormal:
-				if(iActiveBackupClient)
-					{
-					delete iActiveBackupClient;
-					iActiveBackupClient=NULL;
-					}
+				delete iActiveBackupClient;
+				iActiveBackupClient=NULL;
 				break;
 			case EBURBackupFull:
 			case EBURBackupPartial:
-				// we only do full backups
-				if(!iActiveBackupClient)
-					{
-					iActiveBackupClient=CActiveBackupClient::NewL(this);
-					}
-				iActiveBackupClient->ConfirmReadyForBURL(KErrNone);
-				break;
-			case EBURRestoreFull:
-			case EBURRestorePartial:
-				// we only do full restores
+            case EBURRestoreFull:
+            case EBURRestorePartial:
+				// we only do full backups and full restores
 				if(!iActiveBackupClient)
 					{
 					iActiveBackupClient=CActiveBackupClient::NewL(this);
@@ -322,17 +279,14 @@
 					break;
 					}
 				
-				// build the header - this is an instance member because it
-				// has to persist over multiple calls to this method
-				TPtr hdrPtr=iBuffer->Des();
-				
 				// get the checksum - only grab last 4 bytes - enough to be satisfied that
 				// the backup and restore worked ok
-				TUint32 checksum = CheckSumL(iFile) & 0xFFFFFFFF;
+				TUint32 checksum = CheckSumL(iFile) & KMaxTUint32;
 
-				// build the header
+                // build the header - this is an instance member because it
+                // has to persist over multiple calls to this method
 				const TDesC& fileName = iFileList[iFileIndex].FullName();
-				hdrPtr.Format(_L("%8x%8x%4x%16lx%8x%S"),
+				iBuffer.Format(_L("%8x%8x%4x%16lx%8x%S"),
 					checksum,					// %8x
 					KMagicNum,					// %8x
 					KBackupHeaderVersion,		// %4x
@@ -341,7 +295,7 @@
 					&fileName);					// %S
 				
 				// we need it to look like an 8bit buffer
-				TPtr8 hdrPtr8((TUint8*)hdrPtr.Ptr(),hdrPtr.Size(),hdrPtr.Size());
+				TPtr8 hdrPtr8((TUint8*)iBuffer.Ptr(), iBuffer.Size(), iBuffer.Size());
 							
 				TInt len = Min(hdrPtr8.Size(), bufFreeSpace);
 				
@@ -368,14 +322,13 @@
 			case EBackupOpenPartHeaderSent: // need to send the rest of the header
 				{
 				// get back the header - this is already loaded with the necessary info
-				// from the previous state we were in
-				TPtr hdrPtr = iBuffer->Des();
+				// from the previous state we were in - EBackupOpenNothingSent
 				
 				// we need it to look like an 8bit buffer
-				TPtr8 hdrPtr8((TUint8*)hdrPtr.Ptr(),hdrPtr.Size(),hdrPtr.Size());
+				TPtr8 hdrPtr8((TUint8*)iBuffer.Ptr(), iBuffer.Size(), iBuffer.Size());
 				
 				// how many bytes have we yet to send?
-				TInt bytesRemaining = hdrPtr.Size() - iHeaderSent;
+				TInt bytesRemaining = hdrPtr8.Size() - iHeaderSent;
 				TInt len = Min(bytesRemaining, bufFreeSpace);
 				aBuffer.Append(hdrPtr8.Ptr() + iHeaderSent, len);
 				
@@ -456,7 +409,7 @@
 */
 void CSqlBackupClient::InitialiseRestoreProxyBaseDataL(TSecureId aSid, TDriveNumber /* aDrive */)
 	{
-	iBuffer->Des().Zero();
+	iBuffer.Zero();
 	// this is the first state of the restore state machine
 	iState=ERestoreExpectChecksum;
 	iAnyData=EFalse; // to keep track in the state machine whether any data was actually sent
@@ -481,9 +434,6 @@
 	// fresh chunk of data
 	TInt inBufferPos = 0;
 
-	// convert the buffer - this is KMaxHeaderSize=256+KMaxFileName
-	TPtr outBufPtr = iBuffer->Des();	
-	
 	// to mark when the state machine is through
 	TBool done = EFalse;
 	
@@ -527,22 +477,22 @@
 			case ERestoreExpectChecksum: // 16 bytes (the header is UTF16 encoded, 8 unicode characters for the checksum)
 				{
 				const TInt KCheckSumStrLen = 8;
-				CopyBufData(aInBuffer, inBufferPos, outBufPtr, KCheckSumStrLen);
-				if(outBufPtr.Length() == KCheckSumStrLen)
+				CopyBufData(aInBuffer, inBufferPos, iBuffer, KCheckSumStrLen);
+				if(iBuffer.Length() == KCheckSumStrLen)
 					{
-					iChecksum = ::GetNumUint32L(outBufPtr);
+					iChecksum = ::GetNumUint32L(iBuffer);
 					iState = ERestoreExpectOldFileSize;
-					outBufPtr.Zero();
+					iBuffer.Zero();
 					}
 				break;
 				}
 			case ERestoreExpectOldFileSize: // 16 bytes (the header is UTF16 encoded, 8 unicode characters for 32-bit old file size)
 				{
 				const TInt KOldFileSizeStrLen = 8;
-				CopyBufData(aInBuffer, inBufferPos, outBufPtr, KOldFileSizeStrLen);
-				if(outBufPtr.Length() == KOldFileSizeStrLen)
+				CopyBufData(aInBuffer, inBufferPos, iBuffer, KOldFileSizeStrLen);
+				if(iBuffer.Length() == KOldFileSizeStrLen)
 					{
-					TUint32 oldFileSize = ::GetNumUint32L(outBufPtr);
+					TUint32 oldFileSize = ::GetNumUint32L(iBuffer);
 					if(oldFileSize == KMagicNum)
 						{
 						iState = ERestoreExpectVersion;
@@ -552,60 +502,60 @@
 						iFileSize = oldFileSize;	
 						iState = ERestoreExpectFileNameSize;
 						}
-					outBufPtr.Zero();
+					iBuffer.Zero();
 					}
 				break;
 				}	
 			case ERestoreExpectVersion:
 				{
 				const TInt KVersionStrLen = 4;
-				CopyBufData(aInBuffer, inBufferPos, outBufPtr, KVersionStrLen);
-				if(outBufPtr.Length() == KVersionStrLen)
+				CopyBufData(aInBuffer, inBufferPos, iBuffer, KVersionStrLen);
+				if(iBuffer.Length() == KVersionStrLen)
 					{
-					//Ignore the version: ::GetNumUint32L(outBufPtr);	
+					//Ignore the version: ::GetNumUint32L(iBuffer);	
 					//At this stage we know that the version is 2+
 					iState = ERestoreExpectFileSize;
-					outBufPtr.Zero();
+					iBuffer.Zero();
 					}
 				break;
 				}
 			case ERestoreExpectFileSize:
 				{
 				const TInt KFileSizeStrLen = 16;
-				CopyBufData(aInBuffer, inBufferPos, outBufPtr, KFileSizeStrLen);
-				if(outBufPtr.Length() == KFileSizeStrLen)
+				CopyBufData(aInBuffer, inBufferPos, iBuffer, KFileSizeStrLen);
+				if(iBuffer.Length() == KFileSizeStrLen)
 					{
-					iFileSize = GetNumInt64L(outBufPtr);	
+					iFileSize = GetNumInt64L(iBuffer);	
 					iState = ERestoreExpectFileNameSize;
-					outBufPtr.Zero();
+					iBuffer.Zero();
 					}
 				break;
 				}
 			case ERestoreExpectFileNameSize: // the size of the file name to restore
 				{
 				const TInt KFileNameLenStrLen = 8;
-				CopyBufData(aInBuffer, inBufferPos, outBufPtr, KFileNameLenStrLen);
-				if(outBufPtr.Length() == KFileNameLenStrLen)
+				CopyBufData(aInBuffer, inBufferPos, iBuffer, KFileNameLenStrLen);
+				if(iBuffer.Length() == KFileNameLenStrLen)
 					{
-					iFileNameSize = GetNumUint32L(outBufPtr);		
+					iFileNameSize = GetNumUint32L(iBuffer);		
 					iState = ERestoreExpectFileName;
-					outBufPtr.Zero();
+					iBuffer.Zero();
 					}
 				break;
 				}
 			case ERestoreExpectFileName:  // the name of the file to restore
 				{
-				CopyBufData(aInBuffer, inBufferPos, outBufPtr, iFileNameSize);
-				if(outBufPtr.Length() == iFileNameSize)
+				CopyBufData(aInBuffer, inBufferPos, iBuffer, iFileNameSize);
+				if(iBuffer.Length() == iFileNameSize)
 					{
 					iState = ERestoreExpectData;
-					outBufPtr.Append(KRestoreSuffix);
+					iBuffer.Append(KRestoreSuffix);
 					// now we start writing the data to the target file
 					// write to a temp - double disk space potentially
 					// once all the temp files are created, then they are renamed to the
 					// real file names in one fell swoop
-					__SQLLEAVE_IF_ERROR(iFile.Replace(iInterface->Fs(), outBufPtr, EFileWrite | EFileShareExclusive));
-					outBufPtr.Zero();
+					__SQLLEAVE_IF_ERROR(iFile.Replace(iInterface->Fs(), iBuffer, EFileWrite | EFileShareExclusive));
+					iBuffer.Zero();
 					}
 				break;
 				}
@@ -624,18 +574,19 @@
 			case ERestoreComplete: // file completely restored
 				{
 				// calculate the checksum
-				TUint32 cksum = CheckSumL(iFile) & 0xFFFFFFFF;
+				TUint32 cksum = CheckSumL(iFile) & KMaxTUint32;
 				
-				// validate that the checksum matches
-				if(cksum!=iChecksum)
-					{
-					__SQLLEAVE(KErrCorrupt);
-					}
-
 				// done with the file now - has to follow checksum cos it
-				// expects ann open file
+				// expects an open file
+                __SQLLEAVE_IF_ERROR(iFile.Flush());
 				iFile.Close();
 
+                // validate that the checksum matches
+                if(cksum!=iChecksum)
+                    {
+                    __SQLLEAVE(KErrCorrupt);
+                    }
+				
 				// end of data - or another file to be restored?
 				if(aFinishedFlag)
 					{
@@ -647,12 +598,12 @@
 					for(TInt a=0;a<dir->Count();++a)
 						{
 						TEntry entry=(*dir)[a];
-						TPtr rst=entry.iName.Des();
+						TPtrC rst=entry.iName.Des();
 						TInt len=rst.Length();
 						// format <filename>.db.bak.rst
 						// just a convenience!
-						TBufC<KMaxFileName> bak(rst.LeftTPtr(len-4));
-						TBufC<KMaxFileName> db(rst.LeftTPtr(len-8));
+						TPtrC bak(rst.Left(len - 4));//".rst" part excluded
+						TPtrC db(rst.Left(len - 8));//".bak.rst" part excluded
 						
 						// first, rename the orig .db as .bak just in case
 						// ok if not found - might have been deleted.
@@ -685,7 +636,7 @@
 					for(TInt a1=0;a1<dir->Count();++a1)
 						{
 						TEntry entry=(*dir)[a1];
-						TPtr bak=entry.iName.Des();
+						TPtrC bak=entry.iName.Des();
 						__SQLLEAVE_IF_ERROR(iInterface->Fs().Delete(bak));
 						}
 					
@@ -728,23 +679,20 @@
 	for(TInt a=0;a<dir->Count();++a)
 		{
 		TEntry entry=(*dir)[a];
-		TPtr bak=entry.iName.Des();
+		TPtrC bak=entry.iName.Des();
 		TInt len=bak.Length();
-		TBufC<KMaxFileName> db(bak.LeftTPtr(len-4));
+		TPtrC db(bak.Left(len-4));//".bak" part excluded
 		rc=iInterface->Fs().Delete(db); // rename does not overwrite
-		if(KErrNone!=rc)
+		if(KErrNone == rc)
 			{
-			// nothing happened, still have bak file (and new db)
-			delete dir;
-			return;
+	        rc = iInterface->Fs().Rename(bak,db);
 			}
-		rc=iInterface->Fs().Rename(bak,db);
-		if(KErrNone!=rc)
-			{
-			// still have bak file, but db is gone!
-			delete dir;
-			return;
-			}
+        //The function cannot leave or return an error. The only thing which could be done here is to print out something
+		//and continue with the next file.
+		if(KErrNone != rc)
+		    {
+		    RDebug::Print(_L(" *** CSqlBackupClient::TerminateMultiStageOperation(), file \"%S\", err=%d\r\n"), &db, rc);
+		    }
 		// backup restored ok
 		}
 	// cleanup dir
--- a/persistentstorage/sql/SRC/Server/SqlBur.h	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/SRC/Server/SqlBur.h	Fri Apr 16 16:49:27 2010 +0300
@@ -25,6 +25,27 @@
 
 using namespace conn;
 
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+//////////////                     Backup database file header format                           ///////////////////
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+////// No version (Version 0)
+//  8 chars          8 chars          8 chars             up to 256 characters (512 bytes)
+// <32-bit checksum><32-bit filesize><32-bit filenamelen><filename - UTF16 encoded>
+
+//////             Version 2
+//  8 chars          8 chars   4 chars     16 chars         8 chars             up to 256 characters (512 bytes)
+// <32-bit checksum><FFFFAA55><Version N#><64-bit filesize><32-bit filenamelen><filename - UTF16 encoded>
+
+const TInt KBackupHeaderVersion = 2;            //Current backup database file header version
+
+const TUint32 KMagicNum = 0xFFFFAA55;           //Magic number. If the "old database file size" field in the header
+                                                //has this value, then the header version is 2+
+const TInt KMaxHeaderSize = 256 + KMaxFileName; //The size of the buffer used for the operations on the header
+
+///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+
 //-----------------------------------------
 // CSqlBackupClient
 //-----------------------------------------
@@ -127,7 +148,7 @@
 		RFile64 iFile;
 		TInt iFileIndex;
 		TUint iState;
-		HBufC* iBuffer; // used for the header data
+		TBuf<KMaxHeaderSize> iBuffer; // used for the header data
 		TInt iHeaderSent; // how many header bytes sent so far
 		TUint32 iChecksum; // used by restore
 		TInt64 iFileSize; // used by restore
--- a/persistentstorage/sql/SRC/Server/SqlSrvAuthorizer.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/SRC/Server/SqlSrvAuthorizer.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -269,14 +269,6 @@
 		case SQLITE_DROP_TRIGGER://          Trigger Name    Table Name      
 		case SQLITE_DROP_VIEW://             View Name       NULL            
 		case SQLITE_ALTER_TABLE://			 Database Name   Table Name
-		case SQLITE_CREATE_TEMP_INDEX://     Index Name      Table Name      
-		case SQLITE_CREATE_TEMP_TABLE://     Table Name      NULL            
-		case SQLITE_CREATE_TEMP_TRIGGER://   Trigger Name    Table Name      
-		case SQLITE_CREATE_TEMP_VIEW://      View Name       NULL            
-		case SQLITE_DROP_TEMP_INDEX://       Index Name      Table Name      
-		case SQLITE_DROP_TEMP_TABLE://       Table Name      NULL            
-		case SQLITE_DROP_TEMP_TRIGGER://     Trigger Name    Table Name      
-		case SQLITE_DROP_TEMP_VIEW://        View Name       NULL            
 		case SQLITE_SELECT://                NULL            NULL            
 		case SQLITE_TRANSACTION://           NULL            NULL          
 		case SQLITE_DELETE://                Table Name      NULL
@@ -294,6 +286,16 @@
 		case SQLITE_PRAGMA://                Pragma Name     1st arg or NULL 
 			res = PragmaCheck(aDbObjName1, (aDbObjName2 != NULL), EFalse);
 			break;
+//All "temp" operations are handled earlier, in CSqlSrvDatabase::AuthorizeCallback(), where a check for "temp"
+//database name is performed.
+//      case SQLITE_CREATE_TEMP_INDEX://     Index Name      Table Name      
+//      case SQLITE_CREATE_TEMP_TABLE://     Table Name      NULL            
+//      case SQLITE_CREATE_TEMP_TRIGGER://   Trigger Name    Table Name      
+//      case SQLITE_CREATE_TEMP_VIEW://      View Name       NULL            
+//      case SQLITE_DROP_TEMP_INDEX://       Index Name      Table Name      
+//      case SQLITE_DROP_TEMP_TABLE://       Table Name      NULL            
+//      case SQLITE_DROP_TEMP_TRIGGER://     Trigger Name    Table Name      
+//      case SQLITE_DROP_TEMP_VIEW://        View Name       NULL            
 		default:
 			__SQLASSERT(EFalse, ESqlPanicInternalError);
 			break;
@@ -360,14 +362,6 @@
 				}
 			break;
 		//No policy check
-		case SQLITE_CREATE_TEMP_INDEX://     Index Name      Table Name      
-		case SQLITE_CREATE_TEMP_TABLE://     Table Name      NULL            
-		case SQLITE_CREATE_TEMP_TRIGGER://   Trigger Name    Table Name      
-		case SQLITE_CREATE_TEMP_VIEW://      View Name       NULL            
-		case SQLITE_DROP_TEMP_INDEX://       Index Name      Table Name      
-		case SQLITE_DROP_TEMP_TABLE://       Table Name      NULL            
-		case SQLITE_DROP_TEMP_TRIGGER://     Trigger Name    Table Name      
-		case SQLITE_DROP_TEMP_VIEW://        View Name       NULL            
 		case SQLITE_SELECT://                NULL            NULL            
 		case SQLITE_TRANSACTION://           NULL            NULL            
 			break;
@@ -423,6 +417,16 @@
 		//No policy check
 		case SQLITE_FUNCTION:
 			break;
+//All "temp" operations are handled earlier, in CSqlSrvDatabase::AuthorizeCallback(), where a check for "temp"
+//database name is performed.
+//      case SQLITE_CREATE_TEMP_INDEX://     Index Name      Table Name      
+//      case SQLITE_CREATE_TEMP_TABLE://     Table Name      NULL            
+//      case SQLITE_CREATE_TEMP_TRIGGER://   Trigger Name    Table Name      
+//      case SQLITE_CREATE_TEMP_VIEW://      View Name       NULL            
+//      case SQLITE_DROP_TEMP_INDEX://       Index Name      Table Name      
+//      case SQLITE_DROP_TEMP_TABLE://       Table Name      NULL            
+//      case SQLITE_DROP_TEMP_TRIGGER://     Trigger Name    Table Name      
+//      case SQLITE_DROP_TEMP_VIEW://        View Name       NULL            
 		default:
 			__SQLASSERT(EFalse, ESqlPanicInternalError);
 			break;
--- a/persistentstorage/sql/SRC/Server/SqlSrvGetFirstSqlStmt.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,61 +0,0 @@
-// Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
-// All rights reserved.
-// This component and the accompanying materials are made available
-// under the terms of "Eclipse Public License v1.0"
-// which accompanies this distribution, and is available
-// at the URL "http://www.eclipse.org/legal/epl-v10.html".
-//
-// Initial Contributors:
-// Nokia Corporation - initial contribution.
-//
-// Contributors:
-//
-// Description:
-//
-
-#include <e32std.h>
-#include "sqlite3.h"
-
-//This function searches aString argument for ';' occurences.
-//Every time when it finds a ';' character, the function places a 0 right after the ';' and
-//tests the just created, zero-terminated substring if it is a comlpete SQL statement.
-//
-//If it is a SQL statement, the function replaces the found ';' character with 0 and returns the just created
-//zero-terminated substring.Also the function modifies aString argument to point right after the found
-//SQL string. If it is not SQL statement, the function will continue the searching.
-//
-//If there is no ';' inside aString argument, the function returns the same string as a return result and
-//modifies aString argument - sets it to TPtr(NULL, 0, 0).
-//
-//The function expects aString argument to be zero-terminated.
-TPtrC GetFirstSqlStmt(TPtr& aString)
-	{
-	const TChar KDelimitier(';');
-	TPtr str(const_cast <TUint16*> (aString.Ptr()), aString.Length(), aString.Length());
-	TInt afterDelimitierPos = 0;
-	TInt pos;
-	while((pos = str.Locate(KDelimitier) + 1) > 0 && pos < str.Length())
-		{
-		//There is a possibility that the string which terminates with the found ';' is SQL statement.
-		//Zero terminate the string placing a zero right after ';' character and test it using sqlite3_complete16()
-		//call. If it is not SQL string, restore the original character and continue searching.
-		afterDelimitierPos += pos;
-		TChar ch = aString[afterDelimitierPos];
-		aString[afterDelimitierPos] = 0;
-		TInt res = sqlite3_complete16(aString.Ptr());
-		aString[afterDelimitierPos] = ch;
-		if(res)
-			{
-			str.Set(const_cast <TUint16*> (aString.Ptr()), afterDelimitierPos, afterDelimitierPos);	
-			//Replace the found ';' character with 0.
-			str[afterDelimitierPos - 1] = 0;
-			aString.Set(const_cast <TUint16*> (aString.Ptr()) + afterDelimitierPos, aString.Length() - afterDelimitierPos, aString.Length() - afterDelimitierPos);
-			return str;
-			}
-		str.Set(const_cast <TUint16*> (str.Ptr()) + pos, str.Length() - pos, str.Length() - pos);	
-		}
-	//aString argument does not contain valid SQL statement or there is no ';' character inside aString.
-	//Set aString to TPtr(NULL, 0, 0) and return the original string.
-	aString.Set(NULL, 0, 0);
-	return str;
-	}
--- a/persistentstorage/sql/SRC/Server/SqlSrvMain.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/SRC/Server/SqlSrvMain.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -233,6 +233,9 @@
 
 /**
 Creates new CSqlSrvSession instance.
+If SQLSRV_STARTUP_TEST macro is defined, then the function returns NULL.
+The "real" implementation of the function is not used in this case because the used unit test will require 
+a lot of cpp files to be included into the test build (t_sqlstartup).
 
 @return A pointer to the created CSqlSrvSession instance.
 
@@ -241,15 +244,20 @@
        
 @see CSqlSrvSession
 */
-CSession2* CSqlServer::NewSessionL(const TVersion &aVersion, const RMessage2&) const
-	{
-	if(!User::QueryVersionSupported(::SqlSrvVersion(), aVersion))
-		{
-		User::Leave(KErrNotSupported);
-		}
-	CSqlSrvSession* sess = CSqlSrvSession::NewL();
-	return sess;
-	}
+CSession2* CSqlServer::NewSessionL(const TVersion& aVersion, const RMessage2&) const
+    {
+#ifdef SQLSRV_STARTUP_TEST
+    aVersion.Name();//to prevent the compiler warning ("unused parameter").
+    return NULL;
+#else
+    if(!User::QueryVersionSupported(::SqlSrvVersion(), aVersion))
+        {
+        User::Leave(KErrNotSupported);
+        }
+    CSqlSrvSession* sess = CSqlSrvSession::NewL();
+    return sess;
+#endif //SQLSRV_STARTUP_TEST
+    }
 
 /**
 CSqlServer's active object priority.
@@ -283,7 +291,11 @@
 */
 void CSqlServer::ConstructL()
 	{
+#ifndef SQLSRV_STARTUP_TEST
+	//Start the server only in "normal" builds, not in the case where t_sqlstartup unit test tests directly
+	//the SQL server startup code.
 	StartL(KSqlSrvName);
+#endif	
 #ifdef _SQLPROFILER 
     TheSqlSrvStartTime.UniversalTime();
     SQLPROFILER_SERVER_START();
@@ -329,18 +341,24 @@
 	//Compactor
 	iCompactor = CSqlCompactor::NewL(&SqlCreateCompactConnL, KSqlCompactStepIntervalMs);
 #ifdef _DEBUG
-	/*
-	 The following statements exist to prevent the failure of the resource allocation 
-	 checking for debug mode. 
-	 They allocate some memory when the server object is constructed so avoid these memory 
-	 allocations during debug mode. 
-	 */
-const TInt KAnyNumber	= 0xAA55; 
-const TInt KGreatSize = 1024; 
+    //The following statements exist to prevent the failure of the OOM testing in debug mode.
+	//The standard C library allocates some memory at the startup and stores a pointer to the allocated memory
+	//in the TLS. During normal API OOM testing the SQL server is not restarted, it never goes down.
+	//Then the TLS and the allocated memory are not released. In which case the OOM testing will fail
+	//(because the standard C library performs a lazy initialization and the allocation and TLS usage will be made
+	//at the point of first use of some C function. This is out of the control of the test code).
+	//In order to avoid that, during the SQL server startup here, before the OOM test goes and checks what 
+	//is the allocated memory at the beginning, a fake sprintf() call is made in order to force the mentioned above  
+	//allocation in the standard C library.
+	//All explanations above are true, except one case when the SQl server startup code is tested directly.
+    #ifndef SQLSRV_STARTUP_TEST
+	const TInt KAnyNumber	= 0xAA55; 
  	char tmp[32]; 
  	sprintf(tmp, "%04X", KAnyNumber);
+    const TInt KGreatSize = 1024; 
  	__SQLLEAVE_IF_ERROR(ReAllocBuf(KGreatSize));
-#endif 	
+    #endif //SQLSRV_STARTUP_TEST 	
+#endif //_DEBUG 	
 	}
 
 /**
@@ -436,6 +454,7 @@
 */
 void CSqlServer::GetBackUpListL(TSecureId aUid, RArray<TParse>& aFileList)
 	{
+	aFileList.Reset();
 	TFindFile findFile(iFileData.Fs());
 	CDir* fileNameCol = NULL;
 	TUidName uidName = (static_cast <TUid> (aUid)).Name();
@@ -490,6 +509,8 @@
 ////////////////////////////////////////   SQL server startup   //////////////////////////////////////////////
 //////////////////////////////////////////////////////////////////////////////////////////////////////////////
 
+#ifndef SQLSRV_STARTUP_TEST
+
 //Run the SQL server
 static void RunServerL()
 	{
@@ -526,3 +547,4 @@
 	return err;
 	}
 
+#endif //SQLSRV_STARTUP_TEST
--- a/persistentstorage/sql/SRC/Server/SqlSrvSession.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/SRC/Server/SqlSrvSession.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -519,17 +519,24 @@
 	__SQLPANIC_CLIENT(!iDatabase, aMessage, ESqlPanicObjExists);
 	const TInt KSecurityPolicyLen = (aMessage.Int2() & 0x7fff0000) >> 16;
 	const TInt KConfigStringLen = aMessage.Int2() & 0xffff;
-	if(KSecurityPolicyLen < 0 || KConfigStringLen < 0 || KConfigStringLen > KSqlSrvMaxConfigStrLen)
+	if(KSecurityPolicyLen < 0 || (TUint)KConfigStringLen > KSqlSrvMaxConfigStrLen)
 		{
 		__SQLLEAVE(KErrArgument);	
 		}
-	TBuf8<KSqlSrvMaxConfigStrLen> configStr;
+	RBuf8 securityAndConfigBuf;
+	CleanupClosePushL(securityAndConfigBuf);
+	if((KSecurityPolicyLen + KConfigStringLen) > 0)
+	    {
+	    securityAndConfigBuf.CreateL(KSecurityPolicyLen + KConfigStringLen);
+        aMessage.ReadL(3, securityAndConfigBuf); 
+        SQLPROFILER_REPORT_IPC(ESqlIpcRead, (KSecurityPolicyLen + KConfigStringLen));
+	    }
+	TSqlSrvFileData& fileData = Server().FileData();
+	TPtrC8 configStr(KNullDesC8);
 	if(KConfigStringLen > 0)
-		{
-		aMessage.ReadL(3, configStr, KSecurityPolicyLen);
-		SQLPROFILER_REPORT_IPC(ESqlIpcRead, KConfigStringLen);
-		}
-	TSqlSrvFileData& fileData = Server().FileData();
+	    {
+	    configStr.Set(securityAndConfigBuf.Mid(KSecurityPolicyLen));//the first part of the buffer is for the security policies
+	    }
 	fileData.SetL(aMessage, aMessage.Int0(), 1, &configStr);
 	iDrive = fileData.Drive();
 	switch(aFunction)
@@ -543,7 +550,7 @@
 			break;
 		case ESqlSrvDbCreateSecure:
 			{
-			if(!fileData.IsSecureFileNameFmt())
+			if(!fileData.IsSecureFileNameFmt() || KSecurityPolicyLen == 0)
 				{
 				__SQLLEAVE(KErrArgument);	
 				}
@@ -552,7 +559,7 @@
 				{
 				__SQLLEAVE(KErrPermissionDenied);	
 				}
-			CSqlSecurityPolicy* policy = InternalizeSecurityPolicyL(aMessage);
+			CSqlSecurityPolicy* policy = CreateSecurityPolicyL(securityAndConfigBuf.Left(KSecurityPolicyLen));
 			iDatabase = CSqlSrvDatabase::CreateSecureL(fileData, policy);
 			}
 			break;
@@ -563,6 +570,7 @@
 			__SQLLEAVE(KErrArgument);	
 			break;
 		}
+	CleanupStack::PopAndDestroy(&securityAndConfigBuf);
 	}
 
 /**
@@ -596,14 +604,8 @@
 	const TBool KCreated = (aMessage.Int0() & 0x40000000) != 0;
 	const TInt KDbFileNameLen = aMessage.Int0() & 0x0000FFFF;
 	const TInt KConfigStringLen = (aMessage.Int0() & 0x3FFF0000) >> 16;
-	if(KConfigStringLen < 0 || KConfigStringLen > KSqlSrvMaxConfigStrLen)
-		{
-		__SQLLEAVE(KErrArgument);	
-		}
-	if(KDbFileNameLen < 1 || KDbFileNameLen > KMaxFileName)
-		{
-		__SQLLEAVE(KErrBadName);
-		}
+    __SQLPANIC_CLIENT((TUint)KConfigStringLen <= KSqlSrvMaxConfigStrLen, aMessage, ESqlPanicBadArgument);
+    __SQLPANIC_CLIENT((TUint)KDbFileNameLen <= KMaxFileName, aMessage, ESqlPanicBadArgument);
 	TDes16& buffer = Server().GetBuf16L(KDbFileNameLen + KConfigStringLen);
 	aMessage.ReadL(1, buffer);
 	SQLPROFILER_REPORT_IPC(ESqlIpcRead, ((KDbFileNameLen + KConfigStringLen) * sizeof(TText)));
@@ -881,7 +883,7 @@
 	{
 	__SQLPANIC_CLIENT(iDatabase != NULL, aMessage, ESqlPanicInvalidObj);
 	const TInt KDbNameLen = aMessage.Int1();
-	if(KDbNameLen < 0 || KDbNameLen > KMaxFileName)
+	if((TUint)KDbNameLen > KMaxFileName)
 		{
 		__SQLLEAVE(KErrBadName);
 		}
@@ -928,7 +930,7 @@
 		return 0;	
 		}
 	const TInt KDbNameLen = aMessage.Int1();
-	if(KDbNameLen < 0 || KDbNameLen > KMaxFileName)
+	if((TUint)KDbNameLen > KMaxFileName)
 		{
 		__SQLLEAVE(KErrBadName);
 		}
@@ -1140,8 +1142,8 @@
 			__SQLLEAVE(KErrBadName);
 			}
 	  	}
-
-	 if(len < 1 || len > KMaxFileName)
+	 __SQLASSERT(len > 0, ESqlPanicInternalError);//The "if" above should have hanled the case with "len == 0"
+	 if((TUint)len > KMaxFileName)
 	  {
 	  __SQLLEAVE(KErrBadName);
 	  }
@@ -1617,47 +1619,21 @@
 	}
 
 /**
-The method reads the message argument 1 data and constructs a CSqlSecurityPolicy object from the data.
+The method constructs a CSqlSecurityPolicy object from the passed as an argument descriptor.
 
-@param aMessage Client request encapsulated in RMessage2 object.
+@param aSecurityPolicyData A descriptor with the security policy data.
 
 @return A pointer to the created CSqlSecurityPolicy instance.
 
-@leave KErrArgument, if aMessage argument 0 length is 0 or negative (no security data);
-       KErrNoMemory, out of memory condition has occured.
-
-Usage of the IPC call arguments:
-Arg 2: [in]  security policies buffer length in bytes if aFunction is ESqlSrvDbCreateSecure
-Arg 3: [in]  security policies buffer if aFunction is ESqlSrvDbCreateSecure
+@leave KErrNoMemory, out of memory condition has occured.
 */
-CSqlSecurityPolicy* CSqlSrvSession::InternalizeSecurityPolicyL(const RMessage2& aMessage)
+CSqlSecurityPolicy* CSqlSrvSession::CreateSecurityPolicyL(const TDesC8& aSecurityPolicyData)
 	{
-	// Leave if there is no security policy data
-	// The format of arg[2] is an unsigned int
-	// with the policy length shifted and concated to the config length
-	// the policy data is the first part of arg[3]
-	const TUint KConfigStrLenBitWidth = 16;
-	TInt securityPolicyLen = aMessage.Int2() >> KConfigStrLenBitWidth;
-	if(securityPolicyLen < 1)
-		{
-		__SQLLEAVE(KErrArgument);
-		}
 	TSecurityPolicy defaultPolicy(TSecurityPolicy::EAlwaysFail);
 	CSqlSecurityPolicy* dbPolicy = CSqlSecurityPolicy::NewLC(defaultPolicy);
 	RSqlBufFlat& bufFlat = dbPolicy->BufFlat();
-	if(securityPolicyLen > bufFlat.MaxSize())
-		{
-		__SQLLEAVE_IF_ERROR(bufFlat.ReAlloc(securityPolicyLen));
-		}
-	TPtr8& ptr = bufFlat.BufPtr();
-	aMessage.ReadL(3, ptr);
-	SQLPROFILER_REPORT_IPC(ESqlIpcRead, securityPolicyLen);
-	// trim off config data if any
-	TInt extraBytes = ptr.Length() - securityPolicyLen;
-	if(extraBytes > 0)
-		{
-		ptr.Delete(securityPolicyLen, extraBytes);
-		}
+    __SQLLEAVE_IF_ERROR(bufFlat.ReAlloc(aSecurityPolicyData.Length()));
+	bufFlat.BufPtr().Copy(aSecurityPolicyData);
 	CleanupStack::Pop(dbPolicy);
 	return dbPolicy;
 	}
--- a/persistentstorage/sql/SRC/Server/SqlSrvSession.h	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/SRC/Server/SqlSrvSession.h	Fri Apr 16 16:49:27 2010 +0300
@@ -113,7 +113,7 @@
 	TDes8& ReadString8ZL(const RMessage2& aMessage, TInt aArgNum, TInt aByteLen);
 	TDes16& ReadString16ZL(const RMessage2& aMessage, TInt aArgNum, TInt aCharLen);
 	TDes16& ReadString16L(const RMessage2& aMessage, TInt aArgNum, TInt aCharLen);
-	CSqlSecurityPolicy* InternalizeSecurityPolicyL(const RMessage2& aMessage);
+	CSqlSecurityPolicy* CreateSecurityPolicyL(const TDesC8& aSecurotyPolicyData);
 	virtual TInt CountResources();
 	void Extract(const RMessage2& aMessage, TSqlSrvFunction& aFunction, TInt& aHandle);
 	TInt GetColumnValueL(const RMessage2& aMessage, CSqlSrvStatement& aStmt, TSqlColumnType aColType);
--- a/persistentstorage/sql/SRC/Server/SqlSrvUtil.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/SRC/Server/SqlSrvUtil.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -156,7 +156,7 @@
 	des.Append(TChar(0));
 	TInt len = wcstombs((char*)aOut.Ptr(), (const wchar_t*)des.Ptr(), KMaxFileName);
 	//Check the file name length. If it is longer than KMaxFileName characters, then the file name is not valid.
-	if(len >= 0 && len <= KMaxFileName)
+	if((TUint)len <= KMaxFileName)
 		{
 		aOut.SetLength(len);
 		return ETrue;
@@ -185,7 +185,7 @@
 	const wchar_t* src = reinterpret_cast <const wchar_t*> (aFileName.Ptr());
 	TInt len = wcstombs((char*)aFileNameDestBuf.Ptr(), src, KMaxFileName);
 	//Check the file name length. If it is longer than KMaxFileName characters, then the file name is not valid.
-	if(len >= 0 && len <= KMaxFileName)
+	if((TUint)len <= KMaxFileName)
 		{
 		aFileNameDestBuf.SetLength(len + 1);
 		aFileNameDestBuf[len] = 0;
--- a/persistentstorage/sql/TEST/t_sqlapi.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/TEST/t_sqlapi.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -1,4 +1,4 @@
-// Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies).
+// Copyright (c) 2005-2010 Nokia Corporation and/or its subsidiary(-ies).
 // All rights reserved.
 // This component and the accompanying materials are made available
 // under the terms of "Eclipse Public License v1.0"
@@ -42,6 +42,7 @@
 _LIT8(KServerConfigString2, " badconfigstring ");
 _LIT8(KServerConfigString3, " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
 _LIT8(KServerConfigString4, "");
+_LIT8(KServerConfigString5, "dfgdfrgdkfjgjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj43w3wk4jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn");
 
 const TUid KSecureUid = {0x1111CCCC};//The same as the UID in the MMP file
 
@@ -244,7 +245,12 @@
 	db.Close();
 	rc2 = RSqlDatabase::Delete(KTestCfgDbName);
 	TEST2(rc2, KErrNone);
-		
+
+    // create database with very long config specified
+    rc = db.Create(KTestCfgDbName, &KServerConfigString5);
+    TEST2(rc, KErrArgument);
+    db.Close();
+	
 	//Secure shared database file on an existing drive (C:). 
 	//Very long database file name (> 90 characters) but still a valid name.
 	rc = db.Create(KTestDbName4, securityPolicy);
@@ -1110,6 +1116,10 @@
 	//Read row 2 using ColumnText(TInt aColumnIndex, TDes& aDest).
 	rc = stmt.ColumnText(1, colData);
 	TEST2(rc, KErrNone);
+	//Too small target buffer
+	TBuf<3> buf1;
+    rc = stmt.ColumnText(1, buf1);
+    TEST2(rc, KErrOverflow);
 	
 	//Check the column value
 	for(i=0;i<KTextLen;++i)
@@ -1224,6 +1234,10 @@
 	rc = db.Exec(sql);
 	TEST2(rc, 1);
 
+    //Insert row 3: the binary column length is just 2 bytes
+    rc = db.Exec(_L("INSERT INTO A VALUES(3, x'A5D3')"));
+    TEST2(rc, 1);
+	
 	//Prepare SELECT SQL statement
 	_LIT8(KSqlStmt3, "SELECT * FROM A");
 	RSqlStatement stmt = PrepareSqlStmt<TDesC8, TBuf8<KSqlBufSize> >(db, KSqlStmt3, KErrNone);
@@ -1315,6 +1329,19 @@
 		TEST(val = KHexVal2);	
 		}
 	
+    //Move on row 3. The binary column value length is just 2 bytes.
+    rc = stmt.Next();
+    TEST2(rc, KSqlAtRow);
+    rc = stmt.Next();
+    TEST2(rc, KSqlAtRow);
+    TBuf8<2> buf1;
+    rc = stmt.ColumnBinary(1, buf1); 
+    TEST2(rc, KErrNone);
+    TEST2(buf1.Length(), 2);
+    TBuf8<1> buf2;
+    rc = stmt.ColumnBinary(1, buf2); 
+    TEST2(rc, KErrOverflow);
+	
 	stmt.Close();
 	
 	//Deallocate buf
@@ -1534,6 +1561,10 @@
 	RSqlParamWriteStream paramStream;
 	rc = paramStream.BindBinary(stmt, 0);
 	TEST2(rc, KErrNone);
+	paramStream.Close();
+    //Open the parameter stream with BindBinaryL()
+    TRAP(rc, paramStream.BindBinaryL(stmt, 0));
+    TEST2(rc, KErrNone);
 
 	//Prepare and set the parameter value (NULL parameter value)
 	TPtr8 prmVal = buf->Des();
@@ -2059,6 +2090,14 @@
 	TPtrC msg = db.LastErrorMessage();
 	TheTest.Printf(_L("Non-existing attached database, error message: %S\r\n"), &msg);
 	
+    //An attempt to get the size when the attached database name contains "bad" unicode characters (cannot be converted to UTF8)
+    TBuf<2> dbName3;
+    dbName3.SetLength(2);
+    dbName3[0] = TChar(0xD800); 
+    dbName3[1] = TChar(0xFC00); 
+    err = db.Size(size1, dbName3);
+    TEST2(err, KErrGeneral);
+	
 	err = db.Detach(KAttachDbName);
 	TEST2(err, KErrNone);
 	db.Close();
--- a/persistentstorage/sql/TEST/t_sqlapi2.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/TEST/t_sqlapi2.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -460,6 +460,12 @@
 	err = TheStmt.ColumnName(0, colName);
 	TEST2(err, KErrNone);
 	TEST2(colName.Compare(_L("RES")), 0);
+	//Too big column index
+    err = TheStmt.ColumnName(1323, colName);
+    TEST2(err, KErrNotFound);
+    //Negative column index 
+    err = TheStmt.ColumnName(-100, colName);
+    TEST2(err, KErrNotFound);
 	TheStmt.Close();
 	//Select constant
 	err = TheStmt.Prepare(TheDb, _L("SELECT (Id + Data) AS RES, 55.89 FROM t2"));
@@ -529,7 +535,20 @@
 		TEST2(err, KErrNone);
 		TEST2(paramName.Compare(expectedParamName), 0);
 		}
+    //Too big parameter index
+    err = TheStmt.ParamName(1323, paramName);
+    TEST2(err, KErrNotFound);
+    //Negative parameter index 
+    err = TheStmt.ParamName(-100, paramName);
+    TEST2(err, KErrNotFound);
 	TheStmt.Close();
+	
+	//SQL statement without parameters
+    err = TheStmt.Prepare(TheDb, _L("INSERT INTO T (A1, A2) VALUES (1, '1')"));
+    TEST2(err, KErrNone);
+    err = TheStmt.ParamName(0, paramName);
+    TEST2(err, KErrNotFound);
+    TheStmt.Close();
 
 	// Create insert statement, then check param names
 	err = TheStmt.Prepare(TheDb, _L("INSERT INTO T (A1, A2) VALUES (:prm1, ?)"));
--- a/persistentstorage/sql/TEST/t_sqlattach.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/TEST/t_sqlattach.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -277,7 +277,19 @@
 	
 	err = TheDb.Detach(KAttachDb4);
 	TEST(err != KErrNone);	
-	
+
+    //Detach() with zero-length logical database name
+    err = TheDb.Detach(_L(""));
+    TEST2(err, KErrBadName);  
+    
+    //Detach() with logical database name containing "bad" unicode characters (cannot be converted to UTF8)
+    TBuf<2> dbName3;
+    dbName3.SetLength(2);
+    dbName3[0] = TChar(0xD800); 
+    dbName3[1] = TChar(0xFC00); 
+    err = TheDb.Detach(dbName3);
+    TEST2(err, KSqlErrGeneral);  
+    
 	TheDb.Close();
 	}
 
--- a/persistentstorage/sql/TEST/t_sqldefect.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/TEST/t_sqldefect.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -36,7 +36,8 @@
 _LIT(KTestDatabase4, "z:\\test\\t_inc095412.db");	//Created outside this test app
 _LIT(KTestDatabase5, "c:\\test\\t_sqldefect_5.db");
 _LIT(KTestDatabase6, "c:\\test\\t_def120237.db");
-
+_LIT(KTestDatabase7, "c:\\test\\t_def144027.db");
+_LIT(KTestDatabase7Journal, "c:\\test\\t_def144027.db-journal");
 
 // This value has been found by performing the OOM test
 // with an allocation limit of 2000 and then taking a value
@@ -49,6 +50,8 @@
 void DeleteTestFiles()
 	{
 	TheDb.Close();
+	(void)TheFs.Delete(KTestDatabase7Journal);
+	(void)RSqlDatabase::Delete(KTestDatabase7);
 	(void)RSqlDatabase::Delete(KTestDatabase6);
 	(void)RSqlDatabase::Delete(KTestDatabase5);
 	(void)RSqlDatabase::Delete(KTestDatabase3);
@@ -1582,9 +1585,55 @@
     TEST2(err, 1);
     }
 
+/**
+@SYMTestCaseID          PDS-SQL-CT-4166
+@SYMTestCaseDesc        Tests for DEF144027: SQL Open returns error if the reported and actual file size are different
+@SYMTestPriority        Medium
+@SYMTestActions         1) Create a simple database and close it (this will automatically delete the journal file
+                        2) Create a 15 bytes garbage journal file which is just less than the minimum file size allowed.
+                        3) Reopen the database and checks that the open operation does not fail even thou we've used a 
+                        garbage journal file which is too small
+@SYMTestExpectedResults The RSqlDatabase::Open operation should not fail
+@SYMDEF                 DEF144027
+                        DEF144238
+*/
+void DEF144027()
+    {
+    (void) RSqlDatabase::Delete(KTestDatabase7);
+    (void) TheFs.Delete(KTestDatabase7Journal);
+    
+    TInt err = TheDb.Create(KTestDatabase7);
+    TEST2(err, KErrNone);
+    
+    err = TheDb.Exec(_L("CREATE TABLE t1(NUM INTEGER)"));
+    TEST2(err, 1);
+    
+    err = TheDb.Exec(_L("INSERT INTO t1(NUM) VALUES (1)"));
+    TEST2(err, 1);
+    
+    TheDb.Close();
+    
+    //Created a garbage 15 bytes journal file 
+    RFile file;
+    err = file.Create(TheFs, KTestDatabase7Journal, EFileWrite);
+    TEST2(err, KErrNone);
+    
+    _LIT8(KJournalJunkData, "A123456789B1234");//15 bytes
+    err = file.Write(0, KJournalJunkData);
+    TEST2(err, KErrNone);
+    
+    file.Flush();
+    file.Close();
+    
+    //Here we check the open operation does not return an error, 
+    //even though there is a journal file less than 16 bytes
+    err = TheDb.Open(KTestDatabase7);
+    TEST2(err, KErrNone);
+    TheDb.Close();
+    }
+
 void DoTestsL()
 	{
-	
 	TheTest.Start(_L(" @SYMTestCaseID:SYSLIB-SQL-CT-1763 \"SQL against a detached db\" test "));
 	SqlDetachedDbTest();	
 
@@ -1665,6 +1714,9 @@
     
     TheTest.Next(_L(" @SYMTestCaseID:PDS-SQL-CT-4157 PDEF143461 : CSqlSrvDatabase::LastErrorMessage() alignment problem"));
     PDEF143461L();
+    
+    TheTest.Next(_L(" @SYMTestCaseID:PDS-SQL-CT-4166 DEF144027: SQL Open returns error if the reported and actual file size are different"));
+    DEF144027();
 	}
 
 TInt E32Main()
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/persistentstorage/sql/TEST/t_sqlfilesrvcrash1.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -0,0 +1,255 @@
+// Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+/**
+Instructions:
+
+This is a manual test created to verify DEFXXXXX, 2 executables needs to be run to do this test
+1) t_sqlfilesrvcrash1.exe - Generate a corrupted journal file, this will cause the device to reset. 
+2) t_sqlfilesrvcrash2.exe - After the reboot, tests if SQL can handle the courrpted journal file.
+
+This test requires a non-rugged drive to store the database file and therefore will only work in hardware mode
+*/
+
+#include <e32test.h>
+#include <f32file.h>
+#include <Sqldb.h>
+
+RTest TheTest(_L("t_sqlfilesrvcrash1 test"));
+
+#if !defined __WINS__ && !defined __WINSCW__
+
+RFs TheFs;
+RSqlDatabase TheDb;
+
+const TInt KControlIoRuggedOn=2;
+const TInt KControlIoRuggedOff=3;
+const TInt KControlIoIsRugged=4;
+
+const TChar KDrvLetter = ('E');
+_LIT(KTestDir, "E:\\test\\");
+_LIT(KDbName, "E:\\test\\t_sqlfilesrvcrash.db");
+_LIT8(KConfigStr, "page_size=32768");
+_LIT(KFileSrvName, "efile.exe");
+
+///////////////////////////////////////////////////////////////////////////////////////
+//Deletes all created test files.
+void DeleteTestFiles()
+    {
+    TheDb.Close();
+    (void)RSqlDatabase::Delete(KDbName);
+    }
+
+///////////////////////////////////////////////////////////////////////////////////////
+//Test macros and functions
+void Check(TInt aValue, TInt aLine)
+    {
+    if(!aValue)
+        {
+        DeleteTestFiles();
+        RDebug::Print(_L("*** Line %d\r\n"), aLine);
+        TheTest(EFalse, aLine);
+        }
+    }
+void Check(TInt aValue, TInt aExpected, TInt aLine)
+    {
+    if(aValue != aExpected)
+        {
+        DeleteTestFiles();
+        RDebug::Print(_L("*** Expected error: %d, got: %d\r\n"), aExpected, aValue);
+        TheTest(EFalse, aLine);
+        }
+    }
+
+#define TEST(arg) ::Check((arg), __LINE__)
+#define TEST2(aValue, aExpected) ::Check(aValue, aExpected, __LINE__)
+
+///////////////////////////////////////////////////////////////////////////////////////
+//Set the drive to Rugged or non-rugged depending on the input parameter
+void SetDrive(TBool aSetToRugged)
+    {
+    TUint8 isRugged;
+    TPtr8 pRugged(&isRugged,1,1);
+
+    TInt drvNum;
+    TInt err = TheFs.CharToDrive(KDrvLetter, drvNum);
+    TEST2(err, KErrNone);
+    err=TheFs.ControlIo(drvNum,KControlIoIsRugged,pRugged);
+    TEST2(err, KErrNone);
+    
+    if(!aSetToRugged)
+        {
+        if(isRugged)
+            {
+            err=TheFs.ControlIo(drvNum,KControlIoRuggedOff);
+            TEST2(err, KErrNone);
+            }
+        }
+    else
+        {
+        if(!isRugged)
+            {
+            err=TheFs.ControlIo(drvNum,KControlIoRuggedOn);
+            TEST2(err, KErrNone);
+            }
+        }
+    }
+
+//Creates file session instance and the test directory
+void CreateTestEnv()
+    {
+    TInt err = TheFs.Connect();
+    TEST2(err, KErrNone);
+    
+    //Set the drive to non-rugged
+    TBool setDriveToRugged = EFalse;
+    SetDrive(setDriveToRugged);
+    
+    err = TheFs.MkDir(KTestDir);
+    TEST(err == KErrNone || err == KErrAlreadyExists);
+    }
+
+TInt KillProcess(const TDesC& aProcessName)
+    {
+    TFullName name;
+    //RDebug::Print(_L("Find and kill \"%S\" process.\n"), &aProcessName);
+    TBuf<64> pattern(aProcessName);
+    TInt length = pattern.Length();
+    pattern += _L("*");
+    TFindProcess procFinder(pattern);
+
+    while (procFinder.Next(name) == KErrNone)
+        {
+        if (name.Length() > length)
+            {//If found name is a string containing aProcessName string.
+            TChar c(name[length]);
+            if (c.IsAlphaDigit() ||
+                c == TChar('_') ||
+                c == TChar('-'))
+                {
+                //RDebug::Print(_L(":: Process name: \"%S\".\n"), &name);
+                continue;
+                }
+            }
+        RProcess proc;
+        if (proc.Open(name) == KErrNone)
+            {
+            RDebug::Print(_L("About to kill process \"%S\", This will force a reboot\n"), &name);
+            proc.Kill(0);
+            
+            }
+        proc.Close();
+        }
+    return KErrNone;
+    }
+
+/**
+@SYMTestCaseID          PDS-SQL-CT-4164
+@SYMTestCaseDesc        Tests for DEF144027: SQL Open returns error if the reported and actual file size are different
+                        This function creates a corrupted jorunal file on a non-rugged FAT, where the actual and 
+                        reported file size is different. This is done by killing the file server forcing the device to 
+                        reset. After the reset t_sqlfilesrvcrash2.exe is used to verify SQL can handle this corrupted
+                        journal file properly.
+@SYMTestActions         DEF144027: SQL Open returns error if the reported and actual file size are different
+@SYMTestExpectedResults Test must not fail
+@SYMTestPriority        Medium
+@SYMDEF                 DEF144027
+                        DEF144238
+*/
+void DEF144027()
+	{
+    TInt err = TheDb.Create(KDbName, &KConfigStr);
+    TEST2(err, KErrNone);
+    
+    err = TheDb.Exec(_L("CREATE TABLE t1(NUM INTEGER)"));
+    TEST2(err, 1);
+    err = TheDb.Exec(_L("CREATE TABLE t2(NUM INTEGER)"));
+    TEST2(err, 1);
+    
+    err = TheDb.Exec(_L("INSERT INTO t1(NUM) VALUES (1)"));
+    TEST2(err, 1);
+    
+    err = TheDb.Exec(_L("INSERT INTO t2(NUM) VALUES (1)"));
+    TEST2(err, 1);
+    
+    TheDb.Close();
+    
+    err = TheDb.Open(KDbName);
+    TEST2(err, KErrNone);
+    
+    err = TheDb.Exec(_L("BEGIN"));
+    TEST(err >= 0);
+    
+    err = TheDb.Exec(_L("CREATE TABLE t3(NUM INTEGER)"));
+    TEST2(err, KErrNone);
+    
+    err = TheDb.Exec(_L("INSERT INTO t1(NUM) VALUES (1)"));
+    TEST2(err, 1);
+    
+    err = TheDb.Exec(_L("INSERT INTO t2(NUM) VALUES (1)"));
+    TEST2(err, 1);
+    
+    err = TheDb.Exec(_L("INSERT INTO t3(NUM) VALUES (1)"));
+    TEST2(err, 1);
+    
+   
+    //Here the transaction is committed but the database is not close
+    //this makes sure that the journal is truncated but not deleted 
+    err = TheDb.Exec(_L("COMMIT"));
+    TEST(err >= 0);
+    
+    //Reset the drive to rugged
+    TBool setDriveToRugged = ETrue;
+    SetDrive(setDriveToRugged);
+    
+    //When the file server is killed, the file size meta data will not be updated
+    KillProcess(KFileSrvName);  
+	}
+
+void DoTests()
+    {    
+    TheTest.Start(_L(" @SYMTestCaseID:PDS-SQL-CT-4164 DEF144027: SQL Open returns error if the reported and actual file size are different"));
+    DEF144027();    
+    }
+#endif //#if !defined __WINS__ && !defined __WINSCW__
+
+TInt E32Main()
+    {
+    TheTest.Title();
+    
+    CTrapCleanup* tc = CTrapCleanup::New();
+    
+    __UHEAP_MARK;
+    
+#if !defined __WINS__ && !defined __WINSCW__
+    CreateTestEnv();
+    DeleteTestFiles();
+    DoTests();
+    TheFs.Close();
+    TheTest.End();
+#else
+    TheTest.Start(_L("This test works only works on hardware!"));
+    TheTest.End();
+#endif  
+ 
+    __UHEAP_MARKEND;
+    
+    TheTest.Close();
+    
+    delete tc;
+
+    User::Heap().Check();
+    return KErrNone;
+    }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/persistentstorage/sql/TEST/t_sqlfilesrvcrash2.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -0,0 +1,152 @@
+// Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+/**
+Instructions:
+
+This is a manual test created to verify DEFXXXXX, 2 executables needs to be run to do this test
+1) t_sqlfilesrvcrash1.exe - Generate a corrupted journal file, this will cause the device to reset. 
+2) t_sqlfilesrvcrash2.exe - After the reboot, tests if SQL can handle the courrpted journal file.
+
+This test requires a non-rugged drive to store the database file and therefore will only work in hardware mode
+*/
+
+#include <e32test.h>
+#include <f32file.h>
+#include <Sqldb.h>
+
+RTest TheTest(_L("t_sqlfilesrvcrash2 test"));
+
+#if !defined __WINS__ && !defined __WINSCW__
+
+RFs TheFs;
+RSqlDatabase TheDb;
+
+_LIT(KDbName, "E:\\test\\t_sqlfilesrvcrash.db");
+_LIT(KJournalName,  "E:\\test\t_sqlfilesrvcrash.db-journal");
+///////////////////////////////////////////////////////////////////////////////////////
+//Deletes all created test files.
+void DeleteTestFiles()
+    {
+    TheDb.Close();
+    (void)RSqlDatabase::Delete(KDbName);
+    }
+
+///////////////////////////////////////////////////////////////////////////////////////
+//Test macros and functions
+void Check(TInt aValue, TInt aLine)
+    {
+    if(!aValue)
+        {
+        RDebug::Print(_L("*** Line %d\r\n"), aLine);
+        TheTest(EFalse, aLine);
+        }
+    }
+void Check(TInt aValue, TInt aExpected, TInt aLine)
+    {
+    if(aValue != aExpected)
+        {
+        RDebug::Print(_L("*** Expected error: %d, got: %d\r\n"), aExpected, aValue);
+        TheTest(EFalse, aLine);
+        }
+    }
+
+#define TEST(arg) ::Check((arg), __LINE__)
+#define TEST2(aValue, aExpected) ::Check(aValue, aExpected, __LINE__)
+///////////////////////////////////////////////////////////////////////////////////////
+//Creates file session instance and the test directory
+void CreateTestEnv()
+    {
+    TInt  err = TheFs.Connect();
+    TEST2(err, KErrNone);
+    
+    RFile file;
+    err = file.Open(TheFs, KJournalName, EFileRead);
+    TEST2(err, KErrNone);
+    
+    TInt size;
+    err = file.Size(size);
+    TEST2(err, KErrNone);
+    TEST(size > SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT);
+    file.Close();
+    }
+///////////////////////////////////////////////////////////////////////////////////////
+/**
+@SYMTestCaseID          PDS-SQL-CT-4165
+@SYMTestCaseDesc        Tests for DEF144027: SQL Open returns error if the reported and actual file size are different
+                        Requires a corrupted journal file to be created using t_sqlfilesrvcrash1.exe before running 
+                        this test. If a corrupted journal file exists then check that the opening the database does not
+                        return an error.
+@SYMTestActions         DEF144027: SQL Open returns error if the reported and actual file size are different
+@SYMTestExpectedResults The RSqlDatabase::Open operation should not fail
+@SYMTestPriority        Medium
+@SYMDEF                 DEF144027
+                        DEF144238
+*/
+void DEF144027()
+	{
+    TInt err = TheDb.Open(KDbName);
+    TEST2(err, KErrNone);
+    
+    //Lets perform a simple operation to make sure it works
+    err = TheDb.Exec(_L("BEGIN"));
+    TEST(err >= 0);
+    
+    err = TheDb.Exec(_L("INSERT INTO t1(NUM) VALUES (55)"));
+    TEST2(err, 1);
+    
+    err = TheDb.Exec(_L("INSERT INTO t2(NUM) VALUES (55)"));
+    TEST2(err, 1);
+        
+    err = TheDb.Exec(_L("COMMIT"));
+    TEST(err >= 0);
+        
+    TheDb.Close();
+	}
+
+void DoTests()
+    {    
+    TheTest.Start(_L(" @SYMTestCaseID:PDS-SQL-CT-4165 DEF144027: SQL Open returns error if the reported and actual file size are different"));
+    DEF144027();    
+    }
+#endif //#if !defined __WINS__ && !defined __WINSCW__
+
+TInt E32Main()
+    {
+    TheTest.Title();
+    
+    CTrapCleanup* tc = CTrapCleanup::New();
+    
+    __UHEAP_MARK;
+    
+#if !defined __WINS__ && !defined __WINSCW__
+    DoTests();
+    DeleteTestFiles();
+    TheFs.Close();
+    TheTest.End();
+#else
+    TheTest.Start(_L("This test works only works on hardware!"));
+    TheTest.End();
+#endif  
+ 
+    __UHEAP_MARKEND;
+    
+    TheTest.Close();
+    
+    delete tc;
+
+    User::Heap().Check();
+    return KErrNone;
+    }
--- a/persistentstorage/sql/TEST/t_sqlfserr.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/TEST/t_sqlfserr.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -27,6 +27,9 @@
 RTest TheTest(_L("t_sqlfserr test"));
 _LIT(KTestDir, "c:\\test\\");
 _LIT(KTestDbName, "c:\\test\\t_fserr.db");
+_LIT(KPrivateTestDbName, "c:\\private\\212A2C27\\t_fserr2.db");
+_LIT(KSecureTestDbName, "c:[212A2C27]t_fserr3.db");
+
 TFileName TheRmvMediaDbFileName;//The name of the file used for tests on a removable media
 RFs TheFs;
 RSqlDatabase TheDb;
@@ -55,6 +58,8 @@
 void DestroyTestEnv()
 	{
 	TheDb.Close();
+    (void)RSqlDatabase::Delete(KSecureTestDbName);
+    (void)RSqlDatabase::Delete(KPrivateTestDbName);
 	(void)RSqlDatabase::Delete(KTestDbName);
 	(void)RSqlDatabase::Delete(TheRmvMediaDbFileName);
 	TheFs.Close();
@@ -117,11 +122,11 @@
 	sqlite3SymbianLibInit();
 	}
 
-TBool CheckRecord(TInt aId, const TDesC& aExpectedName, TBool aOpenDb = ETrue)
+TBool CheckRecord(const TDesC& aDbName, TInt aId, const TDesC& aExpectedName, TBool aOpenDb = ETrue)
 	{
 	if(aOpenDb)
 		{
-		TEST2(TheDb.Open(KTestDbName), KErrNone);
+		TEST2(TheDb.Open(aDbName), KErrNone);
 		}
 	TBuf<64> sql;
 	sql.Copy(_L("SELECT Name FROM A WHERE Id="));
@@ -179,13 +184,13 @@
 				TheDb.Close();//close the database to recover from the last error
 				//check the database content - all bets are off in a case of an I/O error. 
 				//The existing record might have been updated.
-				TEST(CheckRecord(1, _L("Name")) || CheckRecord(1, _L("Name2")));
+				TEST(CheckRecord(KTestDbName, 1, _L("Name")) || CheckRecord(KTestDbName, 1, _L("Name2")));
 				}
 			else
 				{
 				TEST2(err, 1);
 				//check the database content has been modified by the operation. 
-				TEST(CheckRecord(1, _L("Name2"), EFalse));
+				TEST(CheckRecord(KTestDbName, 1, _L("Name2"), EFalse));
 				TheDb.Close();
 				}
 			}
@@ -193,7 +198,7 @@
 	(void)TheFs.SetErrorCondition(KErrNone);
 	TEST2(err, 1);
 	//check the database content (transaction durability). 
-	TEST(CheckRecord(1, _L("Name2")));
+	TEST(CheckRecord(KTestDbName, 1, _L("Name2")));
 	err = RSqlDatabase::Delete(KTestDbName);
 	TEST2(err, KErrNone);
 	TheTest.Printf(_L("\r\n"));
@@ -245,13 +250,13 @@
 				TheDb.Close();//close the database to recover from the last error
 				//check the database content - all bets are off in a case of an I/O error. 
 				//The existing record might have been updated.
-				TEST(CheckRecord(1, _L("Name")) || CheckRecord(1, _L("Name2")));
+				TEST(CheckRecord(KTestDbName, 1, _L("Name")) || CheckRecord(KTestDbName, 1, _L("Name2")));
 				}
 			else
 				{
 				TEST2(err, 1);
 				//check the database content has been modified by the operation. 
-				TEST(CheckRecord(1, _L("Name2"), EFalse));
+				TEST(CheckRecord(KTestDbName, 1, _L("Name2"), EFalse));
 				TheDb.Close();
 				}
 			}
@@ -259,12 +264,26 @@
 	(void)TheFs.SetErrorCondition(KErrNone);
 	TEST2(err, 1);
 	//check the database content has been modified by the operation. 
-	TEST(CheckRecord(1, _L("Name2")));
+	TEST(CheckRecord(KTestDbName, 1, _L("Name2")));
 	err = RSqlDatabase::Delete(KTestDbName);
 	TEST2(err, KErrNone);
 	TheTest.Printf(_L("\r\n"));
 	}
 
+void CreateTestSecurityPolicy(RSqlSecurityPolicy& aSecurityPolicy)
+    {
+    TSecurityPolicy alwaysPassPolicy(TSecurityPolicy::EAlwaysPass);
+    TInt err = aSecurityPolicy.Create(alwaysPassPolicy);
+    TEST2(err, KErrNone);
+
+    err = aSecurityPolicy.SetDbPolicy(RSqlSecurityPolicy::ESchemaPolicy, alwaysPassPolicy);
+    TEST2(err, KErrNone);
+    err = aSecurityPolicy.SetDbPolicy(RSqlSecurityPolicy::EWritePolicy, alwaysPassPolicy);
+    TEST2(err, KErrNone);
+    err = aSecurityPolicy.SetDbPolicy(RSqlSecurityPolicy::EReadPolicy, alwaysPassPolicy);
+    TEST2(err, KErrNone);
+    }
+
 /**
 @SYMTestCaseID			SYSLIB-SQL-UT-3421
 @SYMTestCaseDesc		Test for DEF103859 "SQLITE panic, _DEBUG mode, persistent file I/O error simulation".
@@ -279,46 +298,63 @@
 */
 void OpenDatabaseTest()
 	{
-	(void)RSqlDatabase::Delete(KTestDbName);
-	TInt err = TheDb.Create(KTestDbName);
-	TEST2(err, KErrNone);
-	err = TheDb.Exec(_L("CREATE TABLE A(Id INTEGER,Name TEXT)"));
-	TEST(err >= 0);
-	err = TheDb.Exec(_L("INSERT INTO A(Id,Name) VALUES(1,'Name')"));
-	TEST2(err, 1);
-	TheDb.Close();
-
-	err = KErrNotFound;
-	for(TInt cnt=1;err<KErrNone;++cnt)
-		{		
-		TheTest.Printf(_L("%d \r"), cnt);		
-		for (TInt fsError=KErrNotFound;fsError>=KErrDied;--fsError)
-			{
-			(void)TheFs.SetErrorCondition(fsError, cnt);
-			err = TheDb.Open(KTestDbName);
-			(void)TheFs.SetErrorCondition(KErrNone);
-			if(err != KErrNone)
-				{
-				TheDb.Close();//close the database to recover from the last error
-				//check the database content is still the same as before the "open" call
-				TEST(CheckRecord(1, _L("Name")));
-				}
-			else
-				{
-				TEST2(err, KErrNone);
-				//check the database content is still the same as before the operation, without closing the database
-				TEST(CheckRecord(1, _L("Name"), EFalse));
-				TheDb.Close();
-				}
-			}
-		}
-	(void)TheFs.SetErrorCondition(KErrNone);
-	TEST2(err, KErrNone);
-	//check the database content is the same as before the operation, after reopening the database.
-	TEST(CheckRecord(1, _L("Name")));
-	err = RSqlDatabase::Delete(KTestDbName);
-	TEST2(err, KErrNone);
-	TheTest.Printf(_L("\r\n"));
+    TPtrC dbName[] = {KTestDbName(), KPrivateTestDbName(), KSecureTestDbName()};
+    const TInt KDbNameCnt = sizeof(dbName) / sizeof(dbName[0]);
+    for(TInt k=0;k<KDbNameCnt;++k)
+        {	
+        TheTest.Printf(_L("Database: \"%S\"\r\n"), &dbName[k]);       
+        (void)RSqlDatabase::Delete(dbName[k]);
+        TInt err = KErrGeneral;
+        if(k == (KDbNameCnt - 1))
+            {
+            RSqlSecurityPolicy policy;
+            CreateTestSecurityPolicy(policy);
+            err = TheDb.Create(dbName[k], policy);
+            policy.Close();
+            }
+        else
+            {
+            err = TheDb.Create(dbName[k]);
+            }
+        TEST2(err, KErrNone);
+        err = TheDb.Exec(_L("CREATE TABLE A(Id INTEGER,Name TEXT)"));
+        TEST(err >= 0);
+        err = TheDb.Exec(_L("INSERT INTO A(Id,Name) VALUES(1,'Name')"));
+        TEST2(err, 1);
+        TheDb.Close();
+    
+        err = KErrNotFound;
+        for(TInt cnt=1;err<KErrNone;++cnt)
+            {		
+            TheTest.Printf(_L("%d \r"), cnt);		
+            for (TInt fsError=KErrNotFound;fsError>=KErrDied;--fsError)
+                {
+                (void)TheFs.SetErrorCondition(fsError, cnt);
+                err = TheDb.Open(dbName[k]);
+                (void)TheFs.SetErrorCondition(KErrNone);
+                if(err != KErrNone)
+                    {
+                    TheDb.Close();//close the database to recover from the last error
+                    //check the database content is still the same as before the "open" call
+                    TEST(CheckRecord(dbName[k], 1, _L("Name")));
+                    }
+                else
+                    {
+                    TEST2(err, KErrNone);
+                    //check the database content is still the same as before the operation, without closing the database
+                    TEST(CheckRecord(dbName[k], 1, _L("Name"), EFalse));
+                    TheDb.Close();
+                    }
+                }
+            }
+        (void)TheFs.SetErrorCondition(KErrNone);
+        TEST2(err, KErrNone);
+        //check the database content is the same as before the operation, after reopening the database.
+        TEST(CheckRecord(dbName[k], 1, _L("Name")));
+        err = RSqlDatabase::Delete(dbName[k]);
+        TEST2(err, KErrNone);
+        TheTest.Printf(_L("\r\n"));
+        }
 	}
 
 /**
@@ -335,32 +371,45 @@
 */
 void CreateDatabaseTest()
 	{
-	TInt err = -1;
-	for(TInt cnt=1;err<KErrNone;++cnt)
-		{		
-		TheTest.Printf(_L("%d \r"), cnt);		
-		for (TInt fsError=KErrNotFound;fsError>=KErrDied;--fsError)
-			{
-			//Ideally, the database should be deleted by the SQL server, if RSqlDatabase::Create() fails.
-			//But SetErrorCondition() makes the error persistent, so the SQL server will fail to delete the file.
-			//This is the reason, RSqlDatabase::Delete()to be used, before simulating file I/O error.
-			(void)RSqlDatabase::Delete(KTestDbName);
-			(void)TheFs.SetErrorCondition(fsError, cnt);
-			err = TheDb.Create(KTestDbName);
-			(void)TheFs.SetErrorCondition(KErrNone);
-			TheDb.Close();
-			//If err != KErrNone, the database file should have been already deleted by the server and here is 
-			//the place to check that. But since the file I/O failure simulation makes the file I/O error 
-			//persistent, the file cannot be deleted by the server, because the "file delete" operation also fails.
-			}
-		}
-	(void)TheFs.SetErrorCondition(KErrNone);
-	TheDb.Close();
-	TEST2(err, KErrNone);
-	TEST(FileExists(KTestDbName));
-	err = RSqlDatabase::Delete(KTestDbName);
-	TEST2(err, KErrNone);
-	TheTest.Printf(_L("\r\n"));
+	RSqlSecurityPolicy policy;
+	CreateTestSecurityPolicy(policy);
+	
+	TPtrC dbName[] = {KTestDbName(), KPrivateTestDbName(), KSecureTestDbName()};
+	const TInt KDbNameCnt = sizeof(dbName) / sizeof(dbName[0]);
+	for(TInt k=0;k<KDbNameCnt;++k)
+	    {
+        TheTest.Printf(_L("Database: \"%S\"\r\n"), &dbName[k]);       
+        TInt err = -1;
+        for(TInt cnt=1;err<KErrNone;++cnt)
+            {		
+            TheTest.Printf(_L("%d \r"), cnt);		
+            for (TInt fsError=KErrNotFound;fsError>=KErrDied;--fsError)
+                {
+                //Ideally, the database should be deleted by the SQL server, if RSqlDatabase::Create() fails.
+                //But SetErrorCondition() makes the error persistent, so the SQL server will fail to delete the file.
+                //This is the reason, RSqlDatabase::Delete()to be used, before simulating file I/O error.
+                (void)RSqlDatabase::Delete(dbName[k]);
+                (void)TheFs.SetErrorCondition(fsError, cnt);
+                err = (k == (KDbNameCnt - 1)) ? TheDb.Create(dbName[k], policy) : TheDb.Create(dbName[k]);
+                (void)TheFs.SetErrorCondition(KErrNone);
+                TheDb.Close();
+                //If err != KErrNone, the database file should have been already deleted by the server and here is 
+                //the place to check that. But since the file I/O failure simulation makes the file I/O error 
+                //persistent, the file cannot be deleted by the server, because the "file delete" operation also fails.
+                }
+            }
+        (void)TheFs.SetErrorCondition(KErrNone);
+        TheDb.Close();
+        TEST2(err, KErrNone);
+        if( k != (KDbNameCnt - 1))
+            {
+            TEST(FileExists(dbName[k]));
+            }
+        err = RSqlDatabase::Delete(dbName[k]);
+        TEST2(err, KErrNone);
+        TheTest.Printf(_L("\r\n"));
+	    }
+	policy.Close();
 	}
 
 /**
@@ -415,13 +464,13 @@
 		stmt.Close();
 		TheDb.Close();
 		//check the database content is the same as before the operation
-		TEST(CheckRecord(1, _L("Name")));
+		TEST(CheckRecord(KTestDbName, 1, _L("Name")));
 		}
 	(void)TheFs.SetErrorCondition(KErrNone);
 	TEST(err >= 0);
 	TheDb.Close();
 	//check the database content is the same as before the operation, after reopening the database.
-	TEST(CheckRecord(1, _L("Name")));
+	TEST(CheckRecord(KTestDbName, 1, _L("Name")));
 	err = RSqlDatabase::Delete(KTestDbName);
 	TEST2(err, KErrNone);
 	TheTest.Printf(_L("\r\n"));
@@ -477,22 +526,22 @@
 			{
 			TheDb.Close();//close the database to recover from the last error
 			//check that the database contains the "name" record that has been inserted before the file I/O failure test.
-			TEST(CheckRecord(1, _L("Name")));
+			TEST(CheckRecord(KTestDbName, 1, _L("Name")));
 			}
 		else
 			{
 			TEST2(err, 1);
 			//check the database content has been modified by the operation, without closing the database.
-			TEST(CheckRecord(1, _L("Name"), EFalse));
-			TEST(CheckRecord(2, _L("Name2"), EFalse));
+			TEST(CheckRecord(KTestDbName, 1, _L("Name"), EFalse));
+			TEST(CheckRecord(KTestDbName, 2, _L("Name2"), EFalse));
 			TheDb.Close();
 			}
 		}
 	(void)TheFs.SetErrorCondition(KErrNone);
 	TEST2(err, 1);
 	//check the database content (transaction durability).
-	TEST(CheckRecord(1, _L("Name")));
-	TEST(CheckRecord(2, _L("Name2")));
+	TEST(CheckRecord(KTestDbName, 1, _L("Name")));
+	TEST(CheckRecord(KTestDbName, 2, _L("Name2")));
 	(void)RSqlDatabase::Delete(KTestDbName);
 	TheTest.Printf(_L("\r\n"));
 	}
--- a/persistentstorage/sql/TEST/t_sqlood.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/TEST/t_sqlood.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -127,6 +127,10 @@
 	TEST2(err, KErrNone);
 
 	err = TheFs.MkDir(KTestDir);
+	if(err != KErrNone)
+	    {
+	    RDebug::Print(_L("*** CreateTestEnv(), RFs::MkDir(), err=%d\r\n"), err);
+	    }
 	TEST(err == KErrNone || err == KErrAlreadyExists);
 	}
 
--- a/persistentstorage/sql/TEST/t_sqloslayer.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/TEST/t_sqloslayer.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -41,6 +41,8 @@
 const char* KTestFile1Z = "c:\\test\\t_sqloslayer.bin";
 const char* KTestFile2Z = "z:\\test\\TestDb1.db";
 const char* KTestFile3Z = "c:\\test\\t_sqloslayer.db";
+_LIT(KPrivateDir, "c:\\private\\21F12127\\");
+const char* KTestFile4Z = "c:\\test\\t_sqloslayer2.db";
 
 //In order to be able to compile the test, the following variables are defined (used inside the OS porting layer, when _SQLPROFILER macro is defined)
 #ifdef _SQLPROFILER
@@ -91,6 +93,63 @@
 
 ///////////////////////////////////////////////////////////////////////////////////////
 
+static TInt TheProcessHandleCount = 0;
+static TInt TheThreadHandleCount = 0;
+static TInt TheAllocatedCellsCount = 0;
+
+#ifdef _DEBUG
+static const TInt KBurstRate = 20;
+#endif
+
+static void MarkHandles()
+    {
+    RThread().HandleCount(TheProcessHandleCount, TheThreadHandleCount);
+    }
+
+static void MarkAllocatedCells()
+    {
+    TheAllocatedCellsCount = User::CountAllocCells();
+    }
+
+static void CheckAllocatedCells()
+    {
+    TInt allocatedCellsCount = User::CountAllocCells();
+    TEST2(allocatedCellsCount, TheAllocatedCellsCount);
+    }
+
+static void CheckHandles()
+    {
+    TInt endProcessHandleCount;
+    TInt endThreadHandleCount;
+    
+    RThread().HandleCount(endProcessHandleCount, endThreadHandleCount);
+
+    TEST2(TheProcessHandleCount, endProcessHandleCount);
+    TEST2(TheThreadHandleCount, endThreadHandleCount);
+    }
+
+static void OomPreStep(TInt
+#ifdef _DEBUG        
+    aFailingAllocationNo
+#endif
+                      )
+    {
+    MarkHandles();
+    MarkAllocatedCells();
+    __UHEAP_MARK;
+    __UHEAP_SETBURSTFAIL(RAllocator::EBurstFailNext, aFailingAllocationNo, KBurstRate);
+    }
+
+static void OomPostStep()
+    {
+    __UHEAP_RESET;
+    __UHEAP_MARKEND;
+    CheckAllocatedCells();
+    CheckHandles();
+    }
+
+///////////////////////////////////////////////////////////////////////////////////////
+
 void TestEnvInit()
     {
 	TInt err = TheFs.Connect();
@@ -405,35 +464,14 @@
 	TInt err = KErrNoMemory;
 	while(err == KErrNoMemory)
 		{
-		TInt processHandleCnt = 0;
-		TInt threadHandleCnt = 0;
-		RThread().HandleCount(processHandleCnt, threadHandleCnt);
-		TInt allocCellsCnt = User::CountAllocCells();
-		
-		__UHEAP_MARK;
-		
-		__UHEAP_SETBURSTFAIL(RHeap::EDeterministic, ++failingAllocNum, 10);
-		
+		OomPreStep(++failingAllocNum);
 		err = sqlite3SymbianLibInit();
-		
-		__UHEAP_SETBURSTFAIL(RHeap::ENone, 0, 0);
-
-		if(err != KErrNoMemory)
-			{
-			TEST2(err, KErrNone);
-			sqlite3SymbianLibFinalize();
-			}
-
-		__UHEAP_MARKEND;
-
-		TInt processHandleCnt2 = 0;
-		TInt threadHandleCnt2 = 0;
-		RThread().HandleCount(processHandleCnt2, threadHandleCnt2);
-		TEST2(processHandleCnt2, processHandleCnt);
-		TEST2(threadHandleCnt2, threadHandleCnt);
-
-		TInt allocCellsCnt2 = User::CountAllocCells();
-		TEST2(allocCellsCnt2, allocCellsCnt);
+        sqlite3SymbianLibFinalize();
+        OomPostStep();
+        if(err != KErrNoMemory)
+            {
+            TEST2(err, KErrNone);
+            }
 		}
 	TEST2(err, KErrNone);
 	TheTest.Printf(_L("=== sqlite3SymbianLibInit() OOM test succeeded at allcoation %d\r\n"), failingAllocNum);
@@ -585,6 +623,94 @@
 	User::Free(osFile);
 	}
 
+void VfsOpenTempFileOomTest()
+    {
+    //Delete all temp files in this test private data cage.
+    CFileMan* fm = NULL;
+    TRAPD(err, fm = CFileMan::NewL(TheFs));
+    TEST2(err, KErrNone);
+    TBuf<50> path;
+    path.Copy(KPrivateDir);
+    path.Append(_L("*.$$$"));
+    err = fm->Delete(path);
+    TEST(err == KErrNone || err == KErrNotFound);
+    
+    sqlite3_vfs* vfs = sqlite3_vfs_find(NULL);
+    TEST(vfs != NULL);
+
+    sqlite3_file* osFile = (sqlite3_file*)User::Alloc(vfs->szOsFile);
+    TEST(osFile != NULL);
+    
+    TheTest.Printf(_L("Iteration: "));
+    TInt failingAllocNum = 0;
+    err = SQLITE_IOERR_NOMEM;
+    while(err == SQLITE_IOERR_NOMEM)
+        {
+        ++failingAllocNum;
+        TheTest.Printf(_L("%d "), failingAllocNum);
+        OomPreStep(failingAllocNum);
+        int outFlags = 0;
+        err = sqlite3OsOpen(vfs, NULL, osFile, SQLITE_OPEN_READWRITE, &outFlags);
+        if(err == SQLITE_OK)
+            {
+            err = sqlite3OsClose(osFile);
+            }
+        OomPostStep();
+        if(err != SQLITE_OK)
+            {
+            TEST2(err, SQLITE_IOERR_NOMEM);
+            }
+        //If the iteration has failed, then no temp file should exist in the test private data cage.
+        //If the iteration has succeeded, then sqlite3OsClose() should have deleted the temp file.
+        TInt err2 = fm->Delete(path);
+        TEST2(err2, KErrNotFound);
+        }
+    TEST2(err, SQLITE_OK);
+    TheTest.Printf(_L("\r\n=== TVfs::Open(<temp file>) OOM test succeeded at allcoation %d\r\n"), failingAllocNum);
+    
+    User::Free(osFile);
+    delete fm;
+    }
+
+void VfsCreateDeleteOnCloseFileOomTest()
+    {
+    sqlite3_vfs* vfs = sqlite3_vfs_find(NULL);
+    TEST(vfs != NULL);
+
+    sqlite3_file* osFile = (sqlite3_file*)User::Alloc(vfs->szOsFile);
+    TEST(osFile != NULL);
+    
+    TheTest.Printf(_L("Iteration: "));
+    TInt failingAllocNum = 0;
+    TInt err = SQLITE_IOERR_NOMEM;
+    while(err == SQLITE_IOERR_NOMEM)
+        {
+        ++failingAllocNum;
+        TheTest.Printf(_L("%d "), failingAllocNum);
+        OomPreStep(failingAllocNum);
+        int outFlags = 0;
+        err = sqlite3OsOpen(vfs, KTestFile4Z, osFile, SQLITE_OPEN_CREATE | SQLITE_OPEN_DELETEONCLOSE, &outFlags);
+        if(err == SQLITE_OK)
+            {
+            err = sqlite3OsClose(osFile);
+            }
+        OomPostStep();
+        if(err != SQLITE_OK)
+            {
+            TEST2(err, SQLITE_IOERR_NOMEM);
+            }
+        //Whether the iteration has failed or succeeded, the file should not exist.
+        TPtrC8 ptrname((const TUint8*)KTestFile4Z);
+        TBuf<50> fname;
+        fname.Copy(ptrname);
+        TInt err2 = TheFs.Delete(fname);
+        TEST2(err2, KErrNotFound);
+        }
+    TEST2(err, SQLITE_OK);
+    TheTest.Printf(_L("\r\n=== TVfs::Open(<delete on close file>) OOM test succeeded at allcoation %d\r\n"), failingAllocNum);
+    User::Free(osFile);
+    }
+
 /**
 @SYMTestCaseID			SYSLIB-SQL-CT-1650
 @SYMTestCaseDesc		SQL, OS porting layer tests.
@@ -612,6 +738,10 @@
 	ProfilerDisabledTest();
 	TheTest.Printf(_L("OS porting layer test - negative tests\r\n"));
 	NegativeTest();
+    TheTest.Printf(_L("TVfs::Open(<temp file>) OOM test\r\n"));
+    VfsOpenTempFileOomTest();
+    TheTest.Printf(_L("TVfs::Open(<'delete on close' file>) OOM test\r\n"));
+    VfsCreateDeleteOnCloseFileOomTest();
 	}
 
 TInt E32Main()
@@ -619,6 +749,7 @@
 	TheTest.Title();
 	
 	CTrapCleanup* tc = CTrapCleanup::New();
+	TheTest(tc != NULL);
 	
 	__UHEAP_MARK;
 	
--- a/persistentstorage/sql/TEST/t_sqlprivcage.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/TEST/t_sqlprivcage.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -239,6 +239,16 @@
 	//...create as a non-secure database
 	err = db.Create(_L("C:[21212122]BBDb2.db"));
 	TEST2(err, KErrArgument);//secure database name, no security policy
+    //Very long private database name
+    err = db.Create(_L("c:\\private\\21212124\\hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh.db"));
+    TEST2(err, KErrBadName);
+    //Zero length private database name
+    err = db.Create(_L(""));
+    TEST2(err, KErrBadName);
+    //Private database + very long config string
+    _LIT8(KVeryLongConfig, "jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj");
+    err = db.Create(KTestDb2, &KVeryLongConfig);
+    TEST2(err, KErrArgument);
 	//...create as a secure database
 	RSqlSecurityPolicy dbSecurity;
 	TSecurityPolicy policy(TSecurityPolicy::EAlwaysPass);
--- a/persistentstorage/sql/TEST/t_sqlsecurity2.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/TEST/t_sqlsecurity2.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -96,6 +96,14 @@
 	//Attempt to modify the database schema
 	err = TheDb.Exec(_L("CREATE TABLE C(FFF TEXT)"));
 	TEST2(err, KErrPermissionDenied);
+    err = TheDb.Exec(_L("CREATE TEMP TABLE TBL100(COL1 INTEGER)"));
+    TEST(err >= 0);
+    err = TheDb.Exec(_L("CREATE INDEX IDX100 ON TBL100(COL1)"));
+    TEST(err >= 0);
+    err = TheDb.Exec(_L("DROP INDEX IDX100"));
+    TEST(err >= 0);
+    err = TheDb.Exec(_L("DROP TABLE TBL100"));
+    TEST(err >= 0);
 	//Attempt to update the user data
 	err = TheDb.Exec(_L("UPDATE A SET F1 = 11 WHERE F1 = 1"));
 	TEST2(err, KErrPermissionDenied);
--- a/persistentstorage/sql/TEST/t_sqlsecurity3.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/TEST/t_sqlsecurity3.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -104,6 +104,16 @@
 	//Attempt to modify the database schema
 	err = TheDb.Exec(_L("CREATE TABLE C(FFF TEXT)"));
 	TEST2(err, KErrPermissionDenied);
+    err = TheDb.Exec(_L("CREATE TRIGGER upd_a_b1 UPDATE OF B1 ON A BEGIN UPDATE B SET F3 = 'AAAA' WHERE F2 = A.F1; END;"));
+    TEST2(err, KErrPermissionDenied);
+    err = TheDb.Exec(_L("CREATE TEMP TRIGGER upd_a_b1 UPDATE OF B1 ON A BEGIN UPDATE B SET F3 = 'AAAA' WHERE F2 = A.F1; END;"));
+    TEST2(err, KErrPermissionDenied);//Temp trigger which attempts to update one of the tables.
+    err = TheDb.Exec(_L("CREATE VIEW V1 AS SELECT * FROM A"));
+    TEST2(err, KErrPermissionDenied);
+    err = TheDb.Exec(_L("CREATE TEMP VIEW V1 AS SELECT * FROM A"));
+    TEST(err >= 0);
+    err = TheDb.Exec(_L("DROP VIEW V1"));
+    TEST(err >= 0);
 	//Attempt to update the user data (but it includes a READ operation)
 	err = TheDb.Exec(_L("UPDATE A SET F1 = 11 WHERE F1 = 1"));
 	TEST2(err, KErrPermissionDenied);
--- a/persistentstorage/sql/TEST/t_sqlsecurity4.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/TEST/t_sqlsecurity4.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -41,6 +41,7 @@
 RTest TheTest(_L("t_sqlsecurity4 test"));
 
 _LIT(KTestDbName, "c:[21212125]t_ab.db");
+_LIT(KTestDbName2, "c:\\test\\t_sqlsecurity4_2.db");
 
 ///////////////////////////////////////////////////////////////////////////////////////
 //Restore original test database function
@@ -85,6 +86,65 @@
 
 ///////////////////////////////////////////////////////////////////////////////////////
 
+//This functnion is called while there is an open secure connection.
+//The function will create a new, non-secure connection and check that the non-secure database schema can be modified,
+//while there is another alive, secure database connection.
+void NonSecureDbTest()
+    {
+    (void)RSqlDatabase::Delete(KTestDbName2);
+    RSqlDatabase db;
+    TInt err = db.Create(KTestDbName2);
+    TEST2(err, KErrNone);
+    
+    err = db.Exec(_L("CREATE TABLE A(I1 INTEGER, I2 INTEGER)"));
+    TEST(err >= 0);
+    err = db.Exec(_L("CREATE TEMP TABLE B(I1 INTEGER, I2 INTEGER)"));
+    TEST(err >= 0);
+
+    //"CREATE VIRTUAL TABLE" statement not supported
+    err = db.Exec(_L("CREATE VIRTUAL TABLE V1 USING FTS3(ColOne TEXT, ColTwo DATETIME)"));
+    TPtrC msg = db.LastErrorMessage();
+    TheTest.Printf(_L("*** \"CREATE VIRTUAL TABLE\" expected failure, msg=\"%S\", err=%d\r\n"), &msg, err);
+    TEST(err != KErrNone);
+    
+    err = db.Exec(_L("CREATE TRIGGER T1 AFTER INSERT ON A BEGIN INSERT INTO B VALUES(new.I1, new.I2); END;"));
+    TEST(err >= 0);
+    err = db.Exec(_L("DROP TRIGGER T1"));
+    TEST(err >= 0);
+    err = db.Exec(_L("CREATE TEMP TRIGGER T2 AFTER UPDATE OF I1 ON A BEGIN UPDATE B SET I1 = new.I1; END;"));
+    TEST(err >= 0);
+    err = db.Exec(_L("DROP TRIGGER T2"));
+    TEST(err >= 0);
+
+    err = db.Exec(_L("CREATE VIEW V1 AS SELECT * FROM A"));
+    TEST(err >= 0);
+    err = db.Exec(_L("DROP VIEW V1"));
+    TEST(err >= 0);
+    err = db.Exec(_L("CREATE TEMP VIEW V2 AS SELECT * FROM A"));
+    TEST(err >= 0);
+    err = db.Exec(_L("DROP VIEW V2"));
+    TEST(err >= 0);
+
+    err = db.Exec(_L("CREATE INDEX Idx1 ON A(I1)"));
+    TEST(err >= 0);
+    err = db.Exec(_L("ANALYZE A"));
+    TEST(err >= 0);
+    err = db.Exec(_L("DROP INDEX Idx1"));
+    TEST(err >= 0);
+    err = db.Exec(_L("CREATE INDEX Idx2 ON B(I1)"));
+    TEST(err >= 0);
+    err = db.Exec(_L("DROP INDEX Idx2"));
+    TEST(err >= 0);
+        
+    err = db.Exec(_L("DROP TABLE B"));
+    TEST(err >= 0);
+    err = db.Exec(_L("DROP TABLE A"));
+    TEST(err >= 0);
+    
+    db.Close();
+    (void)RSqlDatabase::Delete(KTestDbName2);
+    }
+
 /**
 @SYMTestCaseID			SYSLIB-SQL-CT-1646
 @SYMTestCaseDesc		Testing database operations on a secure database.
@@ -105,6 +165,26 @@
 	//Attempt to modify the database schema
 	err = TheDb.Exec(_L("CREATE TABLE C(FFF TEXT)"));
 	TEST2(err, KErrPermissionDenied);
+    err = TheDb.Exec(_L("CREATE TEMP TABLE TBL1(COL1 INTEGER, COL2 INTEGER)"));
+    TEST(err >= 0);
+    err = TheDb.Exec(_L("CREATE TEMP TRIGGER del1 AFTER DELETE ON TBL1 BEGIN DELETE FROM A; END;"));
+    TEST(err >= 0);
+    err = TheDb.Exec(_L("DROP TRIGGER del1"));
+    TEST(err >= 0);
+    err = TheDb.Exec(_L("CREATE TEMP VIEW V1 AS SELECT * FROM TBL1"));
+    TEST(err >= 0);
+    err = TheDb.Exec(_L("DROP VIEW V1"));
+    TEST(err >= 0);
+    err = TheDb.Exec(_L("CREATE INDEX I1 ON TBL1(COL2)"));
+    TEST(err >= 0);
+    err = TheDb.Exec(_L("DROP INDEX I1"));
+    TEST(err >= 0);
+    err = TheDb.Exec(_L("DROP TABLE TBL1"));
+    TEST(err >= 0);
+    err = TheDb.Exec(_L("ANALYZE A"));
+    TEST2(err, KErrPermissionDenied);
+    err = TheDb.Exec(_L("CREATE VIEW V2 AS SELECT * FROM A"));
+    TEST2(err, KErrPermissionDenied);
 	//Attempt to update the user data (but it includes a READ operation)
 	err = TheDb.Exec(_L("UPDATE A SET F1 = 11 WHERE F1 = 1"));
 	TEST(err >= 0);	
@@ -156,6 +236,8 @@
 	RDebug::Print(_L("Value=%S\r\n"), &p);
 	stmt.Close();
 	
+	NonSecureDbTest();
+	
 	TheDb.Close();
 	}
 	
--- a/persistentstorage/sql/TEST/t_sqlsecurity5.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sql/TEST/t_sqlsecurity5.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -115,6 +115,23 @@
 	//Attempt to modify the database schema
 	err = TheDb.Exec(_L("CREATE TABLE IF NOT EXISTS C(FFF TEXT)"));
 	TEST(err >= 0);	
+	//Index operations
+    err = TheDb.Exec(_L("CREATE INDEX Cidx ON C(FFF)"));
+    TEST(err >= 0);     
+    err = TheDb.Exec(_L("ANALYZE C"));
+    TEST(err >= 0);     
+    err = TheDb.Exec(_L("DROP INDEX Cidx"));
+    TEST(err >= 0);     
+    //Trigger operations
+    err = TheDb.Exec(_L("CREATE TRIGGER T1 AFTER INSERT ON C BEGIN INSERT INTO B VALUES(1, 2); END;"));
+    TEST(err >= 0);
+    err = TheDb.Exec(_L("DROP TRIGGER T1"));
+    TEST(err >= 0);
+    //View operations
+    err = TheDb.Exec(_L("CREATE VIEW V1 AS SELECT * FROM C"));
+    TEST(err >= 0);
+    err = TheDb.Exec(_L("DROP VIEW V1"));
+    TEST(err >= 0);
 	//Attempt to update the user data (but it includes a READ operation)
 	err = TheDb.Exec(_L("UPDATE A SET F1 = 11 WHERE F1 = 1"));
 	TEST(err >= 0);	
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/persistentstorage/sql/TEST/t_sqlstartup.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -0,0 +1,365 @@
+// Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+// All rights reserved.
+// This component and the accompanying materials are made available
+// under the terms of "Eclipse Public License v1.0"
+// which accompanies this distribution, and is available
+// at the URL "http://www.eclipse.org/legal/epl-v10.html".
+//
+// Initial Contributors:
+// Nokia Corporation - initial contribution.
+//
+// Contributors:
+//
+// Description:
+//
+
+#include <e32test.h>
+#include <bautils.h>
+#include "SqlSrvMain.h"
+#include "SqlSrvStartup.h"
+#include "SqlSrvUtil.h"
+
+///////////////////////////////////////////////////////////////////////////////////////
+
+RTest TheTest(_L("t_sqlstartup test"));
+
+static TInt TheProcessHandleCount = 0;
+static TInt TheThreadHandleCount = 0;
+static TInt TheAllocatedCellsCount = 0;
+
+#ifdef _DEBUG
+static const TInt KBurstRate = 20;
+#endif
+
+///////////////////////////////////////////////////////////////////////////////////////
+
+void DeleteTestFiles()
+	{
+	}
+
+///////////////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////////////
+//Test macros and functions
+void Check(TInt aValue, TInt aLine)
+	{
+	if(!aValue)
+		{
+		DeleteTestFiles();
+		RDebug::Print(_L("*** Expresssion evaluated to false\r\n"));
+		TheTest(EFalse, aLine);
+		}
+	}
+void Check(TInt aValue, TInt aExpected, TInt aLine)
+	{
+	if(aValue != aExpected)
+		{
+		DeleteTestFiles();
+		RDebug::Print(_L("*** Expected error: %d, got: %d\r\n"), aExpected, aValue);
+		TheTest(EFalse, aLine);
+		}
+	}
+#define TEST(arg) ::Check((arg), __LINE__)
+#define TEST2(aValue, aExpected) ::Check(aValue, aExpected, __LINE__)
+
+////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+static void MarkHandles()
+    {
+    RThread().HandleCount(TheProcessHandleCount, TheThreadHandleCount);
+    }
+
+static void MarkAllocatedCells()
+    {
+    TheAllocatedCellsCount = User::CountAllocCells();
+    }
+
+static void CheckAllocatedCells()
+    {
+    TInt allocatedCellsCount = User::CountAllocCells();
+    TEST2(allocatedCellsCount, TheAllocatedCellsCount);
+    }
+
+static void CheckHandles()
+    {
+    TInt endProcessHandleCount;
+    TInt endThreadHandleCount;
+    
+    RThread().HandleCount(endProcessHandleCount, endThreadHandleCount);
+
+    TEST2(TheProcessHandleCount, endProcessHandleCount);
+    TEST2(TheThreadHandleCount, endThreadHandleCount);
+    }
+
+static void OomPreStep(TInt
+#ifdef _DEBUG        
+    aFailingAllocationNo
+#endif
+                      )
+    {
+    MarkHandles();
+    MarkAllocatedCells();
+    __UHEAP_MARK;
+    __UHEAP_SETBURSTFAIL(RAllocator::EBurstFailNext, aFailingAllocationNo, KBurstRate);
+    }
+
+static void OomPostStep()
+    {
+    __UHEAP_RESET;
+    __UHEAP_MARKEND;
+    CheckAllocatedCells();
+    CheckHandles();
+    }
+
+////////////////////////////////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+static void CreateAndDestroySqlServerL()
+    {
+    CSqlServer* server = CSqlServer::NewLC();
+    CleanupStack::PopAndDestroy(server);
+    }
+
+static CSqlServer* CreateSqlServerL()
+    {
+    CSqlServer* server = CSqlServer::NewLC();
+    CleanupStack::Pop(server);
+    return server;
+    }
+
+/**
+@SYMTestCaseID          PDS-SQL-UT-4159
+@SYMTestCaseDesc        SQL server startup OOM test
+@SYMTestPriority        High
+@SYMTestActions         Runs the SQL server startup code in an OOM loop.
+@SYMTestExpectedResults Test must not fail
+@SYMDEF                 DEF144096
+*/  
+void SqlServerStartupOomTest()
+    {
+    TInt err = KErrNoMemory;
+    TInt failingAllocationNo = 0;
+    TheTest.Printf(_L("Iteration:\r\n"));
+    while(err == KErrNoMemory)
+        {
+        TheTest.Printf(_L(" %d"), ++failingAllocationNo);
+        OomPreStep(failingAllocationNo);
+        TRAP(err, CreateAndDestroySqlServerL());
+        OomPostStep();
+        }
+    if(err != KErrNoMemory)
+        {
+        TEST2(err, KErrNone);   
+        }
+    TheTest.Printf(_L("\r\n===OOM test succeeded at heap failure rate of %d ===\r\n"), failingAllocationNo);
+    }
+
+/**
+@SYMTestCaseID          PDS-SQL-UT-4160
+@SYMTestCaseDesc        CSqlServer::GetBackUpListL() OOM test
+@SYMTestPriority        High
+@SYMTestActions         Calls CSqlServer::GetBackUpListL() in an OOM loop.
+@SYMTestExpectedResults Test must not fail
+@SYMDEF                 DEF144096
+*/  
+void GetBackupListOomTest()
+    {
+    CSqlServer* server = NULL;
+    TRAPD(err, server = CreateSqlServerL());
+    TEST2(err, KErrNone);
+  
+    TInt fileCnt = 0;
+    err = KErrNoMemory;
+    TInt failingAllocationNo = 0;
+    TheTest.Printf(_L("Iteration:\r\n"));
+    while(err == KErrNoMemory)
+        {
+        TheTest.Printf(_L(" %d"), ++failingAllocationNo);
+        OomPreStep(failingAllocationNo);
+        const TUid KDbUd = {0x98765432};
+        RArray<TParse> files;
+        TRAP(err, server->GetBackUpListL(KDbUd, files));
+        fileCnt = files.Count(); 
+        files.Close();
+        OomPostStep();
+        }
+    
+    delete server;
+    
+    if(err != KErrNoMemory)
+        {
+        TEST2(err, KErrNone);   
+        }
+    TheTest.Printf(_L("\r\n===OOM test succeeded at heap failure rate of %d ===\r\nFile count: %d\r\n"), failingAllocationNo, fileCnt);
+    }
+
+/**
+@SYMTestCaseID          PDS-SQL-UT-4161
+@SYMTestCaseDesc        SQL server startup file I/O error simulation test
+@SYMTestPriority        High
+@SYMTestActions         Runs the SQL server startup code in a file I/O error simulation loop.
+@SYMTestExpectedResults Test must not fail
+@SYMDEF                 DEF144096
+*/  
+void SqlServerStartupFileIoErrorTest()
+    {
+    RFs fs;
+    TInt err = fs.Connect();
+    TEST2(err, KErrNone);
+    
+    for(TInt fsError=KErrNotFound;fsError>=KErrBadName;--fsError)
+        {
+        TheTest.Printf(_L("===Simulated error: %d\r\nIteration: "), fsError);
+        err = KErrNotFound;
+        TInt cnt=1;
+        while(err<KErrNone)
+            {
+            TheTest.Printf(_L("%d "), cnt);
+            (void)fs.SetErrorCondition(fsError, cnt);
+            TRAP(err, CreateAndDestroySqlServerL());
+            (void)fs.SetErrorCondition(KErrNone);
+            if(err != KErrNone)
+                {
+                ++cnt;
+                }
+            }
+        TEST2(err, KErrNone);
+        TheTest.Printf(_L("\r\n===File I/O error simulation test succeeded on iteration %d===\r\n"), cnt);
+        }
+
+    fs.Close();
+    }
+
+/**
+@SYMTestCaseID          PDS-SQL-UT-4162
+@SYMTestCaseDesc        CSqlServer::GetBackUpListL() file I/O error simulation test
+@SYMTestPriority        High
+@SYMTestActions         Calls CSqlServer::GetBackUpListL() in a file I/O error simulation loop.
+@SYMTestExpectedResults Test must not fail
+@SYMDEF                 DEF144096
+*/  
+void GetBackupListFileIoErrorTest()
+    {
+    CSqlServer* server = NULL;
+    TRAPD(err, server = CreateSqlServerL());
+    TEST2(err, KErrNone);
+
+    for(TInt fsError=KErrNotFound;fsError>=KErrBadName;--fsError)
+        {
+        TheTest.Printf(_L("===Simulated error: %d\r\nIteration: "), fsError);
+        err = KErrNotFound;
+        TInt fileCnt = 0;
+        TInt cnt=1;
+        while(err<KErrNone)
+            {
+            TheTest.Printf(_L("%d "), cnt);
+            (void)server->Fs().SetErrorCondition(fsError, cnt);
+            const TUid KDbUd = {0x98765432};
+            RArray<TParse> files;
+            TRAP(err, server->GetBackUpListL(KDbUd, files));
+            fileCnt = files.Count(); 
+            files.Close();
+            (void)server->Fs().SetErrorCondition(KErrNone);
+            if(err != KErrNone)
+                {
+                ++cnt;
+                }
+            }
+        TEST2(err, KErrNone);
+        TheTest.Printf(_L("\r\n===File I/O error simulation test succeeded on iteration %d===\r\nFile count: %d\r\n"), cnt, fileCnt);
+        }
+        
+    delete server;
+    }
+
+/**
+@SYMTestCaseID          PDS-SQL-UT-4163
+@SYMTestCaseDesc        Test for DEF144196: SQL, server code coverage can be improved
+@SYMTestPriority        High
+@SYMTestActions         Tests the UTF conversion functions implemented in SqlSrvUtil.cpp.
+@SYMTestExpectedResults Test must not fail
+@SYMDEF                 DEF144196
+*/  
+void UtfConversionTest()
+    {
+    /////////       UTF16ToUTF8()       ///////////////////////
+    _LIT(KStr16, "abcd");
+    _LIT8(KStr8, "abcd");
+    TBuf8<KMaxFileName + 1> bufout;
+    TBool rc = UTF16ToUTF8(KStr16, bufout);
+    TEST(rc);
+    TEST(bufout == KStr8);
+    //Test where the input buffer contains non-convertible characters
+    TBuf<2> name2;
+    name2.SetLength(2);
+    name2[0] = TChar(0xD800); 
+    name2[1] = TChar(0xFC00); 
+    rc = UTF16ToUTF8(name2, bufout);
+    TEST(!rc);
+    /////////       UTF16ToUTF8Z()       ///////////////////////
+    _LIT8(KStr8Z, "abcd\x0");
+    rc = UTF16ToUTF8Z(KStr16, bufout);
+    TEST(rc);
+    TEST(bufout == KStr8Z);
+    //Test where the input buffer contains non-convertible characters
+    rc = UTF16ToUTF8Z(name2, bufout);
+    TEST(!rc);
+    /////////       UTF16ZToUTF8Z()       ///////////////////////
+    _LIT(KStr16Z, "abcd\x0");
+    rc = UTF16ZToUTF8Z(KStr16Z, bufout);
+    TEST(rc);
+    TEST(bufout == KStr8Z);
+    //Test where the input buffer contains non-convertible characters
+    TBuf<3> name3;
+    name3.SetLength(3);
+    name3[0] = TChar(0xD800); 
+    name3[1] = TChar(0xFC00); 
+    name3[2] = TChar(0x0000); 
+    rc = UTF16ZToUTF8Z(name3, bufout);
+    TEST(!rc);
+    }
+
+void DoTests()
+	{
+    CActiveScheduler* scheduler = new CActiveScheduler;
+    TEST(scheduler != NULL);
+    CActiveScheduler::Install(scheduler);
+	
+    TheTest.Start(_L(" @SYMTestCaseID:PDS-SQL-UT-4159 SQL server startup OOM test"));
+    SqlServerStartupOomTest();
+
+    TheTest.Next (_L(" @SYMTestCaseID:PDS-SQL-UT-4160 CSqlServer::GetBackUpListL() OOM test"));
+    GetBackupListOomTest();
+
+    TheTest.Next (_L(" @SYMTestCaseID:PDS-SQL-UT-4161 SQL server startup file I/O error simulation test"));
+    SqlServerStartupFileIoErrorTest();
+    
+    TheTest.Next (_L(" @SYMTestCaseID:PDS-SQL-UT-4162 CSqlServer::GetBackUpListL() file I/O error simulation test"));
+    GetBackupListFileIoErrorTest();
+
+    TheTest.Next (_L(" @SYMTestCaseID:PDS-SQL-UT-4163 SQL server, UTF conversion test"));
+    UtfConversionTest();
+
+    delete scheduler;
+	}
+
+TInt E32Main()
+	{
+	TheTest.Title();
+	
+	CTrapCleanup* tc = CTrapCleanup::New();
+	
+	__UHEAP_MARK;
+	
+	DoTests();
+	DeleteTestFiles();
+
+	__UHEAP_MARKEND;
+	
+	TheTest.End();
+	TheTest.Close();
+	
+	delete tc;
+
+	User::Heap().Check();
+	return KErrNone;
+	}
--- a/persistentstorage/sqlite3api/OsLayer/FileBuf64.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sqlite3api/OsLayer/FileBuf64.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -186,44 +186,6 @@
 #endif//_DEBUG
 
 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-///////////////////////////        MFileInitializer64    /////////////////////////////////////////////////////////////
-//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-
-/**
-MFileInitializer64 interface provides only one abstract method - Init() that is used during the initialization of
-the RFileBuf64 objects.
-Here is what is the problem MFileInitializer64 tries to solve.
-RFileBuf64 has 4 different "resource acquisition" methods - Create(), Open() and Temp().
-They perform different actions and have different input arguments.
-This is the variable part of the RFileBuf64 initialization.
-Apart from that, RFileBuf64 has a "fixed" initialization part that does not change whatever the variable part is.
-If MFileInitializer64 interface is not used then the following chunk of code has to be duplicated 4 times:
-@code
-	TInt err = do_fixed_init();
-	if(err == KErrNone)
-		{
-		err = do_variable_init();
-		if(err != KErrNone)
-			{
-			revert_fixed_init();
-			}
-		}
-	return err;
-@endcode
-In order to avoid the code duplication, the fixed part of the initialization is moved to RFileBuf64::DoInit(), which
-is given a reference to a MFileInitializer64 derived class that performas the variable part of the initialization.
-4 different MFileInitializer64 derived classes are provided for the 4 different "resource acquisition" methods.
-All they store the variable part of the RFileBuf64 initialization parameters and implement MFileInitializer64::Init().
-
-@see RFileBuf64::DoInit()
-@internalComponent
-*/
-struct MFileInitializer64
-	{
-	virtual TInt Init(RFile64& aFile) = 0;
-	};
-	
-//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 ///////////////////////////        RFileBuf64    /////////////////////////////////////////////////////////////////////
 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 	
@@ -256,7 +218,6 @@
 
 @see TFileMode
 @see RFile64::Create()
-@see MFileInitializer64
 
 @panic FBuf64  7 In _DEBUG mode - Invalid aFs object (null file session handle).
 @panic FBuf64 10 In _DEBUG mode - Invalid file name length (zero file name length).
@@ -266,24 +227,12 @@
 	__FBUF64_ASSERT(aFs.Handle() != 0, EFBufPanicFsHandle);
 	__FBUF64_ASSERT(aFileName.Length() > 0, EFBufPanicFileNameLen);
 	
-	struct TFileCreateInitializer64 : public MFileInitializer64
-		{
-		inline TFileCreateInitializer64(RFs& aFs, const TDesC& aFileName, TUint aFileMode) :
-			iFs(aFs),
-			iFileName(aFileName),
-			iFileMode(aFileMode)
-			{
-			}
-		virtual TInt Init(RFile64& aFile)
-			{
-			return aFile.Create(iFs, iFileName, iFileMode);
-			}
-		RFs& 			iFs;
-		const TDesC& 	iFileName;
-		TUint 			iFileMode;
-		} initializer(aFs, aFileName, aFileMode);
-		
-	return DoInit(initializer);
+    TInt err = DoPreInit();
+    if(err == KErrNone)
+        {
+        err = iFile.Create(aFs, aFileName, aFileMode);
+        }
+    return DoPostInit(err);
 	}
 
 /**
@@ -300,7 +249,6 @@
 
 @see TFileMode
 @see RFile64::Open()
-@see MFileInitializer64
 
 @panic FBuf64  7 In _DEBUG mode - Invalid aFs object (null file session handle).
 @panic FBuf64 10 In _DEBUG mode - Invalid file name length (zero file name length).
@@ -309,25 +257,13 @@
 	{
 	__FBUF64_ASSERT(aFs.Handle() != 0, EFBufPanicFsHandle);
 	__FBUF64_ASSERT(aFileName.Length() > 0, EFBufPanicFileNameLen);
-	
-	struct TFileOpenInitializer64 : public MFileInitializer64
-		{
-		inline TFileOpenInitializer64(RFs& aFs, const TDesC& aFileName, TUint aFileMode) :
-			iFs(aFs),
-			iFileName(aFileName),
-			iFileMode(aFileMode)
-			{
-			}
-		virtual TInt Init(RFile64& aFile)
-			{
-			return aFile.Open(iFs, iFileName, iFileMode);
-			}
-		RFs& 			iFs;
-		const TDesC& 	iFileName;
-		TUint 			iFileMode;
-		} initializer(aFs, aFileName, aFileMode);
-
-	return DoInit(initializer);
+    
+    TInt err = DoPreInit();
+    if(err == KErrNone)
+        {
+        err = iFile.Open(aFs, aFileName, aFileMode);
+        }
+    return DoPostInit(err);
 	}
 
 /**
@@ -346,34 +282,19 @@
 
 @see TFileMode
 @see RFile64::Temp()
-@see MFileInitializer64
 
 @panic FBuf64  7 In _DEBUG mode - Invalid aFs object (null file session handle).
 */
 TInt RFileBuf64::Temp(RFs& aFs, const TDesC& aPath, TFileName& aFileName, TUint aFileMode)
 	{
 	__FBUF64_ASSERT(aFs.Handle() != 0, EFBufPanicFsHandle);
-	
-	struct TFileTempInitializer64 : public MFileInitializer64
-		{
-		inline TFileTempInitializer64(RFs& aFs, const TDesC& aPath, TFileName& aFileName, TUint aFileMode) :
-			iFs(aFs),
-			iPath(aPath),
-			iFileName(aFileName),
-			iFileMode(aFileMode)
-			{
-			}
-		virtual TInt Init(RFile64& aFile)
-			{
-			return aFile.Temp(iFs, iPath, iFileName, iFileMode);
-			}
-		RFs& 			iFs;
-		const TDesC& 	iPath;
-		TFileName& 		iFileName;
-		TUint 			iFileMode;
-		} initializer(aFs, aPath, aFileName, aFileMode);
-	
-	return DoInit(initializer);
+    
+    TInt err = DoPreInit();
+    if(err == KErrNone)
+        {
+        err = iFile.Temp(aFs, aPath, aFileName, aFileMode);
+        }
+    return DoPostInit(err);
 	}
 
 /**
@@ -397,6 +318,15 @@
 
 /**
 Calculates and sets optimal read-ahead buffer size.
+aBlockSize and aReadRecBufSize values are retrieved by the caller from the file system.
+
+Initialization rules:
+Rule 1: If aReadRecBufSize is positive, bigger than the default read-ahead and 
+        a power of two then the read-ahead value will be
+        initialized with aReadRecBufSize (if aReadRecBufSize is less than the buffer capacity otherwise
+        the buffer capacity will be used as a read-ahead value). 
+Rule 2: If rule#1 is not applicable then the same checks, as in rule#1, are performed this time for aBlockSize.
+        If aBlockSize passes the checks then it will be used as a read-ahead value. 
 
 @param aBlockSize The size of a file block in bytes
 @param aReadRecBufSize The recommended buffer size for optimised reading performance
@@ -477,13 +407,13 @@
 	TUint8* outptr = const_cast <TUint8*> (aDes.Ptr());
 	while(len > 0 && err == KErrNone && aFilePos < iFileSize)
 		{
-		//1. If part of all of the data is in the buffer - copy the data to the target location
+		//1. If part or all of the data is in the buffer - copy the data to the target location
 		if(aFilePos >= iFilePos && aFilePos < (iFilePos + iLength))
 			{
-			TInt l = Min(len, (iFilePos + iLength - aFilePos));
-			outptr = Mem::Copy(outptr, iBase + (aFilePos - iFilePos), l);
-			len -= l;
-			aFilePos += l;
+			TInt blocklen = Min(len, (iFilePos + iLength - aFilePos));
+			outptr = Mem::Copy(outptr, iBase + (aFilePos - iFilePos), blocklen);
+			len -= blocklen;
+			aFilePos += blocklen;
 			}
 		//2. Perform a read-ahead operation
 		else
@@ -495,7 +425,7 @@
 				break;	
 				}
 			if(iNextReadFilePos != aFilePos)
-				{//Direct "file read" operation
+				{//Guessed read ahead was wrong. Direct "file read" operation
 				iNextReadFilePosHits = 0;
 				TPtr8 ptr2(outptr, len);
 				err = iFile.Read(aFilePos, ptr2);
@@ -790,31 +720,38 @@
 	}
 
 /**
-Performs the fixed part of the RFileBuf64 initialization and then calls MFileInitializer64::Init() to perform
-the variable part of the initialization.
+Initializes RFileBuf64 data members with their initial values.   
+Allocates memory for the file buffer. 
+ 
+@return KErrNone if successful, 
+        KErrNoMemory out of memory;
+*/
+TInt RFileBuf64::DoPreInit()
+    {
+    DoDiscard();
+    iReadAheadSize = RFileBuf64::KDefaultReadAheadSize;
+    iBase = static_cast <TUint8*> (User::Alloc(iCapacity));
+    return iBase ? KErrNone : KErrNoMemory; 
+    }
 
-@param aFileInitializer A reference to an initializer object that implements MFileInitializer64::Init()
+/**
+Performs post-initialization of the RFileBuf64 object.   
+If aInitErr is not KErrNone, then the buffer memory will be released.
+The function returns the aInitErr value to the caller. 
 
+@param aInitErr The result of the performed before the call RFileBuf64 initialization.
+ 
 @return KErrNone if successful, otherwise one of the other system-wide error codes.
 */
-TInt RFileBuf64::DoInit(MFileInitializer64& aFileInitializer)
-	{
-	DoDiscard();
-	iReadAheadSize = RFileBuf64::KDefaultReadAheadSize;
-	TInt err = KErrNoMemory;
-	iBase = static_cast <TUint8*> (User::Alloc(iCapacity));
-	if(!iBase)
-		{
-		return KErrNoMemory;	
-		}
-	err = aFileInitializer.Init(iFile);
-	if(err != KErrNone)
-		{
-		User::Free(iBase);
-		iBase = 0;
-		}
-	return err;
-	}
+TInt RFileBuf64::DoPostInit(TInt aInitErr)
+    {
+    if(aInitErr != KErrNone)
+        {
+        User::Free(iBase);
+        iBase = 0;
+        }
+    return aInitErr;
+    }
 
 /**
 Discards the content of the RFileBuf64 object returning it to the state as if it has just been created. 
--- a/persistentstorage/sqlite3api/OsLayer/FileBuf64.h	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sqlite3api/OsLayer/FileBuf64.h	Fri Apr 16 16:49:27 2010 +0300
@@ -18,9 +18,6 @@
 #include <f32file.h>
 #include <f32file64.h>
 
-//Forward declaration
-struct MFileInitializer64;
-
 /**
 The RFileBuf64 class provides buffered file read/write operations on a single RFile64 object.
 RFileBuf64::Read() and RFileBuf64::Write() methods may boost the performance of the read/write file operations up to 30% 
@@ -47,28 +44,31 @@
 	  In details, to create a file and access it through a RFileBuf64 object:
 	  
 	  	RFs fs;
-	  	//initialize the file session
+	  	TInt err = fs.Connect();
+        //check the error
 	  	...
 	  	RFileBuf64 fbuf(<N>);									//<N> is the buffer capacity in bytes
-	  	TInt err = fbuf.Create(fs, <file name>, <file mode>);
+	  	err = fbuf.Create(fs, <file name>, <file mode>);
 	  	//check the error
 	  	
 	  To open an existing file and access it through a RFileBuf64 object:
 
 	  	RFs fs;
-	  	//initialize the file session
+        TInt err = fs.Connect();
+        //check the error
 	  	...
 	  	RFileBuf64 fbuf(<N>);									//<N> is the buffer capacity in bytes
-	  	TInt err = fbuf.Open(fs, <file name>, <file mode>);
+	  	err = fbuf.Open(fs, <file name>, <file mode>);
 	  	//check the error
 	  
 	  To create a temporary file and access it through a RFileBuf64 object:
 
 	  	RFs fs;
-	  	//initialize the file session
+        TInt err = fs.Connect();
+        //check the error
 	  	...
 	  	RFileBuf64 fbuf(<N>);									//<N> is the buffer capacity in bytes
-	  	TInt err = fbuf.Temp(fs, <path>, <file name>, <file mode>);
+	  	err = fbuf.Temp(fs, <path>, <file name>, <file mode>);
 	  	//check the error
 	  
 	- if the RFileBuf64 object is initialised successfully, now the public RFileBuf64 methods can be called to perform
@@ -90,7 +90,7 @@
 @endcode
 
 Implementation notes: the current RFileBuf64 implementation is optimised for use by the SQLite OS porting layer.
-	After a detailed investigation of the performed by SQLite file read/write operations it was found that buffering of
+	After investigation of SQLite file read/write operations it was found that buffering of
 	two or more logical file writes into a single physical file write has a positive impact (as expected) on the performance 
 	of the database write operations. But the picture is quite different for the file read operations. The database data is
 	organised in pages with fixed size. After a database is created and set of insert/update/delete operations is performed 
@@ -150,7 +150,8 @@
 
 private:
 	void Invariant() const;
-	TInt DoInit(MFileInitializer64& aFileInitializer);
+    TInt DoPreInit();
+    TInt DoPostInit(TInt aInitErr);
 	void DoDiscard();
 	TInt DoFileSize();
 	TInt DoSetFileSize(TInt64 aFileSize);
--- a/persistentstorage/sqlite3api/OsLayer/os_symbian_mt.cpp	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sqlite3api/OsLayer/os_symbian_mt.cpp	Fri Apr 16 16:49:27 2010 +0300
@@ -547,8 +547,7 @@
 SQLite OS porting layer API.
 
 Closes the file referred by aDbFile parameter.
-If aDbFile, which is actually a pointer to a TDbFile instance, the iFullName data member is not NULL, 
-then the file will be deleted.
+If aDbFile.iFullName data member is not NULL, then the file will be deleted.
 
 @param aDbFile A pointer to a TDbFile instance, than contains the file handle to be closed.
 
@@ -562,7 +561,8 @@
 	TDbFile& dbFile = ::DbFile(aDbFile);
 	dbFile.iFileBuf.Close();	
 	if(dbFile.iFullName)
-		{
+        {//"iFullName" will not be NULL only when TVfs::Open() is called with SQLITE_OPEN_DELETEONCLOSE flag.
+         //That means - SQlite expects the file to be deleted after the file close operation. 
 		(void)TStaticFs::Fs().Delete(*dbFile.iFullName);
 		delete dbFile.iFullName;
 		dbFile.iFullName = NULL;
--- a/persistentstorage/sqlite3api/SQLite/fts1.h	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sqlite3api/SQLite/fts1.h	Fri Apr 16 16:49:27 2010 +0300
@@ -1,3 +1,19 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
 #include "sqlite3.h"
 
 #ifdef __cplusplus
--- a/persistentstorage/sqlite3api/SQLite/parse.h	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sqlite3api/SQLite/parse.h	Fri Apr 16 16:49:27 2010 +0300
@@ -1,3 +1,20 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
 #define TK_SEMI                            1
 #define TK_EXPLAIN                         2
 #define TK_QUERY                           3
--- a/persistentstorage/sqlite3api/SQLite/printf.c	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sqlite3api/SQLite/printf.c	Fri Apr 16 16:49:27 2010 +0300
@@ -1,3 +1,19 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
 /*
 ** The "printf" code that follows dates from the 1980's.  It is in
 ** the public domain.  The original comments are included here for
--- a/persistentstorage/sqlite3api/TEST/TCL/tcldistribution/compat/opendir.c	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sqlite3api/TEST/TCL/tcldistribution/compat/opendir.c	Fri Apr 16 16:49:27 2010 +0300
@@ -1,3 +1,19 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
 /* 
  * opendir.c --
  *
--- a/persistentstorage/sqlite3api/TEST/TCL/tcldistribution/generic/regerrs.h	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sqlite3api/TEST/TCL/tcldistribution/generic/regerrs.h	Fri Apr 16 16:49:27 2010 +0300
@@ -1,3 +1,20 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
 { REG_OKAY,	"REG_OKAY",	"no errors detected" },
 { REG_NOMATCH,	"REG_NOMATCH",	"failed to match" },
 { REG_BADPAT,	"REG_BADPAT",	"invalid regexp (reg version 0.8)" },
--- a/persistentstorage/sqlite3api/TEST/TCL/tcldistribution/mac/MW_TclAppleScriptHeader.h	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sqlite3api/TEST/TCL/tcldistribution/mac/MW_TclAppleScriptHeader.h	Fri Apr 16 16:49:27 2010 +0300
@@ -1,3 +1,20 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
 #if __POWERPC__
 #include "MW_TclAppleScriptHeaderPPC"
 #elif __CFM68K__
--- a/persistentstorage/sqlite3api/TEST/TCL/tcldistribution/mac/MW_TclBuildLibHeader.h	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sqlite3api/TEST/TCL/tcldistribution/mac/MW_TclBuildLibHeader.h	Fri Apr 16 16:49:27 2010 +0300
@@ -1,3 +1,20 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
 #if __POWERPC__
 #include "MW_TclBuildLibHeaderPPC"
 #elif __CFM68K__
--- a/persistentstorage/sqlite3api/TEST/TCL/tcldistribution/mac/MW_TclHeader.h	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sqlite3api/TEST/TCL/tcldistribution/mac/MW_TclHeader.h	Fri Apr 16 16:49:27 2010 +0300
@@ -1,3 +1,20 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
 #if __POWERPC__
 #include "MW_TclHeaderPPC"
 #elif __CFM68K__
--- a/persistentstorage/sqlite3api/TEST/TCL/tcldistribution/mac/MW_TclStaticHeader.h	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sqlite3api/TEST/TCL/tcldistribution/mac/MW_TclStaticHeader.h	Fri Apr 16 16:49:27 2010 +0300
@@ -1,3 +1,20 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
 #if __POWERPC__
 #include "MW_TclStaticHeaderPPC"
 #elif __CFM68K__
--- a/persistentstorage/sqlite3api/TEST/TCL/tcldistribution/mac/MW_TclTestHeader.h	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sqlite3api/TEST/TCL/tcldistribution/mac/MW_TclTestHeader.h	Fri Apr 16 16:49:27 2010 +0300
@@ -1,3 +1,20 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
+
 #if __POWERPC__
 #include "MW_TclTestHeaderPPC"
 #elif __CFM68K__
--- a/persistentstorage/sqlite3api/TEST/TCL/tcldistribution/unix/tclUnixCompat.c	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sqlite3api/TEST/TCL/tcldistribution/unix/tclUnixCompat.c	Fri Apr 16 16:49:27 2010 +0300
@@ -1,3 +1,19 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
 /*
  * tclUnixCompat.c
  *
--- a/persistentstorage/sqlite3api/TEST/TCL/tcldistribution/win/buildall.vc.bat	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sqlite3api/TEST/TCL/tcldistribution/win/buildall.vc.bat	Fri Apr 16 16:49:27 2010 +0300
@@ -1,3 +1,18 @@
+@rem
+@rem Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+@rem All rights reserved.
+@rem This component and the accompanying materials are made available
+@rem under the terms of "Eclipse Public License v1.0"
+@rem which accompanies this distribution, and is available
+@rem at the URL "http://www.eclipse.org/legal/epl-v10.html".
+@rem
+@rem Initial Contributors:
+@rem Nokia Corporation - initial contribution.
+@rem
+@rem Contributors:
+@rem
+@rem Description: 
+@rem
 @echo off
 
 ::  This is an example batchfile for building everything. Please
--- a/persistentstorage/sqlite3api/TEST/TclScript/crashtest1.c	Fri Mar 19 10:00:55 2010 +0200
+++ b/persistentstorage/sqlite3api/TEST/TclScript/crashtest1.c	Fri Apr 16 16:49:27 2010 +0300
@@ -1,3 +1,19 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
 /*
 ** This program tests the ability of SQLite database to recover from a crash.
 ** This program runs under Unix only, but the results are applicable to all
--- a/traceservices/commsdebugutility/INC/commsdebugutility.h	Fri Mar 19 10:00:55 2010 +0200
+++ b/traceservices/commsdebugutility/INC/commsdebugutility.h	Fri Apr 16 16:49:27 2010 +0300
@@ -16,8 +16,9 @@
 //
 
 /**
- @file
- @internalTechnology
+@file
+@publishedAll
+@deprecated Migrate to Open System Trace Instrumentation API instead
 */
 
 #ifndef __COMMSDEBUGUTILITY_H__
@@ -67,7 +68,8 @@
 /**
  * Panic codes
  *
- * @internalTechnology
+ * @publishedAll
+ * @deprecated Migrate to Open System Trace Instrumentation API instead
  * @note The order of the panic numbers should not be changed.
  *       New panic codes must be added at the end of this enum.
  *       All panic codes are assigned to values to ease debugging.
@@ -81,7 +83,7 @@
 /**
  * Logging Mode codes
  *
- * @internalTechnology
+ * @publishedAll
  * @deprecated As of version 8.0 the logging modes are deprecated due to the introduction
  *             of a single log file. Appent mode is the default for all write operations,
  *             while Overwrite can be achieved using new __FLOG_CLEAR macro, or ClearLog API.
@@ -101,7 +103,9 @@
 /**
  * Flogger - File and Serial Logger client interface 
  *
- * @internalTechnology 
+ * @publishedAll
+ * @deprecated Migrate to Open System Trace Instrumentation API instead
+ * 
  * This class is responsible for providing all functions
  * clients require of the flogger system. It is preferred, though,
  * that clients use the provided macros which refer to these API's
--- a/traceservices/commsdebugutility/group/BLD.INF	Fri Mar 19 10:00:55 2010 +0200
+++ b/traceservices/commsdebugutility/group/BLD.INF	Fri Apr 16 16:49:27 2010 +0300
@@ -21,7 +21,7 @@
 ../tools/splitlog.bat	/epoc32/tools/splitlog.bat
 ../tools/extractlog.pl	/epoc32/tools/extractlog.pl
 
-../INC/commsdebugutility.h	SYMBIAN_OS_LAYER_PLATFORM_EXPORT_PATH(comms-infras/commsdebugutility.h)
+../INC/commsdebugutility.h	SYMBIAN_OS_LAYER_PUBLIC_EXPORT_PATH(comms-infras/commsdebugutility.h)
 
 ../group/commsdebugutility.iby	    /epoc32/rom/include/commsdebugutility.iby
 ../group/commslog.iby				/epoc32/rom/include/commslog.iby
--- a/traceservices/tracefw/integ_test/ost/TEF/traces/OstTraceDefinitions.h	Fri Mar 19 10:00:55 2010 +0200
+++ b/traceservices/tracefw/integ_test/ost/TEF/traces/OstTraceDefinitions.h	Fri Apr 16 16:49:27 2010 +0300
@@ -1,3 +1,19 @@
+/*
+* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
+* All rights reserved.
+* This component and the accompanying materials are made available
+* under the terms of "Eclipse Public License v1.0"
+* which accompanies this distribution, and is available
+* at the URL "http://www.eclipse.org/legal/epl-v10.html".
+*
+* Initial Contributors:
+* Nokia Corporation - initial contribution.
+*
+* Contributors:
+*
+* Description: 
+*
+*/
 #ifndef __OSTTRACEDEFINITIONS_H__
 #define __OSTTRACEDEFINITIONS_H__
 // OST_TRACE_COMPILER_IN_USE flag has been added by Trace Compiler