sqllogictest
Check-in [10318b880c]
Not logged in

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
SHA1 Hash:10318b880cb756b267cb9ffa4a301fb97bb17307
Date: 2010-03-09 16:52:34
User: drh
Comment:Update SQLite to pre-3.6.23.
Tags And Properties
Changes
hide diffs unified diffs patch

Changes to src/sqlite3.c

1 /****************************************************************************** 1 /****************************************************************************** 2 ** This file is an amalgamation of many separate C source files from SQLite 2 ** This file is an amalgamation of many separate C source files from SQLite 3 ** version 3.6.22. By combining all the individual C code files into this | 3 ** version 3.6.23. By combining all the individual C code files into this 4 ** single large file, the entire code can be compiled as a one translation 4 ** single large file, the entire code can be compiled as a one translation 5 ** unit. This allows many compilers to do optimizations that would not be 5 ** unit. This allows many compilers to do optimizations that would not be 6 ** possible if the files were compiled separately. Performance improvements 6 ** possible if the files were compiled separately. Performance improvements 7 ** of 5% are more are commonly seen when SQLite is compiled as a single 7 ** of 5% are more are commonly seen when SQLite is compiled as a single 8 ** translation unit. 8 ** translation unit. 9 ** 9 ** 10 ** This file is all you need to compile SQLite. To use SQLite in other 10 ** This file is all you need to compile SQLite. To use SQLite in other ................................................................................................................................................................................ 303 #ifdef HAVE_STDINT_H 303 #ifdef HAVE_STDINT_H 304 #include <stdint.h> 304 #include <stdint.h> 305 #endif 305 #endif 306 #ifdef HAVE_INTTYPES_H 306 #ifdef HAVE_INTTYPES_H 307 #include <inttypes.h> 307 #include <inttypes.h> 308 #endif 308 #endif 309 309 > 310 /* > 311 ** The number of samples of an index that SQLite takes in order to > 312 ** construct a histogram of the table content when running ANALYZE > 313 ** and with SQLITE_ENABLE_STAT2 > 314 */ 310 #define SQLITE_INDEX_SAMPLES 10 315 #define SQLITE_INDEX_SAMPLES 10 311 316 312 /* 317 /* 313 ** This macro is used to "hide" some ugliness in casting an int | 318 ** The following macros are used to cast pointers to integers and 314 ** value to a ptr value under the MSVC 64-bit compiler. Casting | 319 ** integers to pointers. The way you do this varies from one compiler 315 ** non 64-bit values to ptr types results in a "hard" error with | 320 ** to the next, so we have developed the following set of #if statements 316 ** the MSVC 64-bit compiler which this attempts to avoid. | 321 ** to generate appropriate macros for a wide range of compilers. 317 ** 322 ** 318 ** A simple compiler pragma or casting sequence could not be found | 323 ** The correct "ANSI" way to do this is to use the intptr_t type. 319 ** to correct this in all situations, so this macro was introduced. < 320 ** < 321 ** It could be argued that the intptr_t type could be used in this < 322 ** case, but that type is not available on all compilers, or | 324 ** Unfortunately, that typedef is not available on all compilers, or 323 ** requires the #include of specific headers which differs between | 325 ** if it is available, it requires an #include of specific headers 324 ** platforms. < > 326 ** that very from one machine to the next. 325 ** 327 ** 326 ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on 328 ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on 327 ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)). 329 ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)). 328 ** So we have to define the macros in different ways depending on the 330 ** So we have to define the macros in different ways depending on the 329 ** compiler. 331 ** compiler. 330 */ 332 */ 331 #if defined(__GNUC__) | 333 #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */ 332 # if defined(HAVE_STDINT_H) | 334 # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X)) 333 # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X)) | 335 # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X)) 334 # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X)) | 336 #elif !defined(__GNUC__) /* Works for compilers other than LLVM */ 335 # else | 337 # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X]) 336 # define SQLITE_INT_TO_PTR(X) ((void*)(X)) | 338 # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0)) 337 # define SQLITE_PTR_TO_INT(X) ((int)(X)) | 339 #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */ 338 # endif | 340 # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X)) 339 #else | 341 # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X)) 340 # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X]) | 342 #else /* Generates a warning - but it always works */ 341 # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0)) | 343 # define SQLITE_INT_TO_PTR(X) ((void*)(X)) 342 #endif | 344 # define SQLITE_PTR_TO_INT(X) ((int)(X)) 343 | 345 #endif 344 346 345 /* 347 /* 346 ** The SQLITE_THREADSAFE macro must be defined as either 0 or 1. 348 ** The SQLITE_THREADSAFE macro must be defined as either 0 or 1. 347 ** Older versions of SQLite used an optional THREADSAFE macro. 349 ** Older versions of SQLite used an optional THREADSAFE macro. 348 ** We support that for legacy 350 ** We support that for legacy 349 */ 351 */ 350 #if !defined(SQLITE_THREADSAFE) 352 #if !defined(SQLITE_THREADSAFE) ................................................................................................................................................................................ 367 369 368 /* 370 /* 369 ** Exactly one of the following macros must be defined in order to 371 ** Exactly one of the following macros must be defined in order to 370 ** specify which memory allocation subsystem to use. 372 ** specify which memory allocation subsystem to use. 371 ** 373 ** 372 ** SQLITE_SYSTEM_MALLOC // Use normal system malloc() 374 ** SQLITE_SYSTEM_MALLOC // Use normal system malloc() 373 ** SQLITE_MEMDEBUG // Debugging version of system malloc() 375 ** SQLITE_MEMDEBUG // Debugging version of system malloc() 374 ** SQLITE_MEMORY_SIZE // internal allocator #1 | 376 ** 375 ** SQLITE_MMAP_HEAP_SIZE // internal mmap() allocator | 377 ** (Historical note: There used to be several other options, but we've 376 ** SQLITE_POW2_MEMORY_SIZE // internal power-of-two allocator | 378 ** pared it down to just these two.) 377 ** 379 ** 378 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as 380 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as 379 ** the default. 381 ** the default. 380 */ 382 */ 381 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\ | 383 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)>1 382 defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\ < 383 defined(SQLITE_POW2_MEMORY_SIZE)>1 < 384 # error "At most one of the following compile-time configuration options\ 384 # error "At most one of the following compile-time configuration options\ 385 is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,\ | 385 is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG" 386 SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE" < 387 #endif 386 #endif 388 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\ | 387 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)==0 389 defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\ < 390 defined(SQLITE_POW2_MEMORY_SIZE)==0 < 391 # define SQLITE_SYSTEM_MALLOC 1 388 # define SQLITE_SYSTEM_MALLOC 1 392 #endif 389 #endif 393 390 394 /* 391 /* 395 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the 392 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the 396 ** sizes of memory allocations below this value where possible. 393 ** sizes of memory allocations below this value where possible. 397 */ 394 */ ................................................................................................................................................................................ 627 ** string contains the date and time of the check-in (UTC) and an SHA1 624 ** string contains the date and time of the check-in (UTC) and an SHA1 628 ** hash of the entire source tree. 625 ** hash of the entire source tree. 629 ** 626 ** 630 ** See also: [sqlite3_libversion()], 627 ** See also: [sqlite3_libversion()], 631 ** [sqlite3_libversion_number()], [sqlite3_sourceid()], 628 ** [sqlite3_libversion_number()], [sqlite3_sourceid()], 632 ** [sqlite_version()] and [sqlite_source_id()]. 629 ** [sqlite_version()] and [sqlite_source_id()]. 633 */ 630 */ 634 #define SQLITE_VERSION "3.6.22" | 631 #define SQLITE_VERSION "3.6.23" 635 #define SQLITE_VERSION_NUMBER 3006022 | 632 #define SQLITE_VERSION_NUMBER 3006023 636 #define SQLITE_SOURCE_ID "2010-01-05 15:30:36 28d0d7710761114a44a1a3a425a68 | 633 #define SQLITE_SOURCE_ID "2010-03-09 15:10:30 20c400e73a9b6586b97de61da0d9f 637 634 638 /* 635 /* 639 ** CAPI3REF: Run-Time Library Version Numbers 636 ** CAPI3REF: Run-Time Library Version Numbers 640 ** KEYWORDS: sqlite3_version | 637 ** KEYWORDS: sqlite3_version, sqlite3_sourceid 641 ** 638 ** 642 ** These interfaces provide the same information as the [SQLITE_VERSION], 639 ** These interfaces provide the same information as the [SQLITE_VERSION], 643 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros 640 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros 644 ** but are associated with the library instead of the header file. ^(Cautious 641 ** but are associated with the library instead of the header file. ^(Cautious 645 ** programmers might include assert() statements in their application to 642 ** programmers might include assert() statements in their application to 646 ** verify that values returned by these interfaces match the macros in 643 ** verify that values returned by these interfaces match the macros in 647 ** the header, and thus insure that the application is 644 ** the header, and thus insure that the application is ................................................................................................................................................................................ 655 ** 652 ** 656 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION] 653 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION] 657 ** macro. ^The sqlite3_libversion() function returns a pointer to the 654 ** macro. ^The sqlite3_libversion() function returns a pointer to the 658 ** to the sqlite3_version[] string constant. The sqlite3_libversion() 655 ** to the sqlite3_version[] string constant. The sqlite3_libversion() 659 ** function is provided for use in DLLs since DLL users usually do not have 656 ** function is provided for use in DLLs since DLL users usually do not have 660 ** direct access to string constants within the DLL. ^The 657 ** direct access to string constants within the DLL. ^The 661 ** sqlite3_libversion_number() function returns an integer equal to 658 ** sqlite3_libversion_number() function returns an integer equal to 662 ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function a pointer | 659 ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns 663 ** to a string constant whose value is the same as the [SQLITE_SOURCE_ID] | 660 ** a pointer to a string constant whose value is the same as the 664 ** C preprocessor macro. | 661 ** [SQLITE_SOURCE_ID] C preprocessor macro. 665 ** 662 ** 666 ** See also: [sqlite_version()] and [sqlite_source_id()]. 663 ** See also: [sqlite_version()] and [sqlite_source_id()]. 667 */ 664 */ 668 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION; 665 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION; 669 SQLITE_API const char *sqlite3_libversion(void); 666 SQLITE_API const char *sqlite3_libversion(void); 670 SQLITE_API const char *sqlite3_sourceid(void); 667 SQLITE_API const char *sqlite3_sourceid(void); 671 SQLITE_API int sqlite3_libversion_number(void); 668 SQLITE_API int sqlite3_libversion_number(void); 672 669 > 670 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS > 671 /* > 672 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics > 673 ** > 674 ** ^The sqlite3_compileoption_used() function returns 0 or 1 > 675 ** indicating whether the specified option was defined at > 676 ** compile time. ^The SQLITE_ prefix may be omitted from the > 677 ** option name passed to sqlite3_compileoption_used(). > 678 ** > 679 ** ^The sqlite3_compileoption_get() function allows interating > 680 ** over the list of options that were defined at compile time by > 681 ** returning the N-th compile time option string. ^If N is out of range, > 682 ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_ > 683 ** prefix is omitted from any strings returned by > 684 ** sqlite3_compileoption_get(). > 685 ** > 686 ** ^Support for the diagnostic functions sqlite3_compileoption_used() > 687 ** and sqlite3_compileoption_get() may be omitted by specifing the > 688 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time. > 689 ** > 690 ** See also: SQL functions [sqlite_compileoption_used()] and > 691 ** [sqlite_compileoption_get()] and the [compile_options pragma]. > 692 */ > 693 SQLITE_API int sqlite3_compileoption_used(const char *zOptName); > 694 SQLITE_API const char *sqlite3_compileoption_get(int N); > 695 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ > 696 673 /* 697 /* 674 ** CAPI3REF: Test To See If The Library Is Threadsafe 698 ** CAPI3REF: Test To See If The Library Is Threadsafe 675 ** 699 ** 676 ** ^The sqlite3_threadsafe() function returns zero if and only if 700 ** ^The sqlite3_threadsafe() function returns zero if and only if 677 ** SQLite was compiled mutexing code omitted due to the 701 ** SQLite was compiled mutexing code omitted due to the 678 ** [SQLITE_THREADSAFE] compile-time option being set to 0. 702 ** [SQLITE_THREADSAFE] compile-time option being set to 0. 679 ** 703 ** ................................................................................................................................................................................ 957 ** [sqlite3_vfs] object. 981 ** [sqlite3_vfs] object. 958 */ 982 */ 959 #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ 983 #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ 960 #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ 984 #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ 961 #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ 985 #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ 962 #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */ 986 #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */ 963 #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */ 987 #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */ > 988 #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */ 964 #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */ 989 #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */ 965 #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */ 990 #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */ 966 #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */ 991 #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */ 967 #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */ 992 #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */ 968 #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */ 993 #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */ 969 #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */ 994 #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */ 970 #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */ 995 #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */ ................................................................................................................................................................................ 1438 SQLITE_API int sqlite3_initialize(void); 1463 SQLITE_API int sqlite3_initialize(void); 1439 SQLITE_API int sqlite3_shutdown(void); 1464 SQLITE_API int sqlite3_shutdown(void); 1440 SQLITE_API int sqlite3_os_init(void); 1465 SQLITE_API int sqlite3_os_init(void); 1441 SQLITE_API int sqlite3_os_end(void); 1466 SQLITE_API int sqlite3_os_end(void); 1442 1467 1443 /* 1468 /* 1444 ** CAPI3REF: Configuring The SQLite Library 1469 ** CAPI3REF: Configuring The SQLite Library 1445 ** EXPERIMENTAL < 1446 ** 1470 ** 1447 ** The sqlite3_config() interface is used to make global configuration 1471 ** The sqlite3_config() interface is used to make global configuration 1448 ** changes to SQLite in order to tune SQLite to the specific needs of 1472 ** changes to SQLite in order to tune SQLite to the specific needs of 1449 ** the application. The default configuration is recommended for most 1473 ** the application. The default configuration is recommended for most 1450 ** applications and so this routine is usually not necessary. It is 1474 ** applications and so this routine is usually not necessary. It is 1451 ** provided to support rare applications with unusual needs. 1475 ** provided to support rare applications with unusual needs. 1452 ** 1476 ** ................................................................................................................................................................................ 1779 #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */ 1803 #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */ 1780 #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */ 1804 #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */ 1781 #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */ 1805 #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */ 1782 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 1806 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 1783 #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */ 1807 #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */ 1784 #define SQLITE_CONFIG_PCACHE 14 /* sqlite3_pcache_methods* */ 1808 #define SQLITE_CONFIG_PCACHE 14 /* sqlite3_pcache_methods* */ 1785 #define SQLITE_CONFIG_GETPCACHE 15 /* sqlite3_pcache_methods* */ 1809 #define SQLITE_CONFIG_GETPCACHE 15 /* sqlite3_pcache_methods* */ > 1810 #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */ 1786 1811 1787 /* 1812 /* 1788 ** CAPI3REF: Configuration Options 1813 ** CAPI3REF: Configuration Options 1789 ** EXPERIMENTAL 1814 ** EXPERIMENTAL 1790 ** 1815 ** 1791 ** These constants are the available integer configuration options that 1816 ** These constants are the available integer configuration options that 1792 ** can be passed as the second argument to the [sqlite3_db_config()] interface. 1817 ** can be passed as the second argument to the [sqlite3_db_config()] interface. ................................................................................................................................................................................ 4181 ); 4206 ); 4182 SQLITE_API int sqlite3_collation_needed16( 4207 SQLITE_API int sqlite3_collation_needed16( 4183 sqlite3*, 4208 sqlite3*, 4184 void*, 4209 void*, 4185 void(*)(void*,sqlite3*,int eTextRep,const void*) 4210 void(*)(void*,sqlite3*,int eTextRep,const void*) 4186 ); 4211 ); 4187 4212 > 4213 #if SQLITE_HAS_CODEC 4188 /* 4214 /* 4189 ** Specify the key for an encrypted database. This routine should be 4215 ** Specify the key for an encrypted database. This routine should be 4190 ** called right after sqlite3_open(). 4216 ** called right after sqlite3_open(). 4191 ** 4217 ** 4192 ** The code to implement this API is not available in the public release 4218 ** The code to implement this API is not available in the public release 4193 ** of SQLite. 4219 ** of SQLite. 4194 */ 4220 */ ................................................................................................................................................................................ 4206 ** of SQLite. 4232 ** of SQLite. 4207 */ 4233 */ 4208 SQLITE_API int sqlite3_rekey( 4234 SQLITE_API int sqlite3_rekey( 4209 sqlite3 *db, /* Database to be rekeyed */ 4235 sqlite3 *db, /* Database to be rekeyed */ 4210 const void *pKey, int nKey /* The new key */ 4236 const void *pKey, int nKey /* The new key */ 4211 ); 4237 ); 4212 4238 > 4239 /* > 4240 ** Specify the activation key for a SEE database. Unless > 4241 ** activated, none of the SEE routines will work. > 4242 */ > 4243 SQLITE_API void sqlite3_activate_see( > 4244 const char *zPassPhrase /* Activation phrase */ > 4245 ); > 4246 #endif > 4247 > 4248 #ifdef SQLITE_ENABLE_CEROD > 4249 /* > 4250 ** Specify the activation key for a CEROD database. Unless > 4251 ** activated, none of the CEROD routines will work. > 4252 */ > 4253 SQLITE_API void sqlite3_activate_cerod( > 4254 const char *zPassPhrase /* Activation phrase */ > 4255 ); > 4256 #endif > 4257 4213 /* 4258 /* 4214 ** CAPI3REF: Suspend Execution For A Short Time 4259 ** CAPI3REF: Suspend Execution For A Short Time 4215 ** 4260 ** 4216 ** ^The sqlite3_sleep() function causes the current thread to suspend execution 4261 ** ^The sqlite3_sleep() function causes the current thread to suspend execution 4217 ** for at least a number of milliseconds specified in its parameter. 4262 ** for at least a number of milliseconds specified in its parameter. 4218 ** 4263 ** 4219 ** ^If the operating system does not support sleep requests with 4264 ** ^If the operating system does not support sleep requests with ................................................................................................................................................................................ 6167 ** ^The [sqlite3_strnicmp()] API allows applications and extensions to 6212 ** ^The [sqlite3_strnicmp()] API allows applications and extensions to 6168 ** compare the contents of two buffers containing UTF-8 strings in a 6213 ** compare the contents of two buffers containing UTF-8 strings in a 6169 ** case-indendent fashion, using the same definition of case independence 6214 ** case-indendent fashion, using the same definition of case independence 6170 ** that SQLite uses internally when comparing identifiers. 6215 ** that SQLite uses internally when comparing identifiers. 6171 */ 6216 */ 6172 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int); 6217 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int); 6173 6218 > 6219 /* > 6220 ** CAPI3REF: Error Logging Interface > 6221 ** EXPERIMENTAL > 6222 ** > 6223 ** ^The [sqlite3_log()] interface writes a message into the error log > 6224 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()]. > 6225 ** ^If logging is enabled, the zFormat string and subsequent arguments are > 6226 ** passed through to [sqlite3_vmprintf()] to generate the final output string. > 6227 ** > 6228 ** The sqlite3_log() interface is intended for use by extensions such as > 6229 ** virtual tables, collating functions, and SQL functions. While there is > 6230 ** nothing to prevent an application from calling sqlite3_log(), doing so > 6231 ** is considered bad form. > 6232 ** > 6233 ** The zFormat string must not be NULL. > 6234 ** > 6235 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine > 6236 ** will not use dynamically allocated memory. The log message is stored in > 6237 ** a fixed-length buffer on the stack. If the log message is longer than > 6238 ** a few hundred characters, it will be truncated to the length of the > 6239 ** buffer. > 6240 */ > 6241 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...); > 6242 6174 /* 6243 /* 6175 ** Undo the hack that converts floating point types to integer for 6244 ** Undo the hack that converts floating point types to integer for 6176 ** builds on processors without floating point support. 6245 ** builds on processors without floating point support. 6177 */ 6246 */ 6178 #ifdef SQLITE_OMIT_FLOATING_POINT 6247 #ifdef SQLITE_OMIT_FLOATING_POINT 6179 # undef double 6248 # undef double 6180 #endif 6249 #endif ................................................................................................................................................................................ 6480 */ 6549 */ 6481 #ifdef SQLITE_OMIT_TEMPDB 6550 #ifdef SQLITE_OMIT_TEMPDB 6482 #define OMIT_TEMPDB 1 6551 #define OMIT_TEMPDB 1 6483 #else 6552 #else 6484 #define OMIT_TEMPDB 0 6553 #define OMIT_TEMPDB 0 6485 #endif 6554 #endif 6486 6555 6487 /* < 6488 ** If the following macro is set to 1, then NULL values are considered < 6489 ** distinct when determining whether or not two entries are the same < 6490 ** in a UNIQUE index. This is the way PostgreSQL, Oracle, DB2, MySQL, < 6491 ** OCELOT, and Firebird all work. The SQL92 spec explicitly says this < 6492 ** is the way things are suppose to work. < 6493 ** < 6494 ** If the following macro is set to 0, the NULLs are indistinct for < 6495 ** a UNIQUE index. In this mode, you can only have a single NULL entry < 6496 ** for a column declared UNIQUE. This is the way Informix and SQL Server < 6497 ** work. < 6498 */ < 6499 #define NULL_DISTINCT_FOR_UNIQUE 1 < 6500 < 6501 /* 6556 /* 6502 ** The "file format" number is an integer that is incremented whenever 6557 ** The "file format" number is an integer that is incremented whenever 6503 ** the VDBE-level file format changes. The following macros define the 6558 ** the VDBE-level file format changes. The following macros define the 6504 ** the default file format for new databases and the maximum file format 6559 ** the default file format for new databases and the maximum file format 6505 ** that the library can read. 6560 ** that the library can read. 6506 */ 6561 */ 6507 #define SQLITE_MAX_FILE_FORMAT 4 6562 #define SQLITE_MAX_FILE_FORMAT 4 6508 #ifndef SQLITE_DEFAULT_FILE_FORMAT 6563 #ifndef SQLITE_DEFAULT_FILE_FORMAT 6509 # define SQLITE_DEFAULT_FILE_FORMAT 1 6564 # define SQLITE_DEFAULT_FILE_FORMAT 1 6510 #endif 6565 #endif 6511 6566 > 6567 /* > 6568 ** Determine whether triggers are recursive by default. This can be > 6569 ** changed at run-time using a pragma. > 6570 */ 6512 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS 6571 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS 6513 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0 6572 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0 6514 #endif 6573 #endif 6515 6574 6516 /* 6575 /* 6517 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified 6576 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified 6518 ** on the command-line 6577 ** on the command-line ................................................................................................................................................................................ 6749 /* 6808 /* 6750 ** Forward references to structures 6809 ** Forward references to structures 6751 */ 6810 */ 6752 typedef struct AggInfo AggInfo; 6811 typedef struct AggInfo AggInfo; 6753 typedef struct AuthContext AuthContext; 6812 typedef struct AuthContext AuthContext; 6754 typedef struct AutoincInfo AutoincInfo; 6813 typedef struct AutoincInfo AutoincInfo; 6755 typedef struct Bitvec Bitvec; 6814 typedef struct Bitvec Bitvec; 6756 typedef struct RowSet RowSet; < 6757 typedef struct CollSeq CollSeq; 6815 typedef struct CollSeq CollSeq; 6758 typedef struct Column Column; 6816 typedef struct Column Column; 6759 typedef struct Db Db; 6817 typedef struct Db Db; 6760 typedef struct Schema Schema; 6818 typedef struct Schema Schema; 6761 typedef struct Expr Expr; 6819 typedef struct Expr Expr; 6762 typedef struct ExprList ExprList; 6820 typedef struct ExprList ExprList; 6763 typedef struct ExprSpan ExprSpan; 6821 typedef struct ExprSpan ExprSpan; ................................................................................................................................................................................ 6770 typedef struct KeyClass KeyClass; 6828 typedef struct KeyClass KeyClass; 6771 typedef struct KeyInfo KeyInfo; 6829 typedef struct KeyInfo KeyInfo; 6772 typedef struct Lookaside Lookaside; 6830 typedef struct Lookaside Lookaside; 6773 typedef struct LookasideSlot LookasideSlot; 6831 typedef struct LookasideSlot LookasideSlot; 6774 typedef struct Module Module; 6832 typedef struct Module Module; 6775 typedef struct NameContext NameContext; 6833 typedef struct NameContext NameContext; 6776 typedef struct Parse Parse; 6834 typedef struct Parse Parse; > 6835 typedef struct RowSet RowSet; 6777 typedef struct Savepoint Savepoint; 6836 typedef struct Savepoint Savepoint; 6778 typedef struct Select Select; 6837 typedef struct Select Select; 6779 typedef struct SrcList SrcList; 6838 typedef struct SrcList SrcList; 6780 typedef struct StrAccum StrAccum; 6839 typedef struct StrAccum StrAccum; 6781 typedef struct Table Table; 6840 typedef struct Table Table; 6782 typedef struct TableLock TableLock; 6841 typedef struct TableLock TableLock; 6783 typedef struct Token Token; 6842 typedef struct Token Token; > 6843 typedef struct Trigger Trigger; 6784 typedef struct TriggerPrg TriggerPrg; 6844 typedef struct TriggerPrg TriggerPrg; 6785 typedef struct TriggerStep TriggerStep; 6845 typedef struct TriggerStep TriggerStep; 6786 typedef struct Trigger Trigger; < 6787 typedef struct UnpackedRecord UnpackedRecord; 6846 typedef struct UnpackedRecord UnpackedRecord; 6788 typedef struct VTable VTable; 6847 typedef struct VTable VTable; 6789 typedef struct Walker Walker; 6848 typedef struct Walker Walker; 6790 typedef struct WherePlan WherePlan; 6849 typedef struct WherePlan WherePlan; 6791 typedef struct WhereInfo WhereInfo; 6850 typedef struct WhereInfo WhereInfo; 6792 typedef struct WhereLevel WhereLevel; 6851 typedef struct WhereLevel WhereLevel; 6793 6852 ................................................................................................................................................................................ 6877 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*); 6936 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*); 6878 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int); 6937 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int); 6879 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int); 6938 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int); 6880 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*); 6939 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*); 6881 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve 6940 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve 6882 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*); 6941 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*); 6883 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int); 6942 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int); > 6943 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int); 6884 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*); 6944 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*); 6885 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int); 6945 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int); 6886 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *); 6946 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *); 6887 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int); 6947 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int); 6888 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster); 6948 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster); 6889 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*); 6949 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*); 6890 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*); 6950 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*); ................................................................................................................................................................................ 7407 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5); 7467 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5); 7408 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr); 7468 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr); 7409 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N); 7469 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N); 7410 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N) 7470 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N) 7411 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int); 7471 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int); 7412 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int); 7472 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int); 7413 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*); 7473 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*); > 7474 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*); 7414 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*); 7475 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*); 7415 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int); 7476 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int); 7416 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*); 7477 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*); 7417 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int); 7478 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int); 7418 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*); 7479 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*); 7419 #ifdef SQLITE_DEBUG 7480 #ifdef SQLITE_DEBUG 7420 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int); 7481 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int); ................................................................................................................................................................................ 8180 #ifndef SQLITE_OMIT_VIRTUALTABLE 8241 #ifndef SQLITE_OMIT_VIRTUALTABLE 8181 sqlite3 *db; /* "Owner" connection. See comment above */ 8242 sqlite3 *db; /* "Owner" connection. See comment above */ 8182 #endif 8243 #endif 8183 }; 8244 }; 8184 8245 8185 /* 8246 /* 8186 ** These macros can be used to test, set, or clear bits in the 8247 ** These macros can be used to test, set, or clear bits in the 8187 ** Db.flags field. | 8248 ** Db.pSchema->flags field. 8188 */ 8249 */ 8189 #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P)) 8250 #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P)) 8190 #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0) 8251 #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0) 8191 #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P) 8252 #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P) 8192 #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P) 8253 #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P) 8193 8254 8194 /* 8255 /* 8195 ** Allowed values for the DB.flags field. | 8256 ** Allowed values for the DB.pSchema->flags field. 8196 ** 8257 ** 8197 ** The DB_SchemaLoaded flag is set after the database schema has been 8258 ** The DB_SchemaLoaded flag is set after the database schema has been 8198 ** read into internal hash tables. 8259 ** read into internal hash tables. 8199 ** 8260 ** 8200 ** DB_UnresetViews means that one or more views have column names that 8261 ** DB_UnresetViews means that one or more views have column names that 8201 ** have been filled out. If the schema changes, these column names might 8262 ** have been filled out. If the schema changes, these column names might 8202 ** changes and so the view will need to be reset. 8263 ** changes and so the view will need to be reset. ................................................................................................................................................................................ 8252 ** Collisions are on the FuncDef.pHash chain. 8313 ** Collisions are on the FuncDef.pHash chain. 8253 */ 8314 */ 8254 struct FuncDefHash { 8315 struct FuncDefHash { 8255 FuncDef *a[23]; /* Hash table for functions */ 8316 FuncDef *a[23]; /* Hash table for functions */ 8256 }; 8317 }; 8257 8318 8258 /* 8319 /* 8259 ** Each database is an instance of the following structure. | 8320 ** Each database connection is an instance of the following structure. 8260 ** 8321 ** 8261 ** The sqlite.lastRowid records the last insert rowid generated by an 8322 ** The sqlite.lastRowid records the last insert rowid generated by an 8262 ** insert statement. Inserts on views do not affect its value. Each 8323 ** insert statement. Inserts on views do not affect its value. Each 8263 ** trigger has its own context, so that lastRowid can be updated inside 8324 ** trigger has its own context, so that lastRowid can be updated inside 8264 ** triggers as usual. The previous value will be restored once the trigger 8325 ** triggers as usual. The previous value will be restored once the trigger 8265 ** exits. Upon entering a before or instead of trigger, lastRowid is no 8326 ** exits. Upon entering a before or instead of trigger, lastRowid is no 8266 ** longer (since after version 2.8.12) reset to -1. 8327 ** longer (since after version 2.8.12) reset to -1. ................................................................................................................................................................................ 8291 int errMask; /* & result codes with this before returning */ 8352 int errMask; /* & result codes with this before returning */ 8292 u8 autoCommit; /* The auto-commit flag. */ 8353 u8 autoCommit; /* The auto-commit flag. */ 8293 u8 temp_store; /* 1: file 2: memory 0: default */ 8354 u8 temp_store; /* 1: file 2: memory 0: default */ 8294 u8 mallocFailed; /* True if we have seen a malloc failure */ 8355 u8 mallocFailed; /* True if we have seen a malloc failure */ 8295 u8 dfltLockMode; /* Default locking-mode for attached dbs */ 8356 u8 dfltLockMode; /* Default locking-mode for attached dbs */ 8296 u8 dfltJournalMode; /* Default journal mode for attached dbs */ 8357 u8 dfltJournalMode; /* Default journal mode for attached dbs */ 8297 signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */ 8358 signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */ > 8359 u8 suppressErr; /* Do not issue error messages if true */ 8298 int nextPagesize; /* Pagesize after VACUUM if >0 */ 8360 int nextPagesize; /* Pagesize after VACUUM if >0 */ 8299 int nTable; /* Number of tables in the database */ 8361 int nTable; /* Number of tables in the database */ 8300 CollSeq *pDfltColl; /* The default collating sequence (BINARY) */ 8362 CollSeq *pDfltColl; /* The default collating sequence (BINARY) */ 8301 i64 lastRowid; /* ROWID of most recent insert (see above) */ 8363 i64 lastRowid; /* ROWID of most recent insert (see above) */ 8302 u32 magic; /* Magic number for detect library misuse */ 8364 u32 magic; /* Magic number for detect library misuse */ 8303 int nChange; /* Value returned by sqlite3_changes() */ 8365 int nChange; /* Value returned by sqlite3_changes() */ 8304 int nTotalChange; /* Value returned by sqlite3_total_changes() */ 8366 int nTotalChange; /* Value returned by sqlite3_total_changes() */ ................................................................................................................................................................................ 9867 int isInit; /* True after initialization has finished */ 9929 int isInit; /* True after initialization has finished */ 9868 int inProgress; /* True while initialization in progress */ 9930 int inProgress; /* True while initialization in progress */ 9869 int isMutexInit; /* True after mutexes are initialized */ 9931 int isMutexInit; /* True after mutexes are initialized */ 9870 int isMallocInit; /* True after malloc is initialized */ 9932 int isMallocInit; /* True after malloc is initialized */ 9871 int isPCacheInit; /* True after malloc is initialized */ 9933 int isPCacheInit; /* True after malloc is initialized */ 9872 sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */ 9934 sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */ 9873 int nRefInitMutex; /* Number of users of pInitMutex */ 9935 int nRefInitMutex; /* Number of users of pInitMutex */ > 9936 void (*xLog)(void*,int,const char*); /* Function for logging */ > 9937 void *pLogArg; /* First argument to xLog() */ 9874 }; 9938 }; 9875 9939 9876 /* 9940 /* 9877 ** Context pointer passed down through the tree-walk. 9941 ** Context pointer passed down through the tree-walk. 9878 */ 9942 */ 9879 struct Walker { 9943 struct Walker { 9880 int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */ 9944 int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */ ................................................................................................................................................................................ 9908 #define SQLITE_SKIP_UTF8(zIn) { \ 9972 #define SQLITE_SKIP_UTF8(zIn) { \ 9909 if( (*(zIn++))>=0xc0 ){ \ 9973 if( (*(zIn++))>=0xc0 ){ \ 9910 while( (*zIn & 0xc0)==0x80 ){ zIn++; } \ 9974 while( (*zIn & 0xc0)==0x80 ){ zIn++; } \ 9911 } \ 9975 } \ 9912 } 9976 } 9913 9977 9914 /* 9978 /* 9915 ** The SQLITE_CORRUPT_BKPT macro can be either a constant (for production | 9979 ** The SQLITE_*_BKPT macros are substitutes for the error codes with 9916 ** builds) or a function call (for debugging). If it is a function call, | 9980 ** the same name but without the _BKPT suffix. These macros invoke 9917 ** it allows the operator to set a breakpoint at the spot where database | 9981 ** routines that report the line-number on which the error originated 9918 ** corruption is first detected. | 9982 ** using sqlite3_log(). The routines also provide a convenient place > 9983 ** to set a debugger breakpoint. 9919 */ 9984 */ 9920 #ifdef SQLITE_DEBUG < 9921 SQLITE_PRIVATE int sqlite3Corrupt(void); | 9985 SQLITE_PRIVATE int sqlite3CorruptError(int); > 9986 SQLITE_PRIVATE int sqlite3MisuseError(int); > 9987 SQLITE_PRIVATE int sqlite3CantopenError(int); 9922 # define SQLITE_CORRUPT_BKPT sqlite3Corrupt() | 9988 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__) 9923 #else < > 9989 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__) > 9990 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__) > 9991 > 9992 > 9993 /* > 9994 ** FTS4 is really an extension for FTS3. It is enabled using the > 9995 ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all > 9996 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3. > 9997 */ > 9998 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3) 9924 # define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT | 9999 # define SQLITE_ENABLE_FTS3 9925 #endif 10000 #endif 9926 10001 9927 /* 10002 /* 9928 ** The ctype.h header is needed for non-ASCII systems. It is also 10003 ** The ctype.h header is needed for non-ASCII systems. It is also 9929 ** needed by FTS3 when FTS3 is included in the amalgamation. 10004 ** needed by FTS3 when FTS3 is included in the amalgamation. 9930 */ 10005 */ 9931 #if !defined(SQLITE_ASCII) || \ 10006 #if !defined(SQLITE_ASCII) || \ ................................................................................................................................................................................ 10019 SQLITE_PRIVATE int sqlite3MutexEnd(void); 10094 SQLITE_PRIVATE int sqlite3MutexEnd(void); 10020 #endif 10095 #endif 10021 10096 10022 SQLITE_PRIVATE int sqlite3StatusValue(int); 10097 SQLITE_PRIVATE int sqlite3StatusValue(int); 10023 SQLITE_PRIVATE void sqlite3StatusAdd(int, int); 10098 SQLITE_PRIVATE void sqlite3StatusAdd(int, int); 10024 SQLITE_PRIVATE void sqlite3StatusSet(int, int); 10099 SQLITE_PRIVATE void sqlite3StatusSet(int, int); 10025 10100 > 10101 #ifndef SQLITE_OMIT_FLOATING_POINT 10026 SQLITE_PRIVATE int sqlite3IsNaN(double); | 10102 SQLITE_PRIVATE int sqlite3IsNaN(double); > 10103 #else > 10104 # define sqlite3IsNaN(X) 0 > 10105 #endif 10027 10106 10028 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list); 10107 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list); 10029 #ifndef SQLITE_OMIT_TRACE 10108 #ifndef SQLITE_OMIT_TRACE 10030 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...); 10109 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...); 10031 #endif 10110 #endif 10032 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...); 10111 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...); 10033 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list); 10112 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list); ................................................................................................................................................................................ 10036 SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...); 10115 SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...); 10037 #endif 10116 #endif 10038 #if defined(SQLITE_TEST) 10117 #if defined(SQLITE_TEST) 10039 SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*); 10118 SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*); 10040 #endif 10119 #endif 10041 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...); 10120 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...); 10042 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...); 10121 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...); 10043 SQLITE_PRIVATE void sqlite3ErrorClear(Parse*); < 10044 SQLITE_PRIVATE int sqlite3Dequote(char*); 10122 SQLITE_PRIVATE int sqlite3Dequote(char*); 10045 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int); 10123 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int); 10046 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **); 10124 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **); 10047 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*); 10125 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*); 10048 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*); 10126 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*); 10049 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int); 10127 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int); 10050 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int); 10128 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int); ................................................................................................................................................................................ 10206 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*); 10284 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*); 10207 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int); 10285 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int); 10208 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*); 10286 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*); 10209 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int) 10287 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int) 10210 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*); 10288 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*); 10211 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void); 10289 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void); 10212 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void); 10290 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void); 10213 #ifdef SQLITE_DEBUG < 10214 SQLITE_PRIVATE int sqlite3SafetyOn(sqlite3*); < 10215 SQLITE_PRIVATE int sqlite3SafetyOff(sqlite3*); < 10216 #else < 10217 # define sqlite3SafetyOn(A) 0 < 10218 # define sqlite3SafetyOff(A) 0 < 10219 #endif < 10220 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*); 10291 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*); 10221 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*); 10292 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*); 10222 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int); 10293 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int); 10223 10294 10224 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) 10295 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) 10225 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int); 10296 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int); 10226 #endif 10297 #endif ................................................................................................................................................................................ 10348 10419 10349 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8); 10420 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8); 10350 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8); 10421 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8); 10351 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 10422 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 10352 void(*)(void*)); 10423 void(*)(void*)); 10353 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*); 10424 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*); 10354 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *); 10425 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *); 10355 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int); | 10426 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8); 10356 #ifdef SQLITE_ENABLE_STAT2 10427 #ifdef SQLITE_ENABLE_STAT2 10357 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *); 10428 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *); 10358 #endif 10429 #endif 10359 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value 10430 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value 10360 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8); 10431 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8); 10361 #ifndef SQLITE_AMALGAMATION 10432 #ifndef SQLITE_AMALGAMATION 10362 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[]; 10433 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[]; ................................................................................................................................................................................ 10748 0, /* isInit */ 10819 0, /* isInit */ 10749 0, /* inProgress */ 10820 0, /* inProgress */ 10750 0, /* isMutexInit */ 10821 0, /* isMutexInit */ 10751 0, /* isMallocInit */ 10822 0, /* isMallocInit */ 10752 0, /* isPCacheInit */ 10823 0, /* isPCacheInit */ 10753 0, /* pInitMutex */ 10824 0, /* pInitMutex */ 10754 0, /* nRefInitMutex */ 10825 0, /* nRefInitMutex */ > 10826 0, /* xLog */ > 10827 0, /* pLogArg */ 10755 }; 10828 }; 10756 10829 10757 10830 10758 /* 10831 /* 10759 ** Hash table for global functions - functions common to all 10832 ** Hash table for global functions - functions common to all 10760 ** database connections. After initialization, this table is 10833 ** database connections. After initialization, this table is 10761 ** read-only. 10834 ** read-only. ................................................................................................................................................................................ 10872 ** This implementation assumes that reading or writing an aligned 10945 ** This implementation assumes that reading or writing an aligned 10873 ** 32-bit integer is an atomic operation. If that assumption is not true, 10946 ** 32-bit integer is an atomic operation. If that assumption is not true, 10874 ** then this routine is not threadsafe. 10947 ** then this routine is not threadsafe. 10875 */ 10948 */ 10876 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetF 10949 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetF 10877 wsdStatInit; 10950 wsdStatInit; 10878 if( op<0 || op>=ArraySize(wsdStat.nowValue) ){ 10951 if( op<0 || op>=ArraySize(wsdStat.nowValue) ){ 10879 return SQLITE_MISUSE; | 10952 return SQLITE_MISUSE_BKPT; 10880 } 10953 } 10881 *pCurrent = wsdStat.nowValue[op]; 10954 *pCurrent = wsdStat.nowValue[op]; 10882 *pHighwater = wsdStat.mxValue[op]; 10955 *pHighwater = wsdStat.mxValue[op]; 10883 if( resetFlag ){ 10956 if( resetFlag ){ 10884 wsdStat.mxValue[op] = wsdStat.nowValue[op]; 10957 wsdStat.mxValue[op] = wsdStat.nowValue[op]; 10885 } 10958 } 10886 return SQLITE_OK; 10959 return SQLITE_OK; ................................................................................................................................................................................ 12001 FUNCTION(datetime, -1, 0, 0, datetimeFunc ), 12074 FUNCTION(datetime, -1, 0, 0, datetimeFunc ), 12002 FUNCTION(strftime, -1, 0, 0, strftimeFunc ), 12075 FUNCTION(strftime, -1, 0, 0, strftimeFunc ), 12003 FUNCTION(current_time, 0, 0, 0, ctimeFunc ), 12076 FUNCTION(current_time, 0, 0, 0, ctimeFunc ), 12004 FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc), 12077 FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc), 12005 FUNCTION(current_date, 0, 0, 0, cdateFunc ), 12078 FUNCTION(current_date, 0, 0, 0, cdateFunc ), 12006 #else 12079 #else 12007 STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc), 12080 STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc), 12008 STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d", 0, currentTimeFunc), | 12081 STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc), 12009 STR_FUNCTION(current_date, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc), | 12082 STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc), 12010 #endif 12083 #endif 12011 }; 12084 }; 12012 int i; 12085 int i; 12013 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions); 12086 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions); 12014 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs); 12087 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs); 12015 12088 12016 for(i=0; i<ArraySize(aDateTimeFuncs); i++){ 12089 for(i=0; i<ArraySize(aDateTimeFuncs); i++){ ................................................................................................................................................................................ 12129 const char *zPath, 12202 const char *zPath, 12130 sqlite3_file *pFile, 12203 sqlite3_file *pFile, 12131 int flags, 12204 int flags, 12132 int *pFlagsOut 12205 int *pFlagsOut 12133 ){ 12206 ){ 12134 int rc; 12207 int rc; 12135 DO_OS_MALLOC_TEST(0); 12208 DO_OS_MALLOC_TEST(0); 12136 /* 0x7f1f is a mask of SQLITE_OPEN_ flags that are valid to be passed | 12209 /* 0x7f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed 12137 ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example, 12210 ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example, 12138 ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before 12211 ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before 12139 ** reaching the VFS. */ 12212 ** reaching the VFS. */ 12140 rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x7f1f, pFlagsOut); | 12213 rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x7f3f, pFlagsOut); 12141 assert( rc==SQLITE_OK || pFile->pMethods==0 ); 12214 assert( rc==SQLITE_OK || pFile->pMethods==0 ); 12142 return rc; 12215 return rc; 12143 } 12216 } 12144 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dir 12217 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dir 12145 return pVfs->xDelete(pVfs, zPath, dirSync); 12218 return pVfs->xDelete(pVfs, zPath, dirSync); 12146 } 12219 } 12147 SQLITE_PRIVATE int sqlite3OsAccess( 12220 SQLITE_PRIVATE int sqlite3OsAccess( ................................................................................................................................................................................ 12508 sqlite3_int64 *p; 12581 sqlite3_int64 *p; 12509 assert( nByte>0 ); 12582 assert( nByte>0 ); 12510 nByte = ROUND8(nByte); 12583 nByte = ROUND8(nByte); 12511 p = malloc( nByte+8 ); 12584 p = malloc( nByte+8 ); 12512 if( p ){ 12585 if( p ){ 12513 p[0] = nByte; 12586 p[0] = nByte; 12514 p++; 12587 p++; > 12588 }else{ > 12589 testcase( sqlite3GlobalConfig.xLog!=0 ); > 12590 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte); 12515 } 12591 } 12516 return (void *)p; 12592 return (void *)p; 12517 } 12593 } 12518 12594 12519 /* 12595 /* 12520 ** Like free() but works for allocations obtained from sqlite3MemMalloc() 12596 ** Like free() but works for allocations obtained from sqlite3MemMalloc() 12521 ** or sqlite3MemRealloc(). 12597 ** or sqlite3MemRealloc(). ................................................................................................................................................................................ 12526 */ 12602 */ 12527 static void sqlite3MemFree(void *pPrior){ 12603 static void sqlite3MemFree(void *pPrior){ 12528 sqlite3_int64 *p = (sqlite3_int64*)pPrior; 12604 sqlite3_int64 *p = (sqlite3_int64*)pPrior; 12529 assert( pPrior!=0 ); 12605 assert( pPrior!=0 ); 12530 p--; 12606 p--; 12531 free(p); 12607 free(p); 12532 } 12608 } > 12609 > 12610 /* > 12611 ** Report the allocated size of a prior return from xMalloc() > 12612 ** or xRealloc(). > 12613 */ > 12614 static int sqlite3MemSize(void *pPrior){ > 12615 sqlite3_int64 *p; > 12616 if( pPrior==0 ) return 0; > 12617 p = (sqlite3_int64*)pPrior; > 12618 p--; > 12619 return (int)p[0]; > 12620 } 12533 12621 12534 /* 12622 /* 12535 ** Like realloc(). Resize an allocation previously obtained from 12623 ** Like realloc(). Resize an allocation previously obtained from 12536 ** sqlite3MemMalloc(). 12624 ** sqlite3MemMalloc(). 12537 ** 12625 ** 12538 ** For this low-level interface, we know that pPrior!=0. Cases where 12626 ** For this low-level interface, we know that pPrior!=0. Cases where 12539 ** pPrior==0 while have been intercepted by higher-level routine and 12627 ** pPrior==0 while have been intercepted by higher-level routine and ................................................................................................................................................................................ 12541 ** cases where nByte<=0 will have been intercepted by higher-level 12629 ** cases where nByte<=0 will have been intercepted by higher-level 12542 ** routines and redirected to xFree. 12630 ** routines and redirected to xFree. 12543 */ 12631 */ 12544 static void *sqlite3MemRealloc(void *pPrior, int nByte){ 12632 static void *sqlite3MemRealloc(void *pPrior, int nByte){ 12545 sqlite3_int64 *p = (sqlite3_int64*)pPrior; 12633 sqlite3_int64 *p = (sqlite3_int64*)pPrior; 12546 assert( pPrior!=0 && nByte>0 ); 12634 assert( pPrior!=0 && nByte>0 ); 12547 nByte = ROUND8(nByte); 12635 nByte = ROUND8(nByte); 12548 p = (sqlite3_int64*)pPrior; < 12549 p--; 12636 p--; 12550 p = realloc(p, nByte+8 ); 12637 p = realloc(p, nByte+8 ); 12551 if( p ){ 12638 if( p ){ 12552 p[0] = nByte; 12639 p[0] = nByte; 12553 p++; 12640 p++; > 12641 }else{ > 12642 testcase( sqlite3GlobalConfig.xLog!=0 ); > 12643 sqlite3_log(SQLITE_NOMEM, > 12644 "failed memory resize %u to %u bytes", > 12645 sqlite3MemSize(pPrior), nByte); 12554 } 12646 } 12555 return (void*)p; 12647 return (void*)p; 12556 } 12648 } 12557 12649 12558 /* < 12559 ** Report the allocated size of a prior return from xMalloc() < 12560 ** or xRealloc(). < 12561 */ < 12562 static int sqlite3MemSize(void *pPrior){ < 12563 sqlite3_int64 *p; < 12564 if( pPrior==0 ) return 0; < 12565 p = (sqlite3_int64*)pPrior; < 12566 p--; < 12567 return (int)p[0]; < 12568 } < 12569 < 12570 /* 12650 /* 12571 ** Round up a request size to the next valid allocation size. 12651 ** Round up a request size to the next valid allocation size. 12572 */ 12652 */ 12573 static int sqlite3MemRoundup(int n){ 12653 static int sqlite3MemRoundup(int n){ 12574 return ROUND8(n); 12654 return ROUND8(n); 12575 } 12655 } 12576 12656 ................................................................................................................................................................................ 12910 /* 12990 /* 12911 ** Free memory. 12991 ** Free memory. 12912 */ 12992 */ 12913 static void sqlite3MemFree(void *pPrior){ 12993 static void sqlite3MemFree(void *pPrior){ 12914 struct MemBlockHdr *pHdr; 12994 struct MemBlockHdr *pHdr; 12915 void **pBt; 12995 void **pBt; 12916 char *z; 12996 char *z; 12917 assert( sqlite3GlobalConfig.bMemstat || mem.mutex!=0 ); | 12997 assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 > 12998 || mem.mutex!=0 ); 12918 pHdr = sqlite3MemsysGetHeader(pPrior); 12999 pHdr = sqlite3MemsysGetHeader(pPrior); 12919 pBt = (void**)pHdr; 13000 pBt = (void**)pHdr; 12920 pBt -= pHdr->nBacktraceSlots; 13001 pBt -= pHdr->nBacktraceSlots; 12921 sqlite3_mutex_enter(mem.mutex); 13002 sqlite3_mutex_enter(mem.mutex); 12922 if( pHdr->pPrev ){ 13003 if( pHdr->pPrev ){ 12923 assert( pHdr->pPrev->pNext==pHdr ); 13004 assert( pHdr->pPrev->pNext==pHdr ); 12924 pHdr->pPrev->pNext = pHdr->pNext; 13005 pHdr->pPrev->pNext = pHdr->pNext; ................................................................................................................................................................................ 14037 for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){ 14118 for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){ 14038 14119 14039 /* Make sure mem5.aiFreelist[iLogsize] contains at least one free 14120 /* Make sure mem5.aiFreelist[iLogsize] contains at least one free 14040 ** block. If not, then split a block of the next larger power of 14121 ** block. If not, then split a block of the next larger power of 14041 ** two in order to create a new free block of size iLogsize. 14122 ** two in order to create a new free block of size iLogsize. 14042 */ 14123 */ 14043 for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){} 14124 for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){} 14044 if( iBin>LOGMAX ) return 0; | 14125 if( iBin>LOGMAX ){ > 14126 testcase( sqlite3GlobalConfig.xLog!=0 ); > 14127 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte); > 14128 return 0; > 14129 } 14045 i = memsys5UnlinkFirst(iBin); 14130 i = memsys5UnlinkFirst(iBin); 14046 while( iBin>iLogsize ){ 14131 while( iBin>iLogsize ){ 14047 int newSize; 14132 int newSize; 14048 14133 14049 iBin--; 14134 iBin--; 14050 newSize = 1 << iBin; 14135 newSize = 1 << iBin; 14051 mem5.aCtrl[i+newSize] = CTRL_FREE | iBin; 14136 mem5.aCtrl[i+newSize] = CTRL_FREE | iBin; ................................................................................................................................................................................ 15314 ** Each recursive mutex is an instance of the following structure. 15399 ** Each recursive mutex is an instance of the following structure. 15315 */ 15400 */ 15316 struct sqlite3_mutex { 15401 struct sqlite3_mutex { 15317 CRITICAL_SECTION mutex; /* Mutex controlling the lock */ 15402 CRITICAL_SECTION mutex; /* Mutex controlling the lock */ 15318 int id; /* Mutex type */ 15403 int id; /* Mutex type */ 15319 int nRef; /* Number of enterances */ 15404 int nRef; /* Number of enterances */ 15320 DWORD owner; /* Thread holding this mutex */ 15405 DWORD owner; /* Thread holding this mutex */ > 15406 #ifdef SQLITE_DEBUG > 15407 int trace; /* True to trace changes */ > 15408 #endif 15321 }; 15409 }; > 15410 #define SQLITE_W32_MUTEX_INITIALIZER { 0 } > 15411 #ifdef SQLITE_DEBUG > 15412 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD) > 15413 #else > 15414 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD) > 15415 #endif 15322 15416 15323 /* 15417 /* 15324 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP, 15418 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP, 15325 ** or WinCE. Return false (zero) for Win95, Win98, or WinME. 15419 ** or WinCE. Return false (zero) for Win95, Win98, or WinME. 15326 ** 15420 ** 15327 ** Here is an interesting observation: Win95, Win98, and WinME lack 15421 ** Here is an interesting observation: Win95, Win98, and WinME lack 15328 ** the LockFileEx() API. But we can still statically link against that 15422 ** the LockFileEx() API. But we can still statically link against that ................................................................................................................................................................................ 15357 #ifdef SQLITE_DEBUG 15451 #ifdef SQLITE_DEBUG 15358 /* 15452 /* 15359 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are 15453 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are 15360 ** intended for use only inside assert() statements. 15454 ** intended for use only inside assert() statements. 15361 */ 15455 */ 15362 static int winMutexHeld(sqlite3_mutex *p){ 15456 static int winMutexHeld(sqlite3_mutex *p){ 15363 return p->nRef!=0 && p->owner==GetCurrentThreadId(); 15457 return p->nRef!=0 && p->owner==GetCurrentThreadId(); 15364 } 15458 } > 15459 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){ > 15460 return p->nRef==0 || p->owner!=tid; > 15461 } 15365 static int winMutexNotheld(sqlite3_mutex *p){ 15462 static int winMutexNotheld(sqlite3_mutex *p){ 15366 return p->nRef==0 || p->owner!=GetCurrentThreadId(); | 15463 DWORD tid = GetCurrentThreadId(); > 15464 return winMutexNotheld2(p, tid); 15367 } 15465 } 15368 #endif 15466 #endif 15369 15467 15370 15468 15371 /* 15469 /* 15372 ** Initialize and deinitialize the mutex subsystem. 15470 ** Initialize and deinitialize the mutex subsystem. 15373 */ 15471 */ 15374 static sqlite3_mutex winMutex_staticMutexes[6]; | 15472 static sqlite3_mutex winMutex_staticMutexes[6] = { > 15473 SQLITE3_MUTEX_INITIALIZER, > 15474 SQLITE3_MUTEX_INITIALIZER, > 15475 SQLITE3_MUTEX_INITIALIZER, > 15476 SQLITE3_MUTEX_INITIALIZER, > 15477 SQLITE3_MUTEX_INITIALIZER, > 15478 SQLITE3_MUTEX_INITIALIZER > 15479 }; 15375 static int winMutex_isInit = 0; 15480 static int winMutex_isInit = 0; 15376 /* As winMutexInit() and winMutexEnd() are called as part 15481 /* As winMutexInit() and winMutexEnd() are called as part 15377 ** of the sqlite3_initialize and sqlite3_shutdown() 15482 ** of the sqlite3_initialize and sqlite3_shutdown() 15378 ** processing, the "interlocked" magic is probably not 15483 ** processing, the "interlocked" magic is probably not 15379 ** strictly necessary. 15484 ** strictly necessary. 15380 */ 15485 */ 15381 static long winMutex_lock = 0; 15486 static long winMutex_lock = 0; ................................................................................................................................................................................ 15501 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can 15606 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can 15502 ** be entered multiple times by the same thread. In such cases the, 15607 ** be entered multiple times by the same thread. In such cases the, 15503 ** mutex must be exited an equal number of times before another thread 15608 ** mutex must be exited an equal number of times before another thread 15504 ** can enter. If the same thread tries to enter any other kind of mutex 15609 ** can enter. If the same thread tries to enter any other kind of mutex 15505 ** more than once, the behavior is undefined. 15610 ** more than once, the behavior is undefined. 15506 */ 15611 */ 15507 static void winMutexEnter(sqlite3_mutex *p){ 15612 static void winMutexEnter(sqlite3_mutex *p){ > 15613 DWORD tid = GetCurrentThreadId(); 15508 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) ); | 15614 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) ); 15509 EnterCriticalSection(&p->mutex); 15615 EnterCriticalSection(&p->mutex); 15510 p->owner = GetCurrentThreadId(); | 15616 p->owner = tid; 15511 p->nRef++; 15617 p->nRef++; > 15618 #ifdef SQLITE_DEBUG > 15619 if( p->trace ){ > 15620 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); 15512 } | 15621 } > 15622 #endif > 15623 } 15513 static int winMutexTry(sqlite3_mutex *p){ 15624 static int winMutexTry(sqlite3_mutex *p){ > 15625 #ifndef NDEBUG > 15626 DWORD tid = GetCurrentThreadId(); > 15627 #endif 15514 int rc = SQLITE_BUSY; 15628 int rc = SQLITE_BUSY; 15515 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) ); | 15629 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) ); 15516 /* 15630 /* 15517 ** The sqlite3_mutex_try() routine is very rarely used, and when it 15631 ** The sqlite3_mutex_try() routine is very rarely used, and when it 15518 ** is used it is merely an optimization. So it is OK for it to always 15632 ** is used it is merely an optimization. So it is OK for it to always 15519 ** fail. 15633 ** fail. 15520 ** 15634 ** 15521 ** The TryEnterCriticalSection() interface is only available on WinNT. 15635 ** The TryEnterCriticalSection() interface is only available on WinNT. 15522 ** And some windows compilers complain if you try to use it without 15636 ** And some windows compilers complain if you try to use it without 15523 ** first doing some #defines that prevent SQLite from building on Win98. 15637 ** first doing some #defines that prevent SQLite from building on Win98. 15524 ** For that reason, we will omit this optimization for now. See 15638 ** For that reason, we will omit this optimization for now. See 15525 ** ticket #2685. 15639 ** ticket #2685. 15526 */ 15640 */ 15527 #if 0 15641 #if 0 15528 if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){ 15642 if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){ 15529 p->owner = GetCurrentThreadId(); | 15643 p->owner = tid; 15530 p->nRef++; 15644 p->nRef++; 15531 rc = SQLITE_OK; 15645 rc = SQLITE_OK; 15532 } 15646 } 15533 #else 15647 #else 15534 UNUSED_PARAMETER(p); 15648 UNUSED_PARAMETER(p); > 15649 #endif > 15650 #ifdef SQLITE_DEBUG > 15651 if( rc==SQLITE_OK && p->trace ){ > 15652 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); > 15653 } 15535 #endif 15654 #endif 15536 return rc; 15655 return rc; 15537 } 15656 } 15538 15657 15539 /* 15658 /* 15540 ** The sqlite3_mutex_leave() routine exits a mutex that was 15659 ** The sqlite3_mutex_leave() routine exits a mutex that was 15541 ** previously entered by the same thread. The behavior 15660 ** previously entered by the same thread. The behavior 15542 ** is undefined if the mutex is not currently entered or 15661 ** is undefined if the mutex is not currently entered or 15543 ** is not currently allocated. SQLite will never do either. 15662 ** is not currently allocated. SQLite will never do either. 15544 */ 15663 */ 15545 static void winMutexLeave(sqlite3_mutex *p){ 15664 static void winMutexLeave(sqlite3_mutex *p){ > 15665 #ifndef NDEBUG > 15666 DWORD tid = GetCurrentThreadId(); > 15667 #endif 15546 assert( p->nRef>0 ); 15668 assert( p->nRef>0 ); 15547 assert( p->owner==GetCurrentThreadId() ); | 15669 assert( p->owner==tid ); 15548 p->nRef--; 15670 p->nRef--; 15549 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE ); 15671 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE ); 15550 LeaveCriticalSection(&p->mutex); 15672 LeaveCriticalSection(&p->mutex); > 15673 #ifdef SQLITE_DEBUG > 15674 if( p->trace ){ > 15675 printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); > 15676 } > 15677 #endif 15551 } 15678 } 15552 15679 15553 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){ 15680 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){ 15554 static sqlite3_mutex_methods sMutex = { 15681 static sqlite3_mutex_methods sMutex = { 15555 winMutexInit, 15682 winMutexInit, 15556 winMutexEnd, 15683 winMutexEnd, 15557 winMutexAlloc, 15684 winMutexAlloc, ................................................................................................................................................................................ 16742 } 16869 } 16743 length = (int)(&buf[etBUFSIZE-1]-bufpt); 16870 length = (int)(&buf[etBUFSIZE-1]-bufpt); 16744 break; 16871 break; 16745 case etFLOAT: 16872 case etFLOAT: 16746 case etEXP: 16873 case etEXP: 16747 case etGENERIC: 16874 case etGENERIC: 16748 realvalue = va_arg(ap,double); 16875 realvalue = va_arg(ap,double); 16749 #ifndef SQLITE_OMIT_FLOATING_POINT | 16876 #ifdef SQLITE_OMIT_FLOATING_POINT > 16877 length = 0; > 16878 #else 16750 if( precision<0 ) precision = 6; /* Set default precision */ 16879 if( precision<0 ) precision = 6; /* Set default precision */ 16751 if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10; 16880 if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10; 16752 if( realvalue<0.0 ){ 16881 if( realvalue<0.0 ){ 16753 realvalue = -realvalue; 16882 realvalue = -realvalue; 16754 prefix = '-'; 16883 prefix = '-'; 16755 }else{ 16884 }else{ 16756 if( flag_plussign ) prefix = '+'; 16885 if( flag_plussign ) prefix = '+'; ................................................................................................................................................................................ 16888 for(i=width; i>=nPad; i--){ 17017 for(i=width; i>=nPad; i--){ 16889 bufpt[i] = bufpt[i-nPad]; 17018 bufpt[i] = bufpt[i-nPad]; 16890 } 17019 } 16891 i = prefix!=0; 17020 i = prefix!=0; 16892 while( nPad-- ) bufpt[i++] = '0'; 17021 while( nPad-- ) bufpt[i++] = '0'; 16893 length = width; 17022 length = width; 16894 } 17023 } 16895 #endif | 17024 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */ 16896 break; 17025 break; 16897 case etSIZE: 17026 case etSIZE: 16898 *(va_arg(ap,int*)) = pAccum->nChar; 17027 *(va_arg(ap,int*)) = pAccum->nChar; 16899 length = width = 0; 17028 length = width = 0; 16900 break; 17029 break; 16901 case etPERCENT: 17030 case etPERCENT: 16902 buf[0] = '%'; 17031 buf[0] = '%'; ................................................................................................................................................................................ 16935 int needQuote; 17064 int needQuote; 16936 char ch; 17065 char ch; 16937 char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */ 17066 char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */ 16938 char *escarg = va_arg(ap,char*); 17067 char *escarg = va_arg(ap,char*); 16939 isnull = escarg==0; 17068 isnull = escarg==0; 16940 if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)"); 17069 if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)"); 16941 k = precision; 17070 k = precision; 16942 for(i=n=0; (ch=escarg[i])!=0 && k!=0; i++, k--){ | 17071 for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){ 16943 if( ch==q ) n++; 17072 if( ch==q ) n++; 16944 } 17073 } 16945 needQuote = !isnull && xtype==etSQLESCAPE2; 17074 needQuote = !isnull && xtype==etSQLESCAPE2; 16946 n += i + 1 + needQuote*2; 17075 n += i + 1 + needQuote*2; 16947 if( n>etBUFSIZE ){ 17076 if( n>etBUFSIZE ){ 16948 bufpt = zExtra = sqlite3Malloc( n ); 17077 bufpt = zExtra = sqlite3Malloc( n ); 16949 if( bufpt==0 ){ 17078 if( bufpt==0 ){ ................................................................................................................................................................................ 17218 acc.useMalloc = 0; 17347 acc.useMalloc = 0; 17219 va_start(ap,zFormat); 17348 va_start(ap,zFormat); 17220 sqlite3VXPrintf(&acc, 0, zFormat, ap); 17349 sqlite3VXPrintf(&acc, 0, zFormat, ap); 17221 va_end(ap); 17350 va_end(ap); 17222 z = sqlite3StrAccumFinish(&acc); 17351 z = sqlite3StrAccumFinish(&acc); 17223 return z; 17352 return z; 17224 } 17353 } > 17354 > 17355 /* > 17356 ** This is the routine that actually formats the sqlite3_log() message. > 17357 ** We house it in a separate routine from sqlite3_log() to avoid using > 17358 ** stack space on small-stack systems when logging is disabled. > 17359 ** > 17360 ** sqlite3_log() must render into a static buffer. It cannot dynamically > 17361 ** allocate memory because it might be called while the memory allocator > 17362 ** mutex is held. > 17363 */ > 17364 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){ > 17365 StrAccum acc; /* String accumulator */ > 17366 char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */ > 17367 > 17368 sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0); > 17369 acc.useMalloc = 0; > 17370 sqlite3VXPrintf(&acc, 0, zFormat, ap); > 17371 sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode, > 17372 sqlite3StrAccumFinish(&acc)); > 17373 } > 17374 > 17375 /* > 17376 ** Format and write a message to the log if logging is enabled. > 17377 */ > 17378 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){ > 17379 va_list ap; /* Vararg list */ > 17380 if( sqlite3GlobalConfig.xLog ){ > 17381 va_start(ap, zFormat); > 17382 renderLogMsg(iErrCode, zFormat, ap); > 17383 va_end(ap); > 17384 } > 17385 } 17225 17386 17226 #if defined(SQLITE_DEBUG) 17387 #if defined(SQLITE_DEBUG) 17227 /* 17388 /* 17228 ** A version of printf() that understands %lld. Used for debugging. 17389 ** A version of printf() that understands %lld. Used for debugging. 17229 ** The printf() built into some versions of windows does not understand %lld 17390 ** The printf() built into some versions of windows does not understand %lld 17230 ** and segfaults if you give it a long long int. 17391 ** and segfaults if you give it a long long int. 17231 */ 17392 */ ................................................................................................................................................................................ 17741 u32 cacheCtr; /* VdbeCursor row cache generation counter */ 17902 u32 cacheCtr; /* VdbeCursor row cache generation counter */ 17742 int pc; /* The program counter */ 17903 int pc; /* The program counter */ 17743 int rc; /* Value to return */ 17904 int rc; /* Value to return */ 17744 char *zErrMsg; /* Error message written here */ 17905 char *zErrMsg; /* Error message written here */ 17745 u8 explain; /* True if EXPLAIN present on SQL command */ 17906 u8 explain; /* True if EXPLAIN present on SQL command */ 17746 u8 changeCntOn; /* True to update the change-counter */ 17907 u8 changeCntOn; /* True to update the change-counter */ 17747 u8 expired; /* True if the VM needs to be recompiled */ 17908 u8 expired; /* True if the VM needs to be recompiled */ > 17909 u8 runOnlyOnce; /* Automatically expire on reset */ 17748 u8 minWriteFileFormat; /* Minimum file format for writable database files */ 17910 u8 minWriteFileFormat; /* Minimum file format for writable database files */ 17749 u8 inVtabMethod; /* See comments above */ 17911 u8 inVtabMethod; /* See comments above */ 17750 u8 usesStmtJournal; /* True if uses a statement journal */ 17912 u8 usesStmtJournal; /* True if uses a statement journal */ 17751 u8 readOnly; /* True for read-only statements */ 17913 u8 readOnly; /* True for read-only statements */ 17752 u8 isPrepareV2; /* True if prepared with prepare_v2() */ 17914 u8 isPrepareV2; /* True if prepared with prepare_v2() */ 17753 int nChange; /* Number of db changes made since last reset */ 17915 int nChange; /* Number of db changes made since last reset */ 17754 int btreeMask; /* Bitmask of db->aDb[] entries referenced */ 17916 int btreeMask; /* Bitmask of db->aDb[] entries referenced */ ................................................................................................................................................................................ 17802 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*); 17964 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*); 17803 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*); 17965 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*); 17804 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int); 17966 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int); 17805 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*); 17967 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*); 17806 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*); 17968 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*); 17807 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void 17969 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void 17808 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64); 17970 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64); > 17971 #ifdef SQLITE_OMIT_FLOATING_POINT > 17972 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64 > 17973 #else 17809 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double); | 17974 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double); > 17975 #endif 17810 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*); 17976 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*); 17811 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int); 17977 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int); 17812 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*); 17978 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*); 17813 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*); 17979 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*); 17814 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int); 17980 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int); 17815 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*); 17981 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*); 17816 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*); 17982 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*); ................................................................................................................................................................................ 18255 /* 18421 /* 18256 ** Convert a UTF-16 string in the native encoding into a UTF-8 string. 18422 ** Convert a UTF-16 string in the native encoding into a UTF-8 string. 18257 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must 18423 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must 18258 ** be freed by the calling function. 18424 ** be freed by the calling function. 18259 ** 18425 ** 18260 ** NULL is returned if there is an allocation error. 18426 ** NULL is returned if there is an allocation error. 18261 */ 18427 */ 18262 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte){ | 18428 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 e 18263 Mem m; 18429 Mem m; 18264 memset(&m, 0, sizeof(m)); 18430 memset(&m, 0, sizeof(m)); 18265 m.db = db; 18431 m.db = db; 18266 sqlite3VdbeMemSetStr(&m, z, nByte, SQLITE_UTF16NATIVE, SQLITE_STATIC); | 18432 sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC); 18267 sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8); 18433 sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8); 18268 if( db->mallocFailed ){ 18434 if( db->mallocFailed ){ 18269 sqlite3VdbeMemRelease(&m); 18435 sqlite3VdbeMemRelease(&m); 18270 m.z = 0; 18436 m.z = 0; 18271 } 18437 } 18272 assert( (m.flags & MEM_Term)!=0 || db->mallocFailed ); 18438 assert( (m.flags & MEM_Term)!=0 || db->mallocFailed ); 18273 assert( (m.flags & MEM_Str)!=0 || db->mallocFailed ); 18439 assert( (m.flags & MEM_Str)!=0 || db->mallocFailed ); 18274 return (m.flags & MEM_Dyn)!=0 ? m.z : sqlite3DbStrDup(db, m.z); | 18440 assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed ); > 18441 assert( m.z || db->mallocFailed ); > 18442 return m.z; 18275 } 18443 } 18276 18444 18277 /* 18445 /* 18278 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter 18446 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter 18279 ** enc. A pointer to the new string is returned, and the value of *pnOut 18447 ** enc. A pointer to the new string is returned, and the value of *pnOut 18280 ** is set to the length of the returned string in bytes. The call should 18448 ** is set to the length of the returned string in bytes. The call should 18281 ** arrange to call sqlite3DbFree() on the returned pointer when it is 18449 ** arrange to call sqlite3DbFree() on the returned pointer when it is ................................................................................................................................................................................ 18408 #ifdef SQLITE_COVERAGE_TEST 18576 #ifdef SQLITE_COVERAGE_TEST 18409 SQLITE_PRIVATE void sqlite3Coverage(int x){ 18577 SQLITE_PRIVATE void sqlite3Coverage(int x){ 18410 static int dummy = 0; 18578 static int dummy = 0; 18411 dummy += x; 18579 dummy += x; 18412 } 18580 } 18413 #endif 18581 #endif 18414 18582 > 18583 #ifndef SQLITE_OMIT_FLOATING_POINT 18415 /* 18584 /* 18416 ** Return true if the floating point value is Not a Number (NaN). 18585 ** Return true if the floating point value is Not a Number (NaN). 18417 ** 18586 ** 18418 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN. 18587 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN. 18419 ** Otherwise, we have our own implementation that works on most systems. 18588 ** Otherwise, we have our own implementation that works on most systems. 18420 */ 18589 */ 18421 SQLITE_PRIVATE int sqlite3IsNaN(double x){ 18590 SQLITE_PRIVATE int sqlite3IsNaN(double x){ ................................................................................................................................................................................ 18452 rc = (y!=z); 18621 rc = (y!=z); 18453 #else /* if defined(SQLITE_HAVE_ISNAN) */ 18622 #else /* if defined(SQLITE_HAVE_ISNAN) */ 18454 rc = isnan(x); 18623 rc = isnan(x); 18455 #endif /* SQLITE_HAVE_ISNAN */ 18624 #endif /* SQLITE_HAVE_ISNAN */ 18456 testcase( rc ); 18625 testcase( rc ); 18457 return rc; 18626 return rc; 18458 } 18627 } > 18628 #endif /* SQLITE_OMIT_FLOATING_POINT */ 18459 18629 18460 /* 18630 /* 18461 ** Compute a string length that is limited to what can be stored in 18631 ** Compute a string length that is limited to what can be stored in 18462 ** lower 30 bits of a 32-bit signed integer. 18632 ** lower 30 bits of a 32-bit signed integer. 18463 ** 18633 ** 18464 ** The value returned will never be negative. Nor will it ever be greater 18634 ** The value returned will never be negative. Nor will it ever be greater 18465 ** than the actual length of the string. For very long strings (greater 18635 ** than the actual length of the string. For very long strings (greater ................................................................................................................................................................................ 18523 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The 18693 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The 18524 ** last thing the sqlite3_prepare() function does is copy the error 18694 ** last thing the sqlite3_prepare() function does is copy the error 18525 ** stored by this function into the database handle using sqlite3Error(). 18695 ** stored by this function into the database handle using sqlite3Error(). 18526 ** Function sqlite3Error() should be used during statement execution 18696 ** Function sqlite3Error() should be used during statement execution 18527 ** (sqlite3_step() etc.). 18697 ** (sqlite3_step() etc.). 18528 */ 18698 */ 18529 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){ 18699 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){ 18530 va_list ap; | 18700 char *zMsg; 18531 sqlite3 *db = pParse->db; | 18701 va_list ap; 18532 pParse->nErr++; | 18702 sqlite3 *db = pParse->db; 18533 sqlite3DbFree(db, pParse->zErrMsg); | 18703 va_start(ap, zFormat); 18534 va_start(ap, zFormat); | 18704 zMsg = sqlite3VMPrintf(db, zFormat, ap); 18535 pParse->zErrMsg = sqlite3VMPrintf(db, zFormat, ap); | 18705 va_end(ap); 18536 va_end(ap); | 18706 if( db->suppressErr ){ 18537 pParse->rc = SQLITE_ERROR; | 18707 sqlite3DbFree(db, zMsg); 18538 } | 18708 }else{ 18539 | 18709 pParse->nErr++; 18540 /* | 18710 sqlite3DbFree(db, pParse->zErrMsg); 18541 ** Clear the error message in pParse, if any | 18711 pParse->zErrMsg = zMsg; 18542 */ | 18712 pParse->rc = SQLITE_ERROR; 18543 SQLITE_PRIVATE void sqlite3ErrorClear(Parse *pParse){ | 18713 } 18544 sqlite3DbFree(pParse->db, pParse->zErrMsg); < 18545 pParse->zErrMsg = 0; < 18546 pParse->nErr = 0; < 18547 } 18714 } 18548 18715 18549 /* 18716 /* 18550 ** Convert an SQL-style quoted string into a normal string by removing 18717 ** Convert an SQL-style quoted string into a normal string by removing 18551 ** the quote characters. The conversion is done in-place. If the 18718 ** the quote characters. The conversion is done in-place. If the 18552 ** input does not begin with a quote character, then this routine 18719 ** input does not begin with a quote character, then this routine 18553 ** is a no-op. 18720 ** is a no-op. ................................................................................................................................................................................ 18632 if( *z=='-' || *z=='+' ) z += incr; 18799 if( *z=='-' || *z=='+' ) z += incr; 18633 if( !sqlite3Isdigit(*z) ){ 18800 if( !sqlite3Isdigit(*z) ){ 18634 return 0; 18801 return 0; 18635 } 18802 } 18636 z += incr; 18803 z += incr; 18637 *realnum = 0; 18804 *realnum = 0; 18638 while( sqlite3Isdigit(*z) ){ z += incr; } 18805 while( sqlite3Isdigit(*z) ){ z += incr; } > 18806 #ifndef SQLITE_OMIT_FLOATING_POINT 18639 if( *z=='.' ){ 18807 if( *z=='.' ){ 18640 z += incr; 18808 z += incr; 18641 if( !sqlite3Isdigit(*z) ) return 0; 18809 if( !sqlite3Isdigit(*z) ) return 0; 18642 while( sqlite3Isdigit(*z) ){ z += incr; } 18810 while( sqlite3Isdigit(*z) ){ z += incr; } 18643 *realnum = 1; 18811 *realnum = 1; 18644 } 18812 } 18645 if( *z=='e' || *z=='E' ){ 18813 if( *z=='e' || *z=='E' ){ 18646 z += incr; 18814 z += incr; 18647 if( *z=='+' || *z=='-' ) z += incr; 18815 if( *z=='+' || *z=='-' ) z += incr; 18648 if( !sqlite3Isdigit(*z) ) return 0; 18816 if( !sqlite3Isdigit(*z) ) return 0; 18649 while( sqlite3Isdigit(*z) ){ z += incr; } 18817 while( sqlite3Isdigit(*z) ){ z += incr; } 18650 *realnum = 1; 18818 *realnum = 1; 18651 } 18819 } > 18820 #endif 18652 return *z==0; 18821 return *z==0; 18653 } 18822 } 18654 18823 18655 /* 18824 /* 18656 ** The string z[] is an ASCII representation of a real number. 18825 ** The string z[] is an ASCII representation of a real number. 18657 ** Convert this string to a double. 18826 ** Convert this string to a double. 18658 ** 18827 ** ................................................................................................................................................................................ 18806 ** will return -8. 18975 ** will return -8. 18807 */ 18976 */ 18808 static int compare2pow63(const char *zNum){ 18977 static int compare2pow63(const char *zNum){ 18809 int c; 18978 int c; 18810 c = memcmp(zNum,"922337203685477580",18)*10; 18979 c = memcmp(zNum,"922337203685477580",18)*10; 18811 if( c==0 ){ 18980 if( c==0 ){ 18812 c = zNum[18] - '8'; 18981 c = zNum[18] - '8'; > 18982 testcase( c==(-1) ); > 18983 testcase( c==0 ); > 18984 testcase( c==(+1) ); 18813 } 18985 } 18814 return c; 18986 return c; 18815 } 18987 } 18816 18988 18817 18989 18818 /* 18990 /* 18819 ** Return TRUE if zNum is a 64-bit signed integer and write 18991 ** Return TRUE if zNum is a 64-bit signed integer and write ................................................................................................................................................................................ 18842 } 19014 } 18843 zStart = zNum; 19015 zStart = zNum; 18844 while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */ 19016 while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */ 18845 for(i=0; (c=zNum[i])>='0' && c<='9'; i++){ 19017 for(i=0; (c=zNum[i])>='0' && c<='9'; i++){ 18846 v = v*10 + c - '0'; 19018 v = v*10 + c - '0'; 18847 } 19019 } 18848 *pNum = neg ? -v : v; 19020 *pNum = neg ? -v : v; > 19021 testcase( i==18 ); > 19022 testcase( i==19 ); > 19023 testcase( i==20 ); 18849 if( c!=0 || (i==0 && zStart==zNum) || i>19 ){ 19024 if( c!=0 || (i==0 && zStart==zNum) || i>19 ){ 18850 /* zNum is empty or contains non-numeric text or is longer 19025 /* zNum is empty or contains non-numeric text or is longer 18851 ** than 19 digits (thus guaranting that it is too large) */ 19026 ** than 19 digits (thus guaranting that it is too large) */ 18852 return 0; 19027 return 0; 18853 }else if( i<19 ){ 19028 }else if( i<19 ){ 18854 /* Less than 19 digits, so we know that it fits in 64 bits */ 19029 /* Less than 19 digits, so we know that it fits in 64 bits */ 18855 return 1; 19030 return 1; ................................................................................................................................................................................ 18885 assert( zNum[0]>='0' && zNum[0]<='9' ); /* zNum is an unsigned number */ 19060 assert( zNum[0]>='0' && zNum[0]<='9' ); /* zNum is an unsigned number */ 18886 19061 18887 if( negFlag ) neg = 1-neg; 19062 if( negFlag ) neg = 1-neg; 18888 while( *zNum=='0' ){ 19063 while( *zNum=='0' ){ 18889 zNum++; /* Skip leading zeros. Ticket #2454 */ 19064 zNum++; /* Skip leading zeros. Ticket #2454 */ 18890 } 19065 } 18891 for(i=0; zNum[i]; i++){ assert( zNum[i]>='0' && zNum[i]<='9' ); } 19066 for(i=0; zNum[i]; i++){ assert( zNum[i]>='0' && zNum[i]<='9' ); } > 19067 testcase( i==18 ); > 19068 testcase( i==19 ); > 19069 testcase( i==20 ); 18892 if( i<19 ){ 19070 if( i<19 ){ 18893 /* Guaranteed to fit if less than 19 digits */ 19071 /* Guaranteed to fit if less than 19 digits */ 18894 return 1; 19072 return 1; 18895 }else if( i>19 ){ 19073 }else if( i>19 ){ 18896 /* Guaranteed to be too big if greater than 19 digits */ 19074 /* Guaranteed to be too big if greater than 19 digits */ 18897 return 0; 19075 return 0; 18898 }else{ 19076 }else{ ................................................................................................................................................................................ 18925 } 19103 } 18926 19104 18927 /* The longest decimal representation of a 32 bit integer is 10 digits: 19105 /* The longest decimal representation of a 32 bit integer is 10 digits: 18928 ** 19106 ** 18929 ** 1234567890 19107 ** 1234567890 18930 ** 2^31 -> 2147483648 19108 ** 2^31 -> 2147483648 18931 */ 19109 */ > 19110 testcase( i==10 ); 18932 if( i>10 ){ 19111 if( i>10 ){ 18933 return 0; 19112 return 0; 18934 } 19113 } > 19114 testcase( v-neg==2147483647 ); 18935 if( v-neg>2147483647 ){ 19115 if( v-neg>2147483647 ){ 18936 return 0; 19116 return 0; 18937 } 19117 } 18938 if( neg ){ 19118 if( neg ){ 18939 v = -v; 19119 v = -v; 18940 } 19120 } 18941 *pValue = (int)v; 19121 *pValue = (int)v; ................................................................................................................................................................................ 19014 if( (v & ~0x3fff)==0 ){ 19194 if( (v & ~0x3fff)==0 ){ 19015 p[0] = (u8)((v>>7) | 0x80); 19195 p[0] = (u8)((v>>7) | 0x80); 19016 p[1] = (u8)(v & 0x7f); 19196 p[1] = (u8)(v & 0x7f); 19017 return 2; 19197 return 2; 19018 } 19198 } 19019 return sqlite3PutVarint(p, v); 19199 return sqlite3PutVarint(p, v); 19020 } 19200 } > 19201 > 19202 /* > 19203 ** Bitmasks used by sqlite3GetVarint(). These precomputed constants > 19204 ** are defined here rather than simply putting the constant expressions > 19205 ** inline in order to work around bugs in the RVT compiler. > 19206 ** > 19207 ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f > 19208 ** > 19209 ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0 > 19210 */ > 19211 #define SLOT_2_0 0x001fc07f > 19212 #define SLOT_4_2_0 0xf01fc07f > 19213 19021 19214 19022 /* 19215 /* 19023 ** Read a 64-bit variable-length integer from memory starting at p[0]. 19216 ** Read a 64-bit variable-length integer from memory starting at p[0]. 19024 ** Return the number of bytes read. The value is stored in *v. 19217 ** Return the number of bytes read. The value is stored in *v. 19025 */ 19218 */ 19026 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){ 19219 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){ 19027 u32 a,b,s; 19220 u32 a,b,s; ................................................................................................................................................................................ 19042 a &= 0x7f; 19235 a &= 0x7f; 19043 a = a<<7; 19236 a = a<<7; 19044 a |= b; 19237 a |= b; 19045 *v = a; 19238 *v = a; 19046 return 2; 19239 return 2; 19047 } 19240 } 19048 19241 > 19242 /* Verify that constants are precomputed correctly */ > 19243 assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) ); > 19244 assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) ); > 19245 19049 p++; 19246 p++; 19050 a = a<<14; 19247 a = a<<14; 19051 a |= *p; 19248 a |= *p; 19052 /* a: p0<<14 | p2 (unmasked) */ 19249 /* a: p0<<14 | p2 (unmasked) */ 19053 if (!(a&0x80)) 19250 if (!(a&0x80)) 19054 { 19251 { 19055 a &= (0x7f<<14)|(0x7f); | 19252 a &= SLOT_2_0; 19056 b &= 0x7f; 19253 b &= 0x7f; 19057 b = b<<7; 19254 b = b<<7; 19058 a |= b; 19255 a |= b; 19059 *v = a; 19256 *v = a; 19060 return 3; 19257 return 3; 19061 } 19258 } 19062 19259 19063 /* CSE1 from below */ 19260 /* CSE1 from below */ 19064 a &= (0x7f<<14)|(0x7f); | 19261 a &= SLOT_2_0; 19065 p++; 19262 p++; 19066 b = b<<14; 19263 b = b<<14; 19067 b |= *p; 19264 b |= *p; 19068 /* b: p1<<14 | p3 (unmasked) */ 19265 /* b: p1<<14 | p3 (unmasked) */ 19069 if (!(b&0x80)) 19266 if (!(b&0x80)) 19070 { 19267 { 19071 b &= (0x7f<<14)|(0x7f); | 19268 b &= SLOT_2_0; 19072 /* moved CSE1 up */ 19269 /* moved CSE1 up */ 19073 /* a &= (0x7f<<14)|(0x7f); */ 19270 /* a &= (0x7f<<14)|(0x7f); */ 19074 a = a<<7; 19271 a = a<<7; 19075 a |= b; 19272 a |= b; 19076 *v = a; 19273 *v = a; 19077 return 4; 19274 return 4; 19078 } 19275 } 19079 19276 19080 /* a: p0<<14 | p2 (masked) */ 19277 /* a: p0<<14 | p2 (masked) */ 19081 /* b: p1<<14 | p3 (unmasked) */ 19278 /* b: p1<<14 | p3 (unmasked) */ 19082 /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ 19279 /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */ 19083 /* moved CSE1 up */ 19280 /* moved CSE1 up */ 19084 /* a &= (0x7f<<14)|(0x7f); */ 19281 /* a &= (0x7f<<14)|(0x7f); */ 19085 b &= (0x7f<<14)|(0x7f); | 19282 b &= SLOT_2_0; 19086 s = a; 19283 s = a; 19087 /* s: p0<<14 | p2 (masked) */ 19284 /* s: p0<<14 | p2 (masked) */ 19088 19285 19089 p++; 19286 p++; 19090 a = a<<14; 19287 a = a<<14; 19091 a |= *p; 19288 a |= *p; 19092 /* a: p0<<28 | p2<<14 | p4 (unmasked) */ 19289 /* a: p0<<28 | p2<<14 | p4 (unmasked) */ ................................................................................................................................................................................ 19111 b = b<<14; 19308 b = b<<14; 19112 b |= *p; 19309 b |= *p; 19113 /* b: p1<<28 | p3<<14 | p5 (unmasked) */ 19310 /* b: p1<<28 | p3<<14 | p5 (unmasked) */ 19114 if (!(b&0x80)) 19311 if (!(b&0x80)) 19115 { 19312 { 19116 /* we can skip this cause it was (effectively) done above in calc'ing s */ 19313 /* we can skip this cause it was (effectively) done above in calc'ing s */ 19117 /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */ 19314 /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */ 19118 a &= (0x7f<<14)|(0x7f); | 19315 a &= SLOT_2_0; 19119 a = a<<7; 19316 a = a<<7; 19120 a |= b; 19317 a |= b; 19121 s = s>>18; 19318 s = s>>18; 19122 *v = ((u64)s)<<32 | a; 19319 *v = ((u64)s)<<32 | a; 19123 return 6; 19320 return 6; 19124 } 19321 } 19125 19322 19126 p++; 19323 p++; 19127 a = a<<14; 19324 a = a<<14; 19128 a |= *p; 19325 a |= *p; 19129 /* a: p2<<28 | p4<<14 | p6 (unmasked) */ 19326 /* a: p2<<28 | p4<<14 | p6 (unmasked) */ 19130 if (!(a&0x80)) 19327 if (!(a&0x80)) 19131 { 19328 { 19132 a &= (0x1f<<28)|(0x7f<<14)|(0x7f); | 19329 a &= SLOT_4_2_0; 19133 b &= (0x7f<<14)|(0x7f); | 19330 b &= SLOT_2_0; 19134 b = b<<7; 19331 b = b<<7; 19135 a |= b; 19332 a |= b; 19136 s = s>>11; 19333 s = s>>11; 19137 *v = ((u64)s)<<32 | a; 19334 *v = ((u64)s)<<32 | a; 19138 return 7; 19335 return 7; 19139 } 19336 } 19140 19337 19141 /* CSE2 from below */ 19338 /* CSE2 from below */ 19142 a &= (0x7f<<14)|(0x7f); | 19339 a &= SLOT_2_0; 19143 p++; 19340 p++; 19144 b = b<<14; 19341 b = b<<14; 19145 b |= *p; 19342 b |= *p; 19146 /* b: p3<<28 | p5<<14 | p7 (unmasked) */ 19343 /* b: p3<<28 | p5<<14 | p7 (unmasked) */ 19147 if (!(b&0x80)) 19344 if (!(b&0x80)) 19148 { 19345 { 19149 b &= (0x1f<<28)|(0x7f<<14)|(0x7f); | 19346 b &= SLOT_4_2_0; 19150 /* moved CSE2 up */ 19347 /* moved CSE2 up */ 19151 /* a &= (0x7f<<14)|(0x7f); */ 19348 /* a &= (0x7f<<14)|(0x7f); */ 19152 a = a<<7; 19349 a = a<<7; 19153 a |= b; 19350 a |= b; 19154 s = s>>4; 19351 s = s>>4; 19155 *v = ((u64)s)<<32 | a; 19352 *v = ((u64)s)<<32 | a; 19156 return 8; 19353 return 8; ................................................................................................................................................................................ 19159 p++; 19356 p++; 19160 a = a<<15; 19357 a = a<<15; 19161 a |= *p; 19358 a |= *p; 19162 /* a: p4<<29 | p6<<15 | p8 (unmasked) */ 19359 /* a: p4<<29 | p6<<15 | p8 (unmasked) */ 19163 19360 19164 /* moved CSE2 up */ 19361 /* moved CSE2 up */ 19165 /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */ 19362 /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */ 19166 b &= (0x7f<<14)|(0x7f); | 19363 b &= SLOT_2_0; 19167 b = b<<8; 19364 b = b<<8; 19168 a |= b; 19365 a |= b; 19169 19366 19170 s = s<<4; 19367 s = s<<4; 19171 b = p[-4]; 19368 b = p[-4]; 19172 b &= 0x7f; 19369 b &= 0x7f; 19173 b = b>>3; 19370 b = b>>3; ................................................................................................................................................................................ 19279 19476 19280 p++; 19477 p++; 19281 a = a<<14; 19478 a = a<<14; 19282 a |= *p; 19479 a |= *p; 19283 /* a: p0<<28 | p2<<14 | p4 (unmasked) */ 19480 /* a: p0<<28 | p2<<14 | p4 (unmasked) */ 19284 if (!(a&0x80)) 19481 if (!(a&0x80)) 19285 { 19482 { 19286 /* Walues between 268435456 and 34359738367 */ | 19483 /* Values between 268435456 and 34359738367 */ 19287 a &= (0x1f<<28)|(0x7f<<14)|(0x7f); | 19484 a &= SLOT_4_2_0; 19288 b &= (0x1f<<28)|(0x7f<<14)|(0x7f); | 19485 b &= SLOT_4_2_0; 19289 b = b<<7; 19486 b = b<<7; 19290 *v = a | b; 19487 *v = a | b; 19291 return 5; 19488 return 5; 19292 } 19489 } 19293 19490 19294 /* We can only reach this point when reading a corrupt database 19491 /* We can only reach this point when reading a corrupt database 19295 ** file. In that case we are not in any hurry. Use the (relatively 19492 ** file. In that case we are not in any hurry. Use the (relatively ................................................................................................................................................................................ 19374 } 19571 } 19375 zBlob[i/2] = 0; 19572 zBlob[i/2] = 0; 19376 } 19573 } 19377 return zBlob; 19574 return zBlob; 19378 } 19575 } 19379 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */ 19576 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */ 19380 19577 19381 < 19382 /* 19578 /* > 19579 ** Log an error that is an API call on a connection pointer that should 19383 ** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY. | 19580 ** not have been used. The "type" of connection pointer is given as the 19384 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN | 19581 ** argument. The zType is a word like "NULL" or "closed" or "invalid". 19385 ** when this routine is called. < 19386 ** | 19582 */ > 19583 static void logBadConnection(const char *zType){ 19387 ** This routine is called when entering an SQLite API. The SQLITE_MAGIC_OPEN | 19584 sqlite3_log(SQLITE_MISUSE, 19388 ** value indicates that the database connection passed into the API is | 19585 "API call with %s database connection pointer", 19389 ** open and is not being used by another thread. By changing the value | 19586 zType 19390 ** to SQLITE_MAGIC_BUSY we indicate that the connection is in use. < 19391 ** sqlite3SafetyOff() below will change the value back to SQLITE_MAGIC_OPEN < 19392 ** when the API exits. < 19393 ** < 19394 ** This routine is a attempt to detect if two threads use the < 19395 ** same sqlite* pointer at the same time. There is a race < 19396 ** condition so it is possible that the error is not detected. < 19397 ** But usually the problem will be seen. The result will be an < 19398 ** error which can be used to debug the application that is < 19399 ** using SQLite incorrectly. < 19400 ** < 19401 ** Ticket #202: If db->magic is not a valid open value, take care not < 19402 ** to modify the db structure at all. It could be that db is a stale < 19403 ** pointer. In other words, it could be that there has been a prior < 19404 ** call to sqlite3_close(db) and db has been deallocated. And we do < 19405 ** not want to write into deallocated memory. < 19406 */ < 19407 #ifdef SQLITE_DEBUG < 19408 SQLITE_PRIVATE int sqlite3SafetyOn(sqlite3 *db){ < 19409 if( db->magic==SQLITE_MAGIC_OPEN ){ < 19410 db->magic = SQLITE_MAGIC_BUSY; < 19411 assert( sqlite3_mutex_held(db->mutex) ); < 19412 return 0; < 19413 }else if( db->magic==SQLITE_MAGIC_BUSY ){ < 19414 db->magic = SQLITE_MAGIC_ERROR; < 19415 db->u1.isInterrupted = 1; < > 19587 ); 19416 } | 19588 } 19417 return 1; < 19418 } < 19419 #endif < 19420 < 19421 /* < 19422 ** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN. < 19423 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY < 19424 ** when this routine is called. < 19425 */ < 19426 #ifdef SQLITE_DEBUG < 19427 SQLITE_PRIVATE int sqlite3SafetyOff(sqlite3 *db){ < 19428 if( db->magic==SQLITE_MAGIC_BUSY ){ < 19429 db->magic = SQLITE_MAGIC_OPEN; < 19430 assert( sqlite3_mutex_held(db->mutex) ); < 19431 return 0; < 19432 }else{ < 19433 db->magic = SQLITE_MAGIC_ERROR; < 19434 db->u1.isInterrupted = 1; < 19435 return 1; < 19436 } < 19437 } < 19438 #endif < 19439 19589 19440 /* 19590 /* 19441 ** Check to make sure we have a valid db pointer. This test is not 19591 ** Check to make sure we have a valid db pointer. This test is not 19442 ** foolproof but it does provide some measure of protection against 19592 ** foolproof but it does provide some measure of protection against 19443 ** misuse of the interface such as passing in db pointers that are 19593 ** misuse of the interface such as passing in db pointers that are 19444 ** NULL or which have been previously closed. If this routine returns 19594 ** NULL or which have been previously closed. If this routine returns 19445 ** 1 it means that the db pointer is valid and 0 if it should not be 19595 ** 1 it means that the db pointer is valid and 0 if it should not be ................................................................................................................................................................................ 19449 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for 19599 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for 19450 ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to 19600 ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to 19451 ** open properly and is not fit for general use but which can be 19601 ** open properly and is not fit for general use but which can be 19452 ** used as an argument to sqlite3_errmsg() or sqlite3_close(). 19602 ** used as an argument to sqlite3_errmsg() or sqlite3_close(). 19453 */ 19603 */ 19454 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){ 19604 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){ 19455 u32 magic; 19605 u32 magic; 19456 if( db==0 ) return 0; | 19606 if( db==0 ){ 19457 magic = db->magic; | 19607 logBadConnection("NULL"); 19458 if( magic!=SQLITE_MAGIC_OPEN | 19608 return 0; 19459 #ifdef SQLITE_DEBUG | 19609 } 19460 && magic!=SQLITE_MAGIC_BUSY | 19610 magic = db->magic; 19461 #endif | 19611 if( magic!=SQLITE_MAGIC_OPEN ){ 19462 ){ | 19612 if( sqlite3SafetyCheckSickOrOk(db) ){ > 19613 testcase( sqlite3GlobalConfig.xLog!=0 ); > 19614 logBadConnection("unopened"); > 19615 } 19463 return 0; 19616 return 0; 19464 }else{ 19617 }else{ 19465 return 1; 19618 return 1; 19466 } 19619 } 19467 } 19620 } 19468 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){ 19621 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){ 19469 u32 magic; 19622 u32 magic; 19470 magic = db->magic; 19623 magic = db->magic; 19471 if( magic!=SQLITE_MAGIC_SICK && 19624 if( magic!=SQLITE_MAGIC_SICK && 19472 magic!=SQLITE_MAGIC_OPEN && 19625 magic!=SQLITE_MAGIC_OPEN && 19473 magic!=SQLITE_MAGIC_BUSY ) return 0; | 19626 magic!=SQLITE_MAGIC_BUSY ){ > 19627 testcase( sqlite3GlobalConfig.xLog!=0 ); > 19628 logBadConnection("invalid"); > 19629 return 0; > 19630 }else{ 19474 return 1; | 19631 return 1; > 19632 } 19475 } 19633 } 19476 19634 19477 /************** End of util.c ************************************************/ 19635 /************** End of util.c ************************************************/ 19478 /************** Begin file hash.c ********************************************/ 19636 /************** Begin file hash.c ********************************************/ 19479 /* 19637 /* 19480 ** 2001 September 22 19638 ** 2001 September 22 19481 ** 19639 ** ................................................................................................................................................................................ 21379 # include <sys/ioctl.h> 21537 # include <sys/ioctl.h> 21380 # if OS_VXWORKS 21538 # if OS_VXWORKS 21381 # include <semaphore.h> 21539 # include <semaphore.h> 21382 # include <limits.h> 21540 # include <limits.h> 21383 # else 21541 # else 21384 # include <sys/file.h> 21542 # include <sys/file.h> 21385 # include <sys/param.h> 21543 # include <sys/param.h> 21386 # include <sys/mount.h> < 21387 # endif 21544 # endif 21388 #endif /* SQLITE_ENABLE_LOCKING_STYLE */ 21545 #endif /* SQLITE_ENABLE_LOCKING_STYLE */ > 21546 > 21547 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS) > 21548 # include <sys/mount.h> > 21549 #endif > 21550 > 21551 /* > 21552 ** Allowed values of unixFile.fsFlags > 21553 */ > 21554 #define SQLITE_FSFLAGS_IS_MSDOS 0x1 21389 21555 21390 /* 21556 /* 21391 ** If we are to be thread-safe, include the pthreads header and define 21557 ** If we are to be thread-safe, include the pthreads header and define 21392 ** the SQLITE_UNIX_THREADS macro. 21558 ** the SQLITE_UNIX_THREADS macro. 21393 */ 21559 */ 21394 #if SQLITE_THREADSAFE 21560 #if SQLITE_THREADSAFE 21395 # define SQLITE_UNIX_THREADS 1 21561 # define SQLITE_UNIX_THREADS 1 ................................................................................................................................................................................ 21449 int lastErrno; /* The unix errno from the last I/O error */ 21615 int lastErrno; /* The unix errno from the last I/O error */ 21450 void *lockingContext; /* Locking style specific state */ 21616 void *lockingContext; /* Locking style specific state */ 21451 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */ 21617 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */ 21452 int fileFlags; /* Miscellanous flags */ 21618 int fileFlags; /* Miscellanous flags */ 21453 #if SQLITE_ENABLE_LOCKING_STYLE 21619 #if SQLITE_ENABLE_LOCKING_STYLE 21454 int openFlags; /* The flags specified at open() */ 21620 int openFlags; /* The flags specified at open() */ 21455 #endif 21621 #endif > 21622 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__) > 21623 unsigned fsFlags; /* cached details from statfs() */ > 21624 #endif 21456 #if SQLITE_THREADSAFE && defined(__linux__) 21625 #if SQLITE_THREADSAFE && defined(__linux__) 21457 pthread_t tid; /* The thread that "owns" this unixFile */ 21626 pthread_t tid; /* The thread that "owns" this unixFile */ 21458 #endif 21627 #endif 21459 #if OS_VXWORKS 21628 #if OS_VXWORKS 21460 int isDelete; /* Delete on close if true */ 21629 int isDelete; /* Delete on close if true */ 21461 struct vxworksFileId *pId; /* Unique file ID */ 21630 struct vxworksFileId *pId; /* Unique file ID */ 21462 #endif 21631 #endif ................................................................................................................................................................................ 22216 ** object keeps a count of the number of unixFile pointing to it. 22385 ** object keeps a count of the number of unixFile pointing to it. 22217 */ 22386 */ 22218 struct unixLockInfo { 22387 struct unixLockInfo { 22219 struct unixLockKey lockKey; /* The lookup key */ 22388 struct unixLockKey lockKey; /* The lookup key */ 22220 int cnt; /* Number of SHARED locks held */ 22389 int cnt; /* Number of SHARED locks held */ 22221 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */ 22390 int locktype; /* One of SHARED_LOCK, RESERVED_LOCK etc. */ 22222 int nRef; /* Number of pointers to this structure */ 22391 int nRef; /* Number of pointers to this structure */ > 22392 #if defined(SQLITE_ENABLE_LOCKING_STYLE) > 22393 unsigned long long sharedByte; /* for AFP simulated shared lock */ > 22394 #endif 22223 struct unixLockInfo *pNext; /* List of all unixLockInfo objects */ 22395 struct unixLockInfo *pNext; /* List of all unixLockInfo objects */ 22224 struct unixLockInfo *pPrev; /* .... doubly linked */ 22396 struct unixLockInfo *pPrev; /* .... doubly linked */ 22225 }; 22397 }; 22226 22398 22227 /* 22399 /* 22228 ** An instance of the following structure is allocated for each open 22400 ** An instance of the following structure is allocated for each open 22229 ** inode. This structure keeps track of the number of locks on that 22401 ** inode. This structure keeps track of the number of locks on that ................................................................................................................................................................................ 22459 ** we always increase the file size to 1 by writing a single byte 22631 ** we always increase the file size to 1 by writing a single byte 22460 ** prior to accessing the inode number. The one byte written is 22632 ** prior to accessing the inode number. The one byte written is 22461 ** an ASCII 'S' character which also happens to be the first byte 22633 ** an ASCII 'S' character which also happens to be the first byte 22462 ** in the header of every SQLite database. In this way, if there 22634 ** in the header of every SQLite database. In this way, if there 22463 ** is a race condition such that another thread has already populated 22635 ** is a race condition such that another thread has already populated 22464 ** the first page of the database, no damage is done. 22636 ** the first page of the database, no damage is done. 22465 */ 22637 */ 22466 if( statbuf.st_size==0 ){ | 22638 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){ 22467 rc = write(fd, "S", 1); 22639 rc = write(fd, "S", 1); 22468 if( rc!=1 ){ 22640 if( rc!=1 ){ > 22641 pFile->lastErrno = errno; 22469 return SQLITE_IOERR; 22642 return SQLITE_IOERR; 22470 } 22643 } 22471 rc = fstat(fd, &statbuf); 22644 rc = fstat(fd, &statbuf); 22472 if( rc!=0 ){ 22645 if( rc!=0 ){ 22473 pFile->lastErrno = errno; 22646 pFile->lastErrno = errno; 22474 return SQLITE_IOERR; 22647 return SQLITE_IOERR; 22475 } 22648 } ................................................................................................................................................................................ 22501 rc = SQLITE_NOMEM; 22674 rc = SQLITE_NOMEM; 22502 goto exit_findlockinfo; 22675 goto exit_findlockinfo; 22503 } 22676 } 22504 memcpy(&pLock->lockKey,&lockKey,sizeof(lockKey)); 22677 memcpy(&pLock->lockKey,&lockKey,sizeof(lockKey)); 22505 pLock->nRef = 1; 22678 pLock->nRef = 1; 22506 pLock->cnt = 0; 22679 pLock->cnt = 0; 22507 pLock->locktype = 0; 22680 pLock->locktype = 0; > 22681 #if defined(SQLITE_ENABLE_LOCKING_STYLE) > 22682 pLock->sharedByte = 0; > 22683 #endif 22508 pLock->pNext = lockList; 22684 pLock->pNext = lockList; 22509 pLock->pPrev = 0; 22685 pLock->pPrev = 0; 22510 if( lockList ) lockList->pPrev = pLock; 22686 if( lockList ) lockList->pPrev = pLock; 22511 lockList = pLock; 22687 lockList = pLock; 22512 }else{ 22688 }else{ 22513 pLock->nRef++; 22689 pLock->nRef++; 22514 } 22690 } ................................................................................................................................................................................ 22565 if( pthread_equal(pFile->tid, hSelf) ){ 22741 if( pthread_equal(pFile->tid, hSelf) ){ 22566 /* We are still in the same thread */ 22742 /* We are still in the same thread */ 22567 OSTRACE1("No-transfer, same thread\n"); 22743 OSTRACE1("No-transfer, same thread\n"); 22568 return SQLITE_OK; 22744 return SQLITE_OK; 22569 } 22745 } 22570 if( pFile->locktype!=NO_LOCK ){ 22746 if( pFile->locktype!=NO_LOCK ){ 22571 /* We cannot change ownership while we are holding a lock! */ 22747 /* We cannot change ownership while we are holding a lock! */ 22572 return SQLITE_MISUSE; | 22748 return SQLITE_MISUSE_BKPT; 22573 } 22749 } 22574 OSTRACE4("Transfer ownership of %d from %d to %d\n", 22750 OSTRACE4("Transfer ownership of %d from %d to %d\n", 22575 pFile->h, pFile->tid, hSelf); 22751 pFile->h, pFile->tid, hSelf); 22576 pFile->tid = hSelf; 22752 pFile->tid = hSelf; 22577 if (pFile->pLock != NULL) { 22753 if (pFile->pLock != NULL) { 22578 releaseLockInfo(pFile->pLock); 22754 releaseLockInfo(pFile->pLock); 22579 rc = findLockInfo(pFile, &pFile->pLock, 0); 22755 rc = findLockInfo(pFile, &pFile->pLock, 0); ................................................................................................................................................................................ 22631 } 22807 } 22632 #endif 22808 #endif 22633 22809 22634 unixLeaveMutex(); 22810 unixLeaveMutex(); 22635 OSTRACE4("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved); 22811 OSTRACE4("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved); 22636 22812 22637 *pResOut = reserved; 22813 *pResOut = reserved; 22638 return rc; < 22639 } < 22640 < 22641 /* < 22642 ** Perform a file locking operation on a range of bytes in a file. < 22643 ** The "op" parameter should be one of F_RDLCK, F_WRLCK, or F_UNLCK. < 22644 ** Return 0 on success or -1 for failure. On failure, write the error < 22645 ** code into *pErrcode. < 22646 ** < 22647 ** If the SQLITE_WHOLE_FILE_LOCKING bit is clear, then only lock < 22648 ** the range of bytes on the locking page between SHARED_FIRST and < 22649 ** SHARED_SIZE. If SQLITE_WHOLE_FILE_LOCKING is set, then lock all < 22650 ** bytes from 0 up to but not including PENDING_BYTE, and all bytes < 22651 ** that follow SHARED_FIRST. < 22652 ** < 22653 ** In other words, of SQLITE_WHOLE_FILE_LOCKING if false (the historical < 22654 ** default case) then only lock a small range of bytes from SHARED_FIRST < 22655 ** through SHARED_FIRST+SHARED_SIZE-1. But if SQLITE_WHOLE_FILE_LOCKING is < 22656 ** true then lock every byte in the file except for PENDING_BYTE and < 22657 ** RESERVED_BYTE. < 22658 ** < 22659 ** SQLITE_WHOLE_FILE_LOCKING=true overlaps SQLITE_WHOLE_FILE_LOCKING=false < 22660 ** and so the locking schemes are compatible. One type of lock will < 22661 ** effectively exclude the other type. The reason for using the < 22662 ** SQLITE_WHOLE_FILE_LOCKING=true is that by indicating the full range < 22663 ** of bytes to be read or written, we give hints to NFS to help it < 22664 ** maintain cache coherency. On the other hand, whole file locking < 22665 ** is slower, so we don't want to use it except for NFS. < 22666 */ < 22667 static int rangeLock(unixFile *pFile, int op, int *pErrcode){ < 22668 struct flock lock; < 22669 int rc; < 22670 lock.l_type = op; < 22671 lock.l_start = SHARED_FIRST; < 22672 lock.l_whence = SEEK_SET; < 22673 if( (pFile->fileFlags & SQLITE_WHOLE_FILE_LOCKING)==0 ){ < 22674 lock.l_len = SHARED_SIZE; < 22675 rc = fcntl(pFile->h, F_SETLK, &lock); < 22676 *pErrcode = errno; < 22677 }else{ < 22678 lock.l_len = 0; < 22679 rc = fcntl(pFile->h, F_SETLK, &lock); < 22680 *pErrcode = errno; < 22681 if( NEVER(op==F_UNLCK) || rc!=(-1) ){ < 22682 lock.l_start = 0; < 22683 lock.l_len = PENDING_BYTE; < 22684 rc = fcntl(pFile->h, F_SETLK, &lock); < 22685 if( ALWAYS(op!=F_UNLCK) && rc==(-1) ){ < 22686 *pErrcode = errno; < 22687 lock.l_type = F_UNLCK; < 22688 lock.l_start = SHARED_FIRST; < 22689 lock.l_len = 0; < 22690 fcntl(pFile->h, F_SETLK, &lock); < 22691 } < 22692 } < 22693 } < 22694 return rc; 22814 return rc; 22695 } 22815 } 22696 22816 22697 /* 22817 /* 22698 ** Lock the file with the lock specified by parameter locktype - one 22818 ** Lock the file with the lock specified by parameter locktype - one 22699 ** of the following: 22819 ** of the following: 22700 ** 22820 ** ................................................................................................................................................................................ 22758 ** even if the locking primitive used is always a write-lock. 22878 ** even if the locking primitive used is always a write-lock. 22759 */ 22879 */ 22760 int rc = SQLITE_OK; 22880 int rc = SQLITE_OK; 22761 unixFile *pFile = (unixFile*)id; 22881 unixFile *pFile = (unixFile*)id; 22762 struct unixLockInfo *pLock = pFile->pLock; 22882 struct unixLockInfo *pLock = pFile->pLock; 22763 struct flock lock; 22883 struct flock lock; 22764 int s = 0; 22884 int s = 0; 22765 int tErrno; | 22885 int tErrno = 0; 22766 22886 22767 assert( pFile ); 22887 assert( pFile ); 22768 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h, 22888 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h, 22769 locktypeName(locktype), locktypeName(pFile->locktype), 22889 locktypeName(locktype), locktypeName(pFile->locktype), 22770 locktypeName(pLock->locktype), pLock->cnt , getpid()); 22890 locktypeName(pLock->locktype), pLock->cnt , getpid()); 22771 22891 22772 /* If there is already a lock of this type or more restrictive on the 22892 /* If there is already a lock of this type or more restrictive on the ................................................................................................................................................................................ 22854 ** operating system calls for the specified lock. 22974 ** operating system calls for the specified lock. 22855 */ 22975 */ 22856 if( locktype==SHARED_LOCK ){ 22976 if( locktype==SHARED_LOCK ){ 22857 assert( pLock->cnt==0 ); 22977 assert( pLock->cnt==0 ); 22858 assert( pLock->locktype==0 ); 22978 assert( pLock->locktype==0 ); 22859 22979 22860 /* Now get the read-lock */ 22980 /* Now get the read-lock */ 22861 s = rangeLock(pFile, F_RDLCK, &tErrno); | 22981 lock.l_start = SHARED_FIRST; > 22982 lock.l_len = SHARED_SIZE; > 22983 if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){ > 22984 tErrno = errno; 22862 | 22985 } 22863 /* Drop the temporary PENDING lock */ 22986 /* Drop the temporary PENDING lock */ 22864 lock.l_start = PENDING_BYTE; 22987 lock.l_start = PENDING_BYTE; 22865 lock.l_len = 1L; 22988 lock.l_len = 1L; 22866 lock.l_type = F_UNLCK; 22989 lock.l_type = F_UNLCK; 22867 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){ 22990 if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){ 22868 if( s != -1 ){ 22991 if( s != -1 ){ 22869 /* This could happen with a network mount */ 22992 /* This could happen with a network mount */ ................................................................................................................................................................................ 22895 ** already. 23018 ** already. 22896 */ 23019 */ 22897 assert( 0!=pFile->locktype ); 23020 assert( 0!=pFile->locktype ); 22898 lock.l_type = F_WRLCK; 23021 lock.l_type = F_WRLCK; 22899 switch( locktype ){ 23022 switch( locktype ){ 22900 case RESERVED_LOCK: 23023 case RESERVED_LOCK: 22901 lock.l_start = RESERVED_BYTE; 23024 lock.l_start = RESERVED_BYTE; 22902 s = fcntl(pFile->h, F_SETLK, &lock); < 22903 tErrno = errno; < 22904 break; 23025 break; 22905 case EXCLUSIVE_LOCK: 23026 case EXCLUSIVE_LOCK: 22906 s = rangeLock(pFile, F_WRLCK, &tErrno); < > 23027 lock.l_start = SHARED_FIRST; > 23028 lock.l_len = SHARED_SIZE; 22907 break; 23029 break; 22908 default: 23030 default: 22909 assert(0); 23031 assert(0); 22910 } 23032 } > 23033 s = fcntl(pFile->h, F_SETLK, &lock); 22911 if( s==(-1) ){ 23034 if( s==(-1) ){ > 23035 tErrno = errno; 22912 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 23036 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 22913 if( IS_LOCK_ERROR(rc) ){ 23037 if( IS_LOCK_ERROR(rc) ){ 22914 pFile->lastErrno = tErrno; 23038 pFile->lastErrno = tErrno; 22915 } 23039 } 22916 } 23040 } 22917 } 23041 } 22918 23042 ................................................................................................................................................................................ 22994 23118 22995 /* 23119 /* 22996 ** Lower the locking level on file descriptor pFile to locktype. locktype 23120 ** Lower the locking level on file descriptor pFile to locktype. locktype 22997 ** must be either NO_LOCK or SHARED_LOCK. 23121 ** must be either NO_LOCK or SHARED_LOCK. 22998 ** 23122 ** 22999 ** If the locking level of the file descriptor is already at or below 23123 ** If the locking level of the file descriptor is already at or below 23000 ** the requested locking level, this routine is a no-op. 23124 ** the requested locking level, this routine is a no-op. > 23125 ** > 23126 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED > 23127 ** the byte range is divided into 2 parts and the first part is unlocked then > 23128 ** set to a read lock, then the other part is simply unlocked. This works > 23129 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to > 23130 ** remove the write lock on a region when a read lock is set. 23001 */ 23131 */ 23002 static int unixUnlock(sqlite3_file *id, int locktype){ | 23132 static int _posixUnlock(sqlite3_file *id, int locktype, int handleNFSUnlock){ 23003 unixFile *pFile = (unixFile*)id; /* The open file */ | 23133 unixFile *pFile = (unixFile*)id; 23004 struct unixLockInfo *pLock; /* Structure describing current lock state */ | 23134 struct unixLockInfo *pLock; 23005 struct flock lock; /* Information passed into fcntl() */ | 23135 struct flock lock; 23006 int rc = SQLITE_OK; /* Return code from this interface */ | 23136 int rc = SQLITE_OK; 23007 int h; /* The underlying file descriptor */ < > 23137 int h; 23008 int tErrno; /* Error code from system call errors */ 23138 int tErrno; /* Error code from system call errors */ 23009 23139 23010 assert( pFile ); 23140 assert( pFile ); 23011 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, locktype, 23141 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, locktype, 23012 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid()); 23142 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid()); 23013 23143 23014 assert( locktype<=SHARED_LOCK ); 23144 assert( locktype<=SHARED_LOCK ); 23015 if( pFile->locktype<=locktype ){ 23145 if( pFile->locktype<=locktype ){ 23016 return SQLITE_OK; 23146 return SQLITE_OK; 23017 } 23147 } 23018 if( CHECK_THREADID(pFile) ){ 23148 if( CHECK_THREADID(pFile) ){ 23019 return SQLITE_MISUSE; | 23149 return SQLITE_MISUSE_BKPT; 23020 } 23150 } 23021 unixEnterMutex(); 23151 unixEnterMutex(); 23022 h = pFile->h; 23152 h = pFile->h; 23023 pLock = pFile->pLock; 23153 pLock = pFile->pLock; 23024 assert( pLock->cnt!=0 ); 23154 assert( pLock->cnt!=0 ); 23025 if( pFile->locktype>SHARED_LOCK ){ 23155 if( pFile->locktype>SHARED_LOCK ){ 23026 assert( pLock->locktype==pFile->locktype ); 23156 assert( pLock->locktype==pFile->locktype ); ................................................................................................................................................................................ 23039 */ 23169 */ 23040 assert( pFile->inNormalWrite==0 23170 assert( pFile->inNormalWrite==0 23041 || pFile->dbUpdate==0 23171 || pFile->dbUpdate==0 23042 || pFile->transCntrChng==1 ); 23172 || pFile->transCntrChng==1 ); 23043 pFile->inNormalWrite = 0; 23173 pFile->inNormalWrite = 0; 23044 #endif 23174 #endif 23045 23175 23046 < > 23176 /* downgrading to a shared lock on NFS involves clearing the write lock > 23177 ** before establishing the readlock - to avoid a race condition we downgrade > 23178 ** the lock in 2 blocks, so that part of the range will be covered by a > 23179 ** write lock until the rest is covered by a read lock: > 23180 ** 1: [WWWWW] > 23181 ** 2: [....W] > 23182 ** 3: [RRRRW] > 23183 ** 4: [RRRR.] > 23184 */ 23047 if( locktype==SHARED_LOCK ){ 23185 if( locktype==SHARED_LOCK ){ 23048 if( rangeLock(pFile, F_RDLCK, &tErrno)==(-1) ){ < > 23186 if( handleNFSUnlock ){ > 23187 off_t divSize = SHARED_SIZE - 1; > 23188 > 23189 lock.l_type = F_UNLCK; > 23190 lock.l_whence = SEEK_SET; > 23191 lock.l_start = SHARED_FIRST; > 23192 lock.l_len = divSize; > 23193 if( fcntl(h, F_SETLK, &lock)==(-1) ){ > 23194 tErrno = errno; > 23195 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); > 23196 if( IS_LOCK_ERROR(rc) ){ > 23197 pFile->lastErrno = tErrno; > 23198 } > 23199 goto end_unlock; > 23200 } > 23201 lock.l_type = F_RDLCK; > 23202 lock.l_whence = SEEK_SET; > 23203 lock.l_start = SHARED_FIRST; > 23204 lock.l_len = divSize; > 23205 if( fcntl(h, F_SETLK, &lock)==(-1) ){ > 23206 tErrno = errno; 23049 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK); | 23207 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK); 23050 if( IS_LOCK_ERROR(rc) ){ | 23208 if( IS_LOCK_ERROR(rc) ){ 23051 pFile->lastErrno = tErrno; | 23209 pFile->lastErrno = tErrno; 23052 } | 23210 } 23053 goto end_unlock; | 23211 goto end_unlock; > 23212 } > 23213 lock.l_type = F_UNLCK; > 23214 lock.l_whence = SEEK_SET; > 23215 lock.l_start = SHARED_FIRST+divSize; > 23216 lock.l_len = SHARED_SIZE-divSize; > 23217 if( fcntl(h, F_SETLK, &lock)==(-1) ){ > 23218 tErrno = errno; > 23219 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); > 23220 if( IS_LOCK_ERROR(rc) ){ > 23221 pFile->lastErrno = tErrno; > 23222 } > 23223 goto end_unlock; > 23224 } > 23225 }else{ > 23226 lock.l_type = F_RDLCK; > 23227 lock.l_whence = SEEK_SET; > 23228 lock.l_start = SHARED_FIRST; > 23229 lock.l_len = SHARED_SIZE; > 23230 if( fcntl(h, F_SETLK, &lock)==(-1) ){ > 23231 tErrno = errno; > 23232 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK); > 23233 if( IS_LOCK_ERROR(rc) ){ > 23234 pFile->lastErrno = tErrno; > 23235 } > 23236 goto end_unlock; > 23237 } 23054 } 23238 } 23055 } 23239 } 23056 lock.l_type = F_UNLCK; 23240 lock.l_type = F_UNLCK; 23057 lock.l_whence = SEEK_SET; 23241 lock.l_whence = SEEK_SET; 23058 lock.l_start = PENDING_BYTE; 23242 lock.l_start = PENDING_BYTE; 23059 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE ); 23243 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE ); 23060 if( fcntl(h, F_SETLK, &lock)!=(-1) ){ 23244 if( fcntl(h, F_SETLK, &lock)!=(-1) ){ ................................................................................................................................................................................ 23112 } 23296 } 23113 23297 23114 end_unlock: 23298 end_unlock: 23115 unixLeaveMutex(); 23299 unixLeaveMutex(); 23116 if( rc==SQLITE_OK ) pFile->locktype = locktype; 23300 if( rc==SQLITE_OK ) pFile->locktype = locktype; 23117 return rc; 23301 return rc; 23118 } 23302 } > 23303 > 23304 /* > 23305 ** Lower the locking level on file descriptor pFile to locktype. locktype > 23306 ** must be either NO_LOCK or SHARED_LOCK. > 23307 ** > 23308 ** If the locking level of the file descriptor is already at or below > 23309 ** the requested locking level, this routine is a no-op. > 23310 */ > 23311 static int unixUnlock(sqlite3_file *id, int locktype){ > 23312 return _posixUnlock(id, locktype, 0); > 23313 } 23119 23314 23120 /* 23315 /* 23121 ** This function performs the parts of the "close file" operation 23316 ** This function performs the parts of the "close file" operation 23122 ** common to all locking schemes. It closes the directory and file 23317 ** common to all locking schemes. It closes the directory and file 23123 ** handles, if they are valid, and sets all fields of the unixFile 23318 ** handles, if they are valid, and sets all fields of the unixFile 23124 ** structure to 0. 23319 ** structure to 0. 23125 ** 23320 ** ................................................................................................................................................................................ 23824 24019 23825 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE 24020 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE 23826 /* 24021 /* 23827 ** The afpLockingContext structure contains all afp lock specific state 24022 ** The afpLockingContext structure contains all afp lock specific state 23828 */ 24023 */ 23829 typedef struct afpLockingContext afpLockingContext; 24024 typedef struct afpLockingContext afpLockingContext; 23830 struct afpLockingContext { 24025 struct afpLockingContext { 23831 unsigned long long sharedByte; | 24026 int reserved; 23832 const char *dbPath; /* Name of the open file */ 24027 const char *dbPath; /* Name of the open file */ 23833 }; 24028 }; 23834 24029 23835 struct ByteRangeLockPB2 24030 struct ByteRangeLockPB2 23836 { 24031 { 23837 unsigned long long offset; /* offset to first byte to lock */ 24032 unsigned long long offset; /* offset to first byte to lock */ 23838 unsigned long long length; /* nbr of bytes to lock */ 24033 unsigned long long length; /* nbr of bytes to lock */ ................................................................................................................................................................................ 23901 int reserved = 0; 24096 int reserved = 0; 23902 unixFile *pFile = (unixFile*)id; 24097 unixFile *pFile = (unixFile*)id; 23903 24098 23904 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); 24099 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; ); 23905 24100 23906 assert( pFile ); 24101 assert( pFile ); 23907 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext; 24102 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext; > 24103 if( context->reserved ){ > 24104 *pResOut = 1; > 24105 return SQLITE_OK; 23908 | 24106 } > 24107 unixEnterMutex(); /* Because pFile->pLock is shared across threads */ > 24108 23909 /* Check if a thread in this process holds such a lock */ 24109 /* Check if a thread in this process holds such a lock */ 23910 if( pFile->locktype>SHARED_LOCK ){ | 24110 if( pFile->pLock->locktype>SHARED_LOCK ){ 23911 reserved = 1; 24111 reserved = 1; 23912 } 24112 } 23913 24113 23914 /* Otherwise see if some other process holds it. 24114 /* Otherwise see if some other process holds it. 23915 */ 24115 */ 23916 if( !reserved ){ 24116 if( !reserved ){ 23917 /* lock the RESERVED byte */ 24117 /* lock the RESERVED byte */ ................................................................................................................................................................................ 23925 reserved = 1; 24125 reserved = 1; 23926 } 24126 } 23927 if( IS_LOCK_ERROR(lrc) ){ 24127 if( IS_LOCK_ERROR(lrc) ){ 23928 rc=lrc; 24128 rc=lrc; 23929 } 24129 } 23930 } 24130 } 23931 24131 > 24132 unixLeaveMutex(); 23932 OSTRACE4("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved); 24133 OSTRACE4("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved); 23933 24134 23934 *pResOut = reserved; 24135 *pResOut = reserved; 23935 return rc; 24136 return rc; 23936 } 24137 } 23937 24138 23938 /* 24139 /* ................................................................................................................................................................................ 23958 ** 24159 ** 23959 ** This routine will only increase a lock. Use the sqlite3OsUnlock() 24160 ** This routine will only increase a lock. Use the sqlite3OsUnlock() 23960 ** routine to lower a locking level. 24161 ** routine to lower a locking level. 23961 */ 24162 */ 23962 static int afpLock(sqlite3_file *id, int locktype){ 24163 static int afpLock(sqlite3_file *id, int locktype){ 23963 int rc = SQLITE_OK; 24164 int rc = SQLITE_OK; 23964 unixFile *pFile = (unixFile*)id; 24165 unixFile *pFile = (unixFile*)id; > 24166 struct unixLockInfo *pLock = pFile->pLock; 23965 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext; 24167 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext; 23966 24168 23967 assert( pFile ); 24169 assert( pFile ); 23968 OSTRACE5("LOCK %d %s was %s pid=%d (afp)\n", pFile->h, | 24170 OSTRACE7("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h, 23969 locktypeName(locktype), locktypeName(pFile->locktype), getpid()); | 24171 locktypeName(locktype), locktypeName(pFile->locktype), > 24172 locktypeName(pLock->locktype), pLock->cnt , getpid()); 23970 24173 23971 /* If there is already a lock of this type or more restrictive on the 24174 /* If there is already a lock of this type or more restrictive on the 23972 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as 24175 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as 23973 ** unixEnterMutex() hasn't been called yet. 24176 ** unixEnterMutex() hasn't been called yet. 23974 */ 24177 */ 23975 if( pFile->locktype>=locktype ){ 24178 if( pFile->locktype>=locktype ){ 23976 OSTRACE3("LOCK %d %s ok (already held) (afp)\n", pFile->h, 24179 OSTRACE3("LOCK %d %s ok (already held) (afp)\n", pFile->h, 23977 locktypeName(locktype)); 24180 locktypeName(locktype)); 23978 return SQLITE_OK; 24181 return SQLITE_OK; 23979 } 24182 } 23980 24183 23981 /* Make sure the locking sequence is correct 24184 /* Make sure the locking sequence is correct > 24185 ** (1) We never move from unlocked to anything higher than shared lock. > 24186 ** (2) SQLite never explicitly requests a pendig lock. > 24187 ** (3) A shared lock is always held when a reserve lock is requested. 23982 */ 24188 */ 23983 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK ); 24189 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK ); 23984 assert( locktype!=PENDING_LOCK ); 24190 assert( locktype!=PENDING_LOCK ); 23985 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK ); 24191 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK ); 23986 24192 23987 /* This mutex is needed because pFile->pLock is shared across threads 24193 /* This mutex is needed because pFile->pLock is shared across threads 23988 */ 24194 */ ................................................................................................................................................................................ 23990 24196 23991 /* Make sure the current thread owns the pFile. 24197 /* Make sure the current thread owns the pFile. 23992 */ 24198 */ 23993 rc = transferOwnership(pFile); 24199 rc = transferOwnership(pFile); 23994 if( rc!=SQLITE_OK ){ 24200 if( rc!=SQLITE_OK ){ 23995 unixLeaveMutex(); 24201 unixLeaveMutex(); 23996 return rc; 24202 return rc; > 24203 } > 24204 pLock = pFile->pLock; > 24205 > 24206 /* If some thread using this PID has a lock via a different unixFile* > 24207 ** handle that precludes the requested lock, return BUSY. > 24208 */ > 24209 if( (pFile->locktype!=pLock->locktype && > 24210 (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK)) > 24211 ){ > 24212 rc = SQLITE_BUSY; > 24213 goto afp_end_lock; > 24214 } > 24215 > 24216 /* If a SHARED lock is requested, and some thread using this PID already > 24217 ** has a SHARED or RESERVED lock, then increment reference counts and > 24218 ** return SQLITE_OK. > 24219 */ > 24220 if( locktype==SHARED_LOCK && > 24221 (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){ > 24222 assert( locktype==SHARED_LOCK ); > 24223 assert( pFile->locktype==0 ); > 24224 assert( pLock->cnt>0 ); > 24225 pFile->locktype = SHARED_LOCK; > 24226 pLock->cnt++; > 24227 pFile->pOpen->nLock++; > 24228 goto afp_end_lock; 23997 } 24229 } 23998 24230 23999 /* A PENDING lock is needed before acquiring a SHARED lock and before 24231 /* A PENDING lock is needed before acquiring a SHARED lock and before 24000 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will 24232 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will 24001 ** be released. 24233 ** be released. 24002 */ 24234 */ 24003 if( locktype==SHARED_LOCK 24235 if( locktype==SHARED_LOCK ................................................................................................................................................................................ 24011 } 24243 } 24012 } 24244 } 24013 24245 24014 /* If control gets to this point, then actually go ahead and make 24246 /* If control gets to this point, then actually go ahead and make 24015 ** operating system calls for the specified lock. 24247 ** operating system calls for the specified lock. 24016 */ 24248 */ 24017 if( locktype==SHARED_LOCK ){ 24249 if( locktype==SHARED_LOCK ){ 24018 int lk, lrc1, lrc2; | 24250 int lrc1, lrc2, lrc1Errno; 24019 int lrc1Errno = 0; | 24251 long lk, mask; 24020 24252 > 24253 assert( pLock->cnt==0 ); > 24254 assert( pLock->locktype==0 ); > 24255 > 24256 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff; 24021 /* Now get the read-lock SHARED_LOCK */ 24257 /* Now get the read-lock SHARED_LOCK */ 24022 /* note that the quality of the randomness doesn't matter that much */ 24258 /* note that the quality of the randomness doesn't matter that much */ 24023 lk = random(); 24259 lk = random(); 24024 context->sharedByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1); | 24260 pLock->sharedByte = (lk & mask)%(SHARED_SIZE - 1); 24025 lrc1 = afpSetLock(context->dbPath, pFile, 24261 lrc1 = afpSetLock(context->dbPath, pFile, 24026 SHARED_FIRST+context->sharedByte, 1, 1); | 24262 SHARED_FIRST+pLock->sharedByte, 1, 1); 24027 if( IS_LOCK_ERROR(lrc1) ){ 24263 if( IS_LOCK_ERROR(lrc1) ){ 24028 lrc1Errno = pFile->lastErrno; 24264 lrc1Errno = pFile->lastErrno; 24029 } 24265 } 24030 /* Drop the temporary PENDING lock */ 24266 /* Drop the temporary PENDING lock */ 24031 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0); 24267 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0); 24032 24268 24033 if( IS_LOCK_ERROR(lrc1) ) { 24269 if( IS_LOCK_ERROR(lrc1) ) { ................................................................................................................................................................................ 24038 rc = lrc2; 24274 rc = lrc2; 24039 goto afp_end_lock; 24275 goto afp_end_lock; 24040 } else if( lrc1 != SQLITE_OK ) { 24276 } else if( lrc1 != SQLITE_OK ) { 24041 rc = lrc1; 24277 rc = lrc1; 24042 } else { 24278 } else { 24043 pFile->locktype = SHARED_LOCK; 24279 pFile->locktype = SHARED_LOCK; 24044 pFile->pOpen->nLock++; 24280 pFile->pOpen->nLock++; > 24281 pLock->cnt = 1; 24045 } 24282 } > 24283 }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){ > 24284 /* We are trying for an exclusive lock but another thread in this > 24285 ** same process is still holding a shared lock. */ > 24286 rc = SQLITE_BUSY; 24046 }else{ 24287 }else{ 24047 /* The request was for a RESERVED or EXCLUSIVE lock. It is 24288 /* The request was for a RESERVED or EXCLUSIVE lock. It is 24048 ** assumed that there is a SHARED or greater lock on the file 24289 ** assumed that there is a SHARED or greater lock on the file 24049 ** already. 24290 ** already. 24050 */ 24291 */ 24051 int failed = 0; 24292 int failed = 0; 24052 assert( 0!=pFile->locktype ); 24293 assert( 0!=pFile->locktype ); 24053 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) { 24294 if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) { 24054 /* Acquire a RESERVED lock */ 24295 /* Acquire a RESERVED lock */ 24055 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1); 24296 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1); > 24297 if( !failed ){ > 24298 context->reserved = 1; > 24299 } 24056 } 24300 } 24057 if (!failed && locktype == EXCLUSIVE_LOCK) { 24301 if (!failed && locktype == EXCLUSIVE_LOCK) { 24058 /* Acquire an EXCLUSIVE lock */ 24302 /* Acquire an EXCLUSIVE lock */ 24059 24303 24060 /* Remove the shared lock before trying the range. we'll need to 24304 /* Remove the shared lock before trying the range. we'll need to 24061 ** reestablish the shared lock if we can't get the afpUnlock 24305 ** reestablish the shared lock if we can't get the afpUnlock 24062 */ 24306 */ 24063 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST + 24307 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST + 24064 context->sharedByte, 1, 0)) ){ | 24308 pLock->sharedByte, 1, 0)) ){ 24065 int failed2 = SQLITE_OK; 24309 int failed2 = SQLITE_OK; 24066 /* now attemmpt to get the exclusive lock range */ 24310 /* now attemmpt to get the exclusive lock range */ 24067 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 24311 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 24068 SHARED_SIZE, 1); 24312 SHARED_SIZE, 1); 24069 if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 24313 if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 24070 SHARED_FIRST + context->sharedByte, 1, 1)) ){ | 24314 SHARED_FIRST + pLock->sharedByte, 1, 1)) ){ 24071 /* Can't reestablish the shared lock. Sqlite can't deal, this is 24315 /* Can't reestablish the shared lock. Sqlite can't deal, this is 24072 ** a critical I/O error 24316 ** a critical I/O error 24073 */ 24317 */ 24074 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : 24318 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : 24075 SQLITE_IOERR_LOCK; 24319 SQLITE_IOERR_LOCK; 24076 goto afp_end_lock; 24320 goto afp_end_lock; 24077 } 24321 } ................................................................................................................................................................................ 24082 if( failed ){ 24326 if( failed ){ 24083 rc = failed; 24327 rc = failed; 24084 } 24328 } 24085 } 24329 } 24086 24330 24087 if( rc==SQLITE_OK ){ 24331 if( rc==SQLITE_OK ){ 24088 pFile->locktype = locktype; 24332 pFile->locktype = locktype; > 24333 pLock->locktype = locktype; 24089 }else if( locktype==EXCLUSIVE_LOCK ){ 24334 }else if( locktype==EXCLUSIVE_LOCK ){ 24090 pFile->locktype = PENDING_LOCK; 24335 pFile->locktype = PENDING_LOCK; > 24336 pLock->locktype = PENDING_LOCK; 24091 } 24337 } 24092 24338 24093 afp_end_lock: 24339 afp_end_lock: 24094 unixLeaveMutex(); 24340 unixLeaveMutex(); 24095 OSTRACE4("LOCK %d %s %s (afp)\n", pFile->h, locktypeName(locktype), 24341 OSTRACE4("LOCK %d %s %s (afp)\n", pFile->h, locktypeName(locktype), 24096 rc==SQLITE_OK ? "ok" : "failed"); 24342 rc==SQLITE_OK ? "ok" : "failed"); 24097 return rc; 24343 return rc; ................................................................................................................................................................................ 24103 ** 24349 ** 24104 ** If the locking level of the file descriptor is already at or below 24350 ** If the locking level of the file descriptor is already at or below 24105 ** the requested locking level, this routine is a no-op. 24351 ** the requested locking level, this routine is a no-op. 24106 */ 24352 */ 24107 static int afpUnlock(sqlite3_file *id, int locktype) { 24353 static int afpUnlock(sqlite3_file *id, int locktype) { 24108 int rc = SQLITE_OK; 24354 int rc = SQLITE_OK; 24109 unixFile *pFile = (unixFile*)id; 24355 unixFile *pFile = (unixFile*)id; > 24356 struct unixLockInfo *pLock; 24110 afpLockingContext *pCtx = (afpLockingContext *) pFile->lockingContext; | 24357 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext; > 24358 int skipShared = 0; > 24359 #ifdef SQLITE_TEST > 24360 int h = pFile->h; > 24361 #endif 24111 24362 24112 assert( pFile ); 24363 assert( pFile ); 24113 OSTRACE5("UNLOCK %d %d was %d pid=%d (afp)\n", pFile->h, locktype, | 24364 OSTRACE7("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, locktype, 24114 pFile->locktype, getpid()); < > 24365 pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid()) 24115 24366 24116 assert( locktype<=SHARED_LOCK ); 24367 assert( locktype<=SHARED_LOCK ); 24117 if( pFile->locktype<=locktype ){ 24368 if( pFile->locktype<=locktype ){ 24118 return SQLITE_OK; 24369 return SQLITE_OK; 24119 } 24370 } 24120 if( CHECK_THREADID(pFile) ){ 24371 if( CHECK_THREADID(pFile) ){ 24121 return SQLITE_MISUSE; | 24372 return SQLITE_MISUSE_BKPT; 24122 } 24373 } 24123 unixEnterMutex(); 24374 unixEnterMutex(); > 24375 pLock = pFile->pLock; > 24376 assert( pLock->cnt!=0 ); 24124 if( pFile->locktype>SHARED_LOCK ){ 24377 if( pFile->locktype>SHARED_LOCK ){ > 24378 assert( pLock->locktype==pFile->locktype ); > 24379 SimulateIOErrorBenign(1); > 24380 SimulateIOError( h=(-1) ) > 24381 SimulateIOErrorBenign(0); 24125 24382 > 24383 #ifndef NDEBUG > 24384 /* When reducing a lock such that other processes can start > 24385 ** reading the database file again, make sure that the > 24386 ** transaction counter was updated if any part of the database > 24387 ** file changed. If the transaction counter is not updated, > 24388 ** other connections to the same file might not realize that > 24389 ** the file has changed and hence might not know to flush their > 24390 ** cache. The use of a stale cache can lead to database corruption. > 24391 */ > 24392 assert( pFile->inNormalWrite==0 > 24393 || pFile->dbUpdate==0 > 24394 || pFile->transCntrChng==1 ); > 24395 pFile->inNormalWrite = 0; > 24396 #endif > 24397 24126 if( pFile->locktype==EXCLUSIVE_LOCK ){ 24398 if( pFile->locktype==EXCLUSIVE_LOCK ){ 24127 rc = afpSetLock(pCtx->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0); | 24399 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0); 24128 if( rc==SQLITE_OK && locktype==SHARED_LOCK ){ | 24400 if( rc==SQLITE_OK && (locktype==SHARED_LOCK || pLock->cnt>1) ){ 24129 /* only re-establish the shared lock if necessary */ 24401 /* only re-establish the shared lock if necessary */ 24130 int sharedLockByte = SHARED_FIRST+pCtx->sharedByte; | 24402 int sharedLockByte = SHARED_FIRST+pLock->sharedByte; 24131 rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 1); | 24403 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1); > 24404 } else { > 24405 skipShared = 1; 24132 } 24406 } 24133 } 24407 } 24134 if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){ 24408 if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){ 24135 rc = afpSetLock(pCtx->dbPath, pFile, PENDING_BYTE, 1, 0); | 24409 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0); 24136 } 24410 } 24137 if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK ){ | 24411 if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK && context->reserved ){ 24138 rc = afpSetLock(pCtx->dbPath, pFile, RESERVED_BYTE, 1, 0); | 24412 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0); > 24413 if( !rc ){ > 24414 context->reserved = 0; 24139 } | 24415 } > 24416 } > 24417 if( rc==SQLITE_OK && (locktype==SHARED_LOCK || pLock->cnt>1)){ > 24418 pLock->locktype = SHARED_LOCK; > 24419 } > 24420 } 24140 }else if( locktype==NO_LOCK ){ | 24421 if( rc==SQLITE_OK && locktype==NO_LOCK ){ > 24422 24141 /* clear the shared lock */ | 24423 /* Decrement the shared lock counter. Release the lock using an > 24424 ** OS call only when all threads in this same process have released > 24425 ** the lock. > 24426 */ 24142 int sharedLockByte = SHARED_FIRST+pCtx->sharedByte; | 24427 unsigned long long sharedLockByte = SHARED_FIRST+pLock->sharedByte; > 24428 pLock->cnt--; > 24429 if( pLock->cnt==0 ){ > 24430 SimulateIOErrorBenign(1); > 24431 SimulateIOError( h=(-1) ) > 24432 SimulateIOErrorBenign(0); > 24433 if( !skipShared ){ 24143 rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 0); | 24434 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0); 24144 } | 24435 } > 24436 if( !rc ){ > 24437 pLock->locktype = NO_LOCK; > 24438 pFile->locktype = NO_LOCK; 24145 | 24439 } > 24440 } 24146 if( rc==SQLITE_OK ){ | 24441 if( rc==SQLITE_OK ){ 24147 if( locktype==NO_LOCK ){ < 24148 struct unixOpenCnt *pOpen = pFile->pOpen; 24442 struct unixOpenCnt *pOpen = pFile->pOpen; > 24443 24149 pOpen->nLock--; 24444 pOpen->nLock--; 24150 assert( pOpen->nLock>=0 ); 24445 assert( pOpen->nLock>=0 ); 24151 if( pOpen->nLock==0 ){ 24446 if( pOpen->nLock==0 ){ 24152 rc = closePendingFds(pFile); 24447 rc = closePendingFds(pFile); 24153 } 24448 } 24154 } 24449 } 24155 } 24450 } > 24451 24156 unixLeaveMutex(); 24452 unixLeaveMutex(); 24157 if( rc==SQLITE_OK ){ < 24158 pFile->locktype = locktype; | 24453 if( rc==SQLITE_OK ) pFile->locktype = locktype; 24159 } < 24160 return rc; 24454 return rc; 24161 } 24455 } 24162 24456 24163 /* 24457 /* 24164 ** Close a file & cleanup AFP specific locking context 24458 ** Close a file & cleanup AFP specific locking context 24165 */ 24459 */ 24166 static int afpClose(sqlite3_file *id) { 24460 static int afpClose(sqlite3_file *id) { > 24461 int rc = SQLITE_OK; 24167 if( id ){ 24462 if( id ){ 24168 unixFile *pFile = (unixFile*)id; 24463 unixFile *pFile = (unixFile*)id; 24169 afpUnlock(id, NO_LOCK); 24464 afpUnlock(id, NO_LOCK); 24170 unixEnterMutex(); 24465 unixEnterMutex(); 24171 if( pFile->pOpen && pFile->pOpen->nLock ){ 24466 if( pFile->pOpen && pFile->pOpen->nLock ){ 24172 /* If there are outstanding locks, do not actually close the file just 24467 /* If there are outstanding locks, do not actually close the file just 24173 ** yet because that would clear those locks. Instead, add the file 24468 ** yet because that would clear those locks. Instead, add the file 24174 ** descriptor to pOpen->aPending. It will be automatically closed when 24469 ** descriptor to pOpen->aPending. It will be automatically closed when 24175 ** the last lock is cleared. 24470 ** the last lock is cleared. 24176 */ 24471 */ 24177 setPendingFd(pFile); 24472 setPendingFd(pFile); 24178 } 24473 } > 24474 releaseLockInfo(pFile->pLock); 24179 releaseOpenCnt(pFile->pOpen); 24475 releaseOpenCnt(pFile->pOpen); 24180 sqlite3_free(pFile->lockingContext); 24476 sqlite3_free(pFile->lockingContext); 24181 closeUnixFile(id); | 24477 rc = closeUnixFile(id); 24182 unixLeaveMutex(); 24478 unixLeaveMutex(); 24183 } 24479 } 24184 return SQLITE_OK; | 24480 return rc; 24185 } 24481 } 24186 24482 24187 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ 24483 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ 24188 /* 24484 /* 24189 ** The code above is the AFP lock implementation. The code is specific 24485 ** The code above is the AFP lock implementation. The code is specific 24190 ** to MacOSX and does not work on other unix platforms. No alternative 24486 ** to MacOSX and does not work on other unix platforms. No alternative 24191 ** is available. If you don't compile for a mac, then the "unix-afp" 24487 ** is available. If you don't compile for a mac, then the "unix-afp" 24192 ** VFS is not available. 24488 ** VFS is not available. 24193 ** 24489 ** 24194 ********************* End of the AFP lock implementation ********************** 24490 ********************* End of the AFP lock implementation ********************** 24195 ******************************************************************************/ 24491 ******************************************************************************/ 24196 24492 > 24493 /****************************************************************************** > 24494 *************************** Begin NFS Locking ********************************/ > 24495 > 24496 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE > 24497 /* > 24498 ** Lower the locking level on file descriptor pFile to locktype. locktype > 24499 ** must be either NO_LOCK or SHARED_LOCK. > 24500 ** > 24501 ** If the locking level of the file descriptor is already at or below > 24502 ** the requested locking level, this routine is a no-op. > 24503 */ > 24504 static int nfsUnlock(sqlite3_file *id, int locktype){ > 24505 return _posixUnlock(id, locktype, 1); > 24506 } > 24507 > 24508 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */ > 24509 /* > 24510 ** The code above is the NFS lock implementation. The code is specific > 24511 ** to MacOSX and does not work on other unix platforms. No alternative > 24512 ** is available. > 24513 ** > 24514 ********************* End of the NFS lock implementation ********************** > 24515 ******************************************************************************/ 24197 24516 24198 /****************************************************************************** 24517 /****************************************************************************** 24199 **************** Non-locking sqlite3_file methods ***************************** 24518 **************** Non-locking sqlite3_file methods ***************************** 24200 ** 24519 ** 24201 ** The next division contains implementations for all methods of the 24520 ** The next division contains implementations for all methods of the 24202 ** sqlite3_file object other than the locking methods. The locking 24521 ** sqlite3_file object other than the locking methods. The locking 24203 ** methods were defined in divisions above (one locking method per 24522 ** methods were defined in divisions above (one locking method per ................................................................................................................................................................................ 24216 ** See tickets #2741 and #2681. 24535 ** See tickets #2741 and #2681. 24217 ** 24536 ** 24218 ** To avoid stomping the errno value on a failed read the lastErrno value 24537 ** To avoid stomping the errno value on a failed read the lastErrno value 24219 ** is set before returning. 24538 ** is set before returning. 24220 */ 24539 */ 24221 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){ 24540 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){ 24222 int got; 24541 int got; > 24542 #if (!defined(USE_PREAD) && !defined(USE_PREAD64)) 24223 i64 newOffset; 24543 i64 newOffset; > 24544 #endif 24224 TIMER_START; 24545 TIMER_START; 24225 #if defined(USE_PREAD) 24546 #if defined(USE_PREAD) 24226 got = pread(id->h, pBuf, cnt, offset); 24547 got = pread(id->h, pBuf, cnt, offset); 24227 SimulateIOError( got = -1 ); 24548 SimulateIOError( got = -1 ); 24228 #elif defined(USE_PREAD64) 24549 #elif defined(USE_PREAD64) 24229 got = pread64(id->h, pBuf, cnt, offset); 24550 got = pread64(id->h, pBuf, cnt, offset); 24230 SimulateIOError( got = -1 ); 24551 SimulateIOError( got = -1 ); ................................................................................................................................................................................ 24290 ** Return the number of bytes actually read. Update the offset. 24611 ** Return the number of bytes actually read. Update the offset. 24291 ** 24612 ** 24292 ** To avoid stomping the errno value on a failed write the lastErrno value 24613 ** To avoid stomping the errno value on a failed write the lastErrno value 24293 ** is set before returning. 24614 ** is set before returning. 24294 */ 24615 */ 24295 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){ 24616 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){ 24296 int got; 24617 int got; > 24618 #if (!defined(USE_PREAD) && !defined(USE_PREAD64)) 24297 i64 newOffset; 24619 i64 newOffset; > 24620 #endif 24298 TIMER_START; 24621 TIMER_START; 24299 #if defined(USE_PREAD) 24622 #if defined(USE_PREAD) 24300 got = pwrite(id->h, pBuf, cnt, offset); 24623 got = pwrite(id->h, pBuf, cnt, offset); 24301 #elif defined(USE_PREAD64) 24624 #elif defined(USE_PREAD64) 24302 got = pwrite64(id->h, pBuf, cnt, offset); 24625 got = pwrite64(id->h, pBuf, cnt, offset); 24303 #else 24626 #else 24304 newOffset = lseek(id->h, offset, SEEK_SET); 24627 newOffset = lseek(id->h, offset, SEEK_SET); ................................................................................................................................................................................ 24484 ** isn't supported for this file system. So, attempt an fsync 24807 ** isn't supported for this file system. So, attempt an fsync 24485 ** and (for now) ignore the overhead of a superfluous fcntl call. 24808 ** and (for now) ignore the overhead of a superfluous fcntl call. 24486 ** It'd be better to detect fullfsync support once and avoid 24809 ** It'd be better to detect fullfsync support once and avoid 24487 ** the fcntl call every time sync is called. 24810 ** the fcntl call every time sync is called. 24488 */ 24811 */ 24489 if( rc ) rc = fsync(fd); 24812 if( rc ) rc = fsync(fd); 24490 24813 > 24814 #elif defined(__APPLE__) > 24815 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly > 24816 ** so currently we default to the macro that redefines fdatasync to fsync > 24817 */ > 24818 rc = fsync(fd); 24491 #else 24819 #else 24492 rc = fdatasync(fd); 24820 rc = fdatasync(fd); 24493 #if OS_VXWORKS 24821 #if OS_VXWORKS 24494 if( rc==-1 && errno==ENOTSUP ){ 24822 if( rc==-1 && errno==ENOTSUP ){ 24495 rc = fsync(fd); 24823 rc = fsync(fd); 24496 } 24824 } 24497 #endif /* OS_VXWORKS */ 24825 #endif /* OS_VXWORKS */ ................................................................................................................................................................................ 24818 afpClose, /* xClose method */ 25146 afpClose, /* xClose method */ 24819 afpLock, /* xLock method */ 25147 afpLock, /* xLock method */ 24820 afpUnlock, /* xUnlock method */ 25148 afpUnlock, /* xUnlock method */ 24821 afpCheckReservedLock /* xCheckReservedLock method */ 25149 afpCheckReservedLock /* xCheckReservedLock method */ 24822 ) 25150 ) 24823 #endif 25151 #endif 24824 25152 24825 /* < 24826 ** The "Whole File Locking" finder returns the same set of methods as < 24827 ** the posix locking finder. But it also sets the SQLITE_WHOLE_FILE_LOCKING < 24828 ** flag to force the posix advisory locks to cover the whole file instead < 24829 ** of just a small span of bytes near the 1GiB boundary. Whole File Locking < 24830 ** is useful on NFS-mounted files since it helps NFS to maintain cache < 24831 ** coherency. But it is a detriment to other filesystems since it runs < 24832 ** slower. < 24833 */ < 24834 static const sqlite3_io_methods *posixWflIoFinderImpl(const char*z, unixFile*p){ < 24835 UNUSED_PARAMETER(z); < 24836 p->fileFlags = SQLITE_WHOLE_FILE_LOCKING; < 24837 return &posixIoMethods; < 24838 } < 24839 static const sqlite3_io_methods < 24840 *(*const posixWflIoFinder)(const char*,unixFile *p) = posixWflIoFinderImpl; < 24841 < 24842 /* 25153 /* 24843 ** The proxy locking method is a "super-method" in the sense that it 25154 ** The proxy locking method is a "super-method" in the sense that it 24844 ** opens secondary file descriptors for the conch and lock files and 25155 ** opens secondary file descriptors for the conch and lock files and 24845 ** it uses proxy, dot-file, AFP, and flock() locking methods on those 25156 ** it uses proxy, dot-file, AFP, and flock() locking methods on those 24846 ** secondary files. For this reason, the division that implements 25157 ** secondary files. For this reason, the division that implements 24847 ** proxy locking is located much further down in the file. But we need 25158 ** proxy locking is located much further down in the file. But we need 24848 ** to go ahead and define the sqlite3_io_methods and finder function 25159 ** to go ahead and define the sqlite3_io_methods and finder function ................................................................................................................................................................................ 24859 proxyClose, /* xClose method */ 25170 proxyClose, /* xClose method */ 24860 proxyLock, /* xLock method */ 25171 proxyLock, /* xLock method */ 24861 proxyUnlock, /* xUnlock method */ 25172 proxyUnlock, /* xUnlock method */ 24862 proxyCheckReservedLock /* xCheckReservedLock method */ 25173 proxyCheckReservedLock /* xCheckReservedLock method */ 24863 ) 25174 ) 24864 #endif 25175 #endif 24865 25176 > 25177 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */ > 25178 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE > 25179 IOMETHODS( > 25180 nfsIoFinder, /* Finder function name */ > 25181 nfsIoMethods, /* sqlite3_io_methods object name */ > 25182 unixClose, /* xClose method */ > 25183 unixLock, /* xLock method */ > 25184 nfsUnlock, /* xUnlock method */ > 25185 unixCheckReservedLock /* xCheckReservedLock method */ > 25186 ) > 25187 #endif 24866 25188 24867 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE 25189 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE 24868 /* 25190 /* 24869 ** This "finder" function attempts to determine the best locking strategy 25191 ** This "finder" function attempts to determine the best locking strategy 24870 ** for the database file "filePath". It then returns the sqlite3_io_methods 25192 ** for the database file "filePath". It then returns the sqlite3_io_methods 24871 ** object that implements that strategy. 25193 ** object that implements that strategy. 24872 ** 25194 ** ................................................................................................................................................................................ 24879 static const struct Mapping { 25201 static const struct Mapping { 24880 const char *zFilesystem; /* Filesystem type name */ 25202 const char *zFilesystem; /* Filesystem type name */ 24881 const sqlite3_io_methods *pMethods; /* Appropriate locking method */ 25203 const sqlite3_io_methods *pMethods; /* Appropriate locking method */ 24882 } aMap[] = { 25204 } aMap[] = { 24883 { "hfs", &posixIoMethods }, 25205 { "hfs", &posixIoMethods }, 24884 { "ufs", &posixIoMethods }, 25206 { "ufs", &posixIoMethods }, 24885 { "afpfs", &afpIoMethods }, 25207 { "afpfs", &afpIoMethods }, 24886 #ifdef SQLITE_ENABLE_AFP_LOCKING_SMB < 24887 { "smbfs", &afpIoMethods }, 25208 { "smbfs", &afpIoMethods }, 24888 #else < 24889 { "smbfs", &flockIoMethods }, < 24890 #endif < 24891 { "webdav", &nolockIoMethods }, 25209 { "webdav", &nolockIoMethods }, 24892 { 0, 0 } 25210 { 0, 0 } 24893 }; 25211 }; 24894 int i; 25212 int i; 24895 struct statfs fsInfo; 25213 struct statfs fsInfo; 24896 struct flock lockInfo; 25214 struct flock lockInfo; 24897 25215 ................................................................................................................................................................................ 24916 ** assume that the file-system supports POSIX style locks. 25234 ** assume that the file-system supports POSIX style locks. 24917 */ 25235 */ 24918 lockInfo.l_len = 1; 25236 lockInfo.l_len = 1; 24919 lockInfo.l_start = 0; 25237 lockInfo.l_start = 0; 24920 lockInfo.l_whence = SEEK_SET; 25238 lockInfo.l_whence = SEEK_SET; 24921 lockInfo.l_type = F_RDLCK; 25239 lockInfo.l_type = F_RDLCK; 24922 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) { 25240 if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) { 24923 pNew->fileFlags = SQLITE_WHOLE_FILE_LOCKING; | 25241 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){ > 25242 return &nfsIoMethods; > 25243 } else { 24924 return &posixIoMethods; | 25244 return &posixIoMethods; > 25245 } 24925 }else{ 25246 }else{ 24926 return &dotlockIoMethods; 25247 return &dotlockIoMethods; 24927 } 25248 } 24928 } 25249 } 24929 static const sqlite3_io_methods 25250 static const sqlite3_io_methods 24930 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl; 25251 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl; 24931 25252 ................................................................................................................................................................................ 25028 /* Cache zFilename in the locking context (AFP and dotlock override) for 25349 /* Cache zFilename in the locking context (AFP and dotlock override) for 25029 ** proxyLock activation is possible (remote proxy is based on db name) 25350 ** proxyLock activation is possible (remote proxy is based on db name) 25030 ** zFilename remains valid until file is closed, to support */ 25351 ** zFilename remains valid until file is closed, to support */ 25031 pNew->lockingContext = (void*)zFilename; 25352 pNew->lockingContext = (void*)zFilename; 25032 #endif 25353 #endif 25033 } 25354 } 25034 25355 25035 if( pLockingStyle == &posixIoMethods ){ | 25356 if( pLockingStyle == &posixIoMethods > 25357 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE > 25358 || pLockingStyle == &nfsIoMethods > 25359 #endif > 25360 ){ 25036 unixEnterMutex(); 25361 unixEnterMutex(); 25037 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen); 25362 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen); 25038 if( rc!=SQLITE_OK ){ 25363 if( rc!=SQLITE_OK ){ 25039 /* If an error occured in findLockInfo(), close the file descriptor 25364 /* If an error occured in findLockInfo(), close the file descriptor 25040 ** immediately, before releasing the mutex. findLockInfo() may fail 25365 ** immediately, before releasing the mutex. findLockInfo() may fail 25041 ** in two scenarios: 25366 ** in two scenarios: 25042 ** 25367 ** ................................................................................................................................................................................ 25070 if( pCtx==0 ){ 25395 if( pCtx==0 ){ 25071 rc = SQLITE_NOMEM; 25396 rc = SQLITE_NOMEM; 25072 }else{ 25397 }else{ 25073 /* NB: zFilename exists and remains valid until the file is closed 25398 /* NB: zFilename exists and remains valid until the file is closed 25074 ** according to requirement F11141. So we do not need to make a 25399 ** according to requirement F11141. So we do not need to make a 25075 ** copy of the filename. */ 25400 ** copy of the filename. */ 25076 pCtx->dbPath = zFilename; 25401 pCtx->dbPath = zFilename; > 25402 pCtx->reserved = 0; 25077 srandomdev(); 25403 srandomdev(); 25078 unixEnterMutex(); 25404 unixEnterMutex(); 25079 rc = findLockInfo(pNew, NULL, &pNew->pOpen); | 25405 rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen); > 25406 if( rc!=SQLITE_OK ){ > 25407 sqlite3_free(pNew->lockingContext); > 25408 close(h); > 25409 h = -1; > 25410 } 25080 unixLeaveMutex(); 25411 unixLeaveMutex(); 25081 } 25412 } 25082 } 25413 } 25083 #endif 25414 #endif 25084 25415 25085 else if( pLockingStyle == &dotlockIoMethods ){ 25416 else if( pLockingStyle == &dotlockIoMethods ){ 25086 /* Dotfile locking uses the file path so it needs to be included in 25417 /* Dotfile locking uses the file path so it needs to be included in ................................................................................................................................................................................ 25121 unixLeaveMutex(); 25452 unixLeaveMutex(); 25122 } 25453 } 25123 #endif 25454 #endif 25124 25455 25125 pNew->lastErrno = 0; 25456 pNew->lastErrno = 0; 25126 #if OS_VXWORKS 25457 #if OS_VXWORKS 25127 if( rc!=SQLITE_OK ){ 25458 if( rc!=SQLITE_OK ){ > 25459 if( h>=0 ) close(h); > 25460 h = -1; 25128 unlink(zFilename); 25461 unlink(zFilename); 25129 isDelete = 0; 25462 isDelete = 0; 25130 } 25463 } 25131 pNew->isDelete = isDelete; 25464 pNew->isDelete = isDelete; 25132 #endif 25465 #endif 25133 if( rc!=SQLITE_OK ){ 25466 if( rc!=SQLITE_OK ){ 25134 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */ 25467 if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */ ................................................................................................................................................................................ 25164 #ifdef FD_CLOEXEC 25497 #ifdef FD_CLOEXEC 25165 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC); 25498 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC); 25166 #endif 25499 #endif 25167 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname); 25500 OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname); 25168 } 25501 } 25169 } 25502 } 25170 *pFd = fd; 25503 *pFd = fd; 25171 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN); | 25504 return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN_BKPT); 25172 } 25505 } 25173 25506 25174 /* 25507 /* 25175 ** Create a temporary file name in zBuf. zBuf must be allocated 25508 ** Create a temporary file name in zBuf. zBuf must be allocated 25176 ** by the calling process and must be big enough to hold at least 25509 ** by the calling process and must be big enough to hold at least 25177 ** pVfs->mxPathname bytes. 25510 ** pVfs->mxPathname bytes. 25178 */ 25511 */ ................................................................................................................................................................................ 25337 int rc = SQLITE_OK; /* Function Return Code */ 25670 int rc = SQLITE_OK; /* Function Return Code */ 25338 25671 25339 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE); 25672 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE); 25340 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE); 25673 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE); 25341 int isCreate = (flags & SQLITE_OPEN_CREATE); 25674 int isCreate = (flags & SQLITE_OPEN_CREATE); 25342 int isReadonly = (flags & SQLITE_OPEN_READONLY); 25675 int isReadonly = (flags & SQLITE_OPEN_READONLY); 25343 int isReadWrite = (flags & SQLITE_OPEN_READWRITE); 25676 int isReadWrite = (flags & SQLITE_OPEN_READWRITE); > 25677 #if SQLITE_ENABLE_LOCKING_STYLE > 25678 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY); > 25679 #endif 25344 25680 25345 /* If creating a master or main-file journal, this function will open 25681 /* If creating a master or main-file journal, this function will open 25346 ** a file-descriptor on the directory too. The first time unixSync() 25682 ** a file-descriptor on the directory too. The first time unixSync() 25347 ** is called the directory file descriptor will be fsync()ed and close()d. 25683 ** is called the directory file descriptor will be fsync()ed and close()d. 25348 */ 25684 */ 25349 int isOpenDirectory = (isCreate && 25685 int isOpenDirectory = (isCreate && 25350 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL) 25686 (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL) ................................................................................................................................................................................ 25424 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE); 25760 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE); 25425 openFlags &= ~(O_RDWR|O_CREAT); 25761 openFlags &= ~(O_RDWR|O_CREAT); 25426 flags |= SQLITE_OPEN_READONLY; 25762 flags |= SQLITE_OPEN_READONLY; 25427 openFlags |= O_RDONLY; 25763 openFlags |= O_RDONLY; 25428 fd = open(zName, openFlags, openMode); 25764 fd = open(zName, openFlags, openMode); 25429 } 25765 } 25430 if( fd<0 ){ 25766 if( fd<0 ){ 25431 rc = SQLITE_CANTOPEN; | 25767 rc = SQLITE_CANTOPEN_BKPT; 25432 goto open_finished; 25768 goto open_finished; 25433 } 25769 } 25434 } 25770 } 25435 assert( fd>=0 ); 25771 assert( fd>=0 ); 25436 if( pOutFlags ){ 25772 if( pOutFlags ){ 25437 *pOutFlags = flags; 25773 *pOutFlags = flags; 25438 } 25774 } ................................................................................................................................................................................ 25470 25806 25471 #ifdef FD_CLOEXEC 25807 #ifdef FD_CLOEXEC 25472 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC); 25808 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC); 25473 #endif 25809 #endif 25474 25810 25475 noLock = eType!=SQLITE_OPEN_MAIN_DB; 25811 noLock = eType!=SQLITE_OPEN_MAIN_DB; 25476 25812 > 25813 > 25814 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE > 25815 struct statfs fsInfo; > 25816 if( fstatfs(fd, &fsInfo) == -1 ){ > 25817 ((unixFile*)pFile)->lastErrno = errno; > 25818 if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */ > 25819 close(fd); /* silently leak if fail, in error */ > 25820 return SQLITE_IOERR_ACCESS; > 25821 } > 25822 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) { > 25823 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS; > 25824 } > 25825 #endif > 25826 > 25827 #if SQLITE_ENABLE_LOCKING_STYLE 25477 #if SQLITE_PREFER_PROXY_LOCKING 25828 #if SQLITE_PREFER_PROXY_LOCKING 25478 if( zPath!=NULL && !noLock && pVfs->xOpen ){ < > 25829 isAutoProxy = 1; > 25830 #endif > 25831 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){ 25479 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING"); 25832 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING"); 25480 int useProxy = 0; 25833 int useProxy = 0; 25481 25834 25482 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 25835 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 25483 ** never use proxy, NULL means use proxy for non-local files only. */ 25836 ** never use proxy, NULL means use proxy for non-local files only. */ 25484 if( envforce!=NULL ){ 25837 if( envforce!=NULL ){ 25485 useProxy = atoi(envforce)>0; 25838 useProxy = atoi(envforce)>0; ................................................................................................................................................................................ 25503 } 25856 } 25504 useProxy = !(fsInfo.f_flags&MNT_LOCAL); 25857 useProxy = !(fsInfo.f_flags&MNT_LOCAL); 25505 } 25858 } 25506 if( useProxy ){ 25859 if( useProxy ){ 25507 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete); 25860 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete); 25508 if( rc==SQLITE_OK ){ 25861 if( rc==SQLITE_OK ){ 25509 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:"); 25862 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:"); > 25863 if( rc!=SQLITE_OK ){ > 25864 /* Use unixClose to clean up the resources added in fillInUnixFile > 25865 ** and clear all the structure's references. Specifically, > 25866 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op > 25867 */ > 25868 unixClose(pFile); > 25869 return rc; > 25870 } 25510 } 25871 } 25511 goto open_finished; 25872 goto open_finished; 25512 } 25873 } 25513 } 25874 } 25514 #endif 25875 #endif 25515 25876 25516 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete); 25877 rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete); ................................................................................................................................................................................ 25623 25984 25624 zOut[nOut-1] = '\0'; 25985 zOut[nOut-1] = '\0'; 25625 if( zPath[0]=='/' ){ 25986 if( zPath[0]=='/' ){ 25626 sqlite3_snprintf(nOut, zOut, "%s", zPath); 25987 sqlite3_snprintf(nOut, zOut, "%s", zPath); 25627 }else{ 25988 }else{ 25628 int nCwd; 25989 int nCwd; 25629 if( getcwd(zOut, nOut-1)==0 ){ 25990 if( getcwd(zOut, nOut-1)==0 ){ 25630 return SQLITE_CANTOPEN; | 25991 return SQLITE_CANTOPEN_BKPT; 25631 } 25992 } 25632 nCwd = (int)strlen(zOut); 25993 nCwd = (int)strlen(zOut); 25633 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath); 25994 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath); 25634 } 25995 } 25635 return SQLITE_OK; 25996 return SQLITE_OK; 25636 } 25997 } 25637 25998 ................................................................................................................................................................................ 25930 ** will fail and SQLITE_BUSY is returned. 26291 ** will fail and SQLITE_BUSY is returned. 25931 ** 26292 ** 25932 ** The proxy file - a single-byte file used for all advisory file locks 26293 ** The proxy file - a single-byte file used for all advisory file locks 25933 ** normally taken on the database file. This allows for safe sharing 26294 ** normally taken on the database file. This allows for safe sharing 25934 ** of the database file for multiple readers and writers on the same 26295 ** of the database file for multiple readers and writers on the same 25935 ** host (the conch ensures that they all use the same local lock file). 26296 ** host (the conch ensures that they all use the same local lock file). 25936 ** 26297 ** 25937 ** There is a third file - the host ID file - used as a persistent record < 25938 ** of a unique identifier for the host, a 128-byte unique host id file < 25939 ** in the path defined by the HOSTIDPATH macro (default value is < 25940 ** /Library/Caches/.com.apple.sqliteConchHostId). < 25941 ** < 25942 ** Requesting the lock proxy does not immediately take the conch, it is 26298 ** Requesting the lock proxy does not immediately take the conch, it is 25943 ** only taken when the first request to lock database file is made. 26299 ** only taken when the first request to lock database file is made. 25944 ** This matches the semantics of the traditional locking behavior, where 26300 ** This matches the semantics of the traditional locking behavior, where 25945 ** opening a connection to a database file does not take a lock on it. 26301 ** opening a connection to a database file does not take a lock on it. 25946 ** The shared lock and an open file descriptor are maintained until 26302 ** The shared lock and an open file descriptor are maintained until 25947 ** the connection to the database is closed. 26303 ** the connection to the database is closed. 25948 ** 26304 ** ................................................................................................................................................................................ 25960 ** PRAGMA lock_proxy_file=":auto:" 26316 ** PRAGMA lock_proxy_file=":auto:" 25961 ** 26317 ** 25962 ** SQLITE_PROXY_DEBUG 26318 ** SQLITE_PROXY_DEBUG 25963 ** 26319 ** 25964 ** Enables the logging of error messages during host id file 26320 ** Enables the logging of error messages during host id file 25965 ** retrieval and creation 26321 ** retrieval and creation 25966 ** 26322 ** 25967 ** HOSTIDPATH < 25968 ** < 25969 ** Overrides the default host ID file path location < 25970 ** < 25971 ** LOCKPROXYDIR 26323 ** LOCKPROXYDIR 25972 ** 26324 ** 25973 ** Overrides the default directory used for lock proxy files that 26325 ** Overrides the default directory used for lock proxy files that 25974 ** are named automatically via the ":auto:" setting 26326 ** are named automatically via the ":auto:" setting 25975 ** 26327 ** 25976 ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 26328 ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 25977 ** 26329 ** ................................................................................................................................................................................ 25988 */ 26340 */ 25989 26341 25990 /* 26342 /* 25991 ** Proxy locking is only available on MacOSX 26343 ** Proxy locking is only available on MacOSX 25992 */ 26344 */ 25993 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE 26345 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE 25994 26346 25995 #ifdef SQLITE_TEST < 25996 /* simulate multiple hosts by creating unique hostid file paths */ < 25997 SQLITE_API int sqlite3_hostid_num = 0; < 25998 #endif < 25999 < 26000 /* 26347 /* 26001 ** The proxyLockingContext has the path and file structures for the remote 26348 ** The proxyLockingContext has the path and file structures for the remote 26002 ** and local proxy files in it 26349 ** and local proxy files in it 26003 */ 26350 */ 26004 typedef struct proxyLockingContext proxyLockingContext; 26351 typedef struct proxyLockingContext proxyLockingContext; 26005 struct proxyLockingContext { 26352 struct proxyLockingContext { 26006 unixFile *conchFile; /* Open conch file */ 26353 unixFile *conchFile; /* Open conch file */ 26007 char *conchFilePath; /* Name of the conch file */ 26354 char *conchFilePath; /* Name of the conch file */ 26008 unixFile *lockProxy; /* Open proxy lock file */ 26355 unixFile *lockProxy; /* Open proxy lock file */ 26009 char *lockProxyPath; /* Name of the proxy lock file */ 26356 char *lockProxyPath; /* Name of the proxy lock file */ 26010 char *dbPath; /* Name of the open file */ 26357 char *dbPath; /* Name of the open file */ 26011 int conchHeld; /* True if the conch is currently held */ | 26358 int conchHeld; /* 1 if the conch is held, -1 if lockless */ 26012 void *oldLockingContext; /* Original lockingcontext to restore on close */ 26359 void *oldLockingContext; /* Original lockingcontext to restore on close */ 26013 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */ 26360 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */ 26014 }; 26361 }; 26015 26362 26016 /* HOSTIDLEN and CONCHLEN both include space for the string < 26017 ** terminating nul < 26018 */ | 26363 /* > 26364 ** The proxy lock file path for the database at dbPath is written into lPath, > 26365 ** which must point to valid, writable memory large enough for a maxLen length 26019 #define HOSTIDLEN 128 | 26366 ** file path. 26020 #define CONCHLEN (MAXPATHLEN+HOSTIDLEN+1) < 26021 #ifndef HOSTIDPATH < 26022 # define HOSTIDPATH "/Library/Caches/.com.apple.sqliteConchHostId" < 26023 #endif < 26024 < 26025 /* basically a copy of unixRandomness with different < 26026 ** test behavior built in */ < 26027 static int proxyGenerateHostID(char *pHostID){ < 26028 int pid, fd, len; < 26029 unsigned char *key = (unsigned char *)pHostID; < 26030 < 26031 memset(key, 0, HOSTIDLEN); < 26032 len = 0; < 26033 fd = open("/dev/urandom", O_RDONLY); < 26034 if( fd>=0 ){ < 26035 len = read(fd, key, HOSTIDLEN); < 26036 close(fd); /* silently leak the fd if it fails */ < 26037 } < 26038 if( len < HOSTIDLEN ){ < 26039 time_t t; < 26040 time(&t); < 26041 memcpy(key, &t, sizeof(t)); < 26042 pid = getpid(); < 26043 memcpy(&key[sizeof(t)], &pid, sizeof(pid)); < 26044 } < 26045 < 26046 #ifdef MAKE_PRETTY_HOSTID < 26047 { < 26048 int i; < 26049 /* filter the bytes into printable ascii characters and NUL terminate */ < 26050 key[(HOSTIDLEN-1)] = 0x00; < 26051 for( i=0; i<(HOSTIDLEN-1); i++ ){ < 26052 unsigned char pa = key[i]&0x7F; < 26053 if( pa<0x20 ){ < 26054 key[i] = (key[i]&0x80 == 0x80) ? pa+0x40 : pa+0x20; < 26055 }else if( pa==0x7F ){ < 26056 key[i] = (key[i]&0x80 == 0x80) ? pa=0x20 : pa+0x7E; < 26057 } < 26058 } < 26059 } < 26060 #endif < 26061 return SQLITE_OK; < 26062 } < 26063 < 26064 /* writes the host id path to path, path should be an pre-allocated buffer < 26065 ** with enough space for a path < 26066 */ 26367 */ 26067 static void proxyGetHostIDPath(char *path, size_t len){ < 26068 strlcpy(path, HOSTIDPATH, len); < 26069 #ifdef SQLITE_TEST < 26070 if( sqlite3_hostid_num>0 ){ < 26071 char suffix[2] = "1"; < 26072 suffix[0] = suffix[0] + sqlite3_hostid_num; < 26073 strlcat(path, suffix, len); < 26074 } < 26075 #endif < 26076 OSTRACE3("GETHOSTIDPATH %s pid=%d\n", path, getpid()); < 26077 } < 26078 < 26079 /* get the host ID from a sqlite hostid file stored in the < 26080 ** user-specific tmp directory, create the ID if it's not there already < 26081 */ < 26082 static int proxyGetHostID(char *pHostID, int *pError){ < 26083 int fd; < 26084 char path[MAXPATHLEN]; < 26085 size_t len; < 26086 int rc=SQLITE_OK; < 26087 < 26088 proxyGetHostIDPath(path, MAXPATHLEN); < 26089 /* try to create the host ID file, if it already exists read the contents */ < 26090 fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644); < 26091 if( fd<0 ){ < 26092 int err=errno; < 26093 < 26094 if( err!=EEXIST ){ < 26095 #ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */ < 26096 fprintf(stderr, "sqlite error creating host ID file %s: %s\n", < 26097 path, strerror(err)); < 26098 #endif < 26099 return SQLITE_PERM; < 26100 } < 26101 /* couldn't create the file, read it instead */ < 26102 fd = open(path, O_RDONLY|O_EXCL); < 26103 if( fd<0 ){ < 26104 #ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */ < 26105 int err = errno; < 26106 fprintf(stderr, "sqlite error opening host ID file %s: %s\n", < 26107 path, strerror(err)); < 26108 #endif < 26109 return SQLITE_PERM; < 26110 } < 26111 len = pread(fd, pHostID, HOSTIDLEN, 0); < 26112 if( len<0 ){ < 26113 *pError = errno; < 26114 rc = SQLITE_IOERR_READ; < 26115 }else if( len<HOSTIDLEN ){ < 26116 *pError = 0; < 26117 rc = SQLITE_IOERR_SHORT_READ; < 26118 } < 26119 close(fd); /* silently leak the fd if it fails */ < 26120 OSTRACE3("GETHOSTID read %s pid=%d\n", pHostID, getpid()); < 26121 return rc; < 26122 }else{ < 26123 /* we're creating the host ID file (use a random string of bytes) */ < 26124 proxyGenerateHostID(pHostID); < 26125 len = pwrite(fd, pHostID, HOSTIDLEN, 0); < 26126 if( len<0 ){ < 26127 *pError = errno; < 26128 rc = SQLITE_IOERR_WRITE; < 26129 }else if( len<HOSTIDLEN ){ < 26130 *pError = 0; < 26131 rc = SQLITE_IOERR_WRITE; < 26132 } < 26133 close(fd); /* silently leak the fd if it fails */ < 26134 OSTRACE3("GETHOSTID wrote %s pid=%d\n", pHostID, getpid()); < 26135 return rc; < 26136 } < 26137 } < 26138 < 26139 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){ 26368 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){ 26140 int len; 26369 int len; 26141 int dbLen; 26370 int dbLen; 26142 int i; 26371 int i; 26143 26372 26144 #ifdef LOCKPROXYDIR 26373 #ifdef LOCKPROXYDIR 26145 len = strlcpy(lPath, LOCKPROXYDIR, maxLen); 26374 len = strlcpy(lPath, LOCKPROXYDIR, maxLen); 26146 #else 26375 #else 26147 # ifdef _CS_DARWIN_USER_TEMP_DIR 26376 # ifdef _CS_DARWIN_USER_TEMP_DIR 26148 { 26377 { 26149 confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen); | 26378 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){ 26150 len = strlcat(lPath, "sqliteplocks", maxLen); < 26151 if( mkdir(lPath, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){ < 26152 /* if mkdir fails, handle as lock file creation failure */ < 26153 # ifdef SQLITE_DEBUG < 26154 int err = errno; < 26155 if( err!=EEXIST ){ < 26156 fprintf(stderr, "proxyGetLockPath: mkdir(%s,0%o) error %d %s\n", lPath, < 26157 SQLITE_DEFAULT_PROXYDIR_PERMISSIONS, err, strerror(err)); < > 26379 OSTRACE4("GETLOCKPATH failed %s errno=%d pid=%d\n", > 26380 lPath, errno, getpid()); > 26381 return SQLITE_IOERR_LOCK; 26158 } | 26382 } 26159 # endif < 26160 }else{ < 26161 OSTRACE3("GETLOCKPATH mkdir %s pid=%d\n", lPath, getpid()); < 26162 } < 26163 < > 26383 len = strlcat(lPath, "sqliteplocks", maxLen); 26164 } 26384 } 26165 # else 26385 # else 26166 len = strlcpy(lPath, "/tmp/", maxLen); 26386 len = strlcpy(lPath, "/tmp/", maxLen); 26167 # endif 26387 # endif 26168 #endif 26388 #endif 26169 26389 26170 if( lPath[len-1]!='/' ){ 26390 if( lPath[len-1]!='/' ){ ................................................................................................................................................................................ 26175 dbLen = (int)strlen(dbPath); 26395 dbLen = (int)strlen(dbPath); 26176 for( i=0; i<dbLen && (i+len+7)<maxLen; i++){ 26396 for( i=0; i<dbLen && (i+len+7)<maxLen; i++){ 26177 char c = dbPath[i]; 26397 char c = dbPath[i]; 26178 lPath[i+len] = (c=='/')?'_':c; 26398 lPath[i+len] = (c=='/')?'_':c; 26179 } 26399 } 26180 lPath[i+len]='\0'; 26400 lPath[i+len]='\0'; 26181 strlcat(lPath, ":auto:", maxLen); 26401 strlcat(lPath, ":auto:", maxLen); > 26402 OSTRACE3("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()); 26182 return SQLITE_OK; 26403 return SQLITE_OK; 26183 } 26404 } > 26405 > 26406 /* > 26407 ** Creates the lock file and any missing directories in lockPath > 26408 */ > 26409 static int proxyCreateLockPath(const char *lockPath){ > 26410 int i, len; > 26411 char buf[MAXPATHLEN]; > 26412 int start = 0; > 26413 > 26414 assert(lockPath!=NULL); > 26415 /* try to create all the intermediate directories */ > 26416 len = (int)strlen(lockPath); > 26417 buf[0] = lockPath[0]; > 26418 for( i=1; i<len; i++ ){ > 26419 if( lockPath[i] == '/' && (i - start > 0) ){ > 26420 /* only mkdir if leaf dir != "." or "/" or ".." */ > 26421 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') > 26422 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){ > 26423 buf[i]='\0'; > 26424 if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){ > 26425 int err=errno; > 26426 if( err!=EEXIST ) { > 26427 OSTRACE5("CREATELOCKPATH FAILED creating %s, " > 26428 "'%s' proxy lock path=%s pid=%d\n", > 26429 buf, strerror(err), lockPath, getpid()); > 26430 return err; > 26431 } > 26432 } > 26433 } > 26434 start=i+1; > 26435 } > 26436 buf[i] = lockPath[i]; > 26437 } > 26438 OSTRACE3("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()); > 26439 return 0; > 26440 } 26184 26441 26185 /* 26442 /* 26186 ** Create a new VFS file descriptor (stored in memory obtained from 26443 ** Create a new VFS file descriptor (stored in memory obtained from 26187 ** sqlite3_malloc) and open the file named "path" in the file descriptor. 26444 ** sqlite3_malloc) and open the file named "path" in the file descriptor. 26188 ** 26445 ** 26189 ** The caller is responsible not only for closing the file descriptor 26446 ** The caller is responsible not only for closing the file descriptor 26190 ** but also for freeing the memory associated with the file descriptor. 26447 ** but also for freeing the memory associated with the file descriptor. 26191 */ 26448 */ 26192 static int proxyCreateUnixFile(const char *path, unixFile **ppFile) { | 26449 static int proxyCreateUnixFile( > 26450 const char *path, /* path for the new unixFile */ > 26451 unixFile **ppFile, /* unixFile created and returned by ref */ > 26452 int islockfile /* if non zero missing dirs will be created */ > 26453 ) { > 26454 int fd = -1; > 26455 int dirfd = -1; 26193 unixFile *pNew; 26456 unixFile *pNew; 26194 int flags = SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE; < 26195 int rc = SQLITE_OK; 26457 int rc = SQLITE_OK; > 26458 int openFlags = O_RDWR | O_CREAT; 26196 sqlite3_vfs dummyVfs; 26459 sqlite3_vfs dummyVfs; > 26460 int terrno = 0; > 26461 UnixUnusedFd *pUnused = NULL; 26197 26462 > 26463 /* 1. first try to open/create the file > 26464 ** 2. if that fails, and this is a lock file (not-conch), try creating > 26465 ** the parent directories and then try again. > 26466 ** 3. if that fails, try to open the file read-only > 26467 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file > 26468 */ > 26469 pUnused = findReusableFd(path, openFlags); > 26470 if( pUnused ){ > 26471 fd = pUnused->fd; > 26472 }else{ 26198 pNew = (unixFile *)sqlite3_malloc(sizeof(unixFile)); | 26473 pUnused = sqlite3_malloc(sizeof(*pUnused)); 26199 if( !pNew ){ | 26474 if( !pUnused ){ 26200 return SQLITE_NOMEM; | 26475 return SQLITE_NOMEM; 26201 } | 26476 } > 26477 } > 26478 if( fd<0 ){ > 26479 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS); > 26480 terrno = errno; > 26481 if( fd<0 && errno==ENOENT && islockfile ){ > 26482 if( proxyCreateLockPath(path) == SQLITE_OK ){ > 26483 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS); > 26484 } > 26485 } > 26486 } > 26487 if( fd<0 ){ > 26488 openFlags = O_RDONLY; > 26489 fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS); > 26490 terrno = errno; > 26491 } > 26492 if( fd<0 ){ > 26493 if( islockfile ){ > 26494 return SQLITE_BUSY; > 26495 } > 26496 switch (terrno) { > 26497 case EACCES: > 26498 return SQLITE_PERM; > 26499 case EIO: > 26500 return SQLITE_IOERR_LOCK; /* even though it is the conch */ > 26501 default: > 26502 return SQLITE_CANTOPEN_BKPT; > 26503 } > 26504 } > 26505 > 26506 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew)); > 26507 if( pNew==NULL ){ > 26508 rc = SQLITE_NOMEM; > 26509 goto end_create_proxy; > 26510 } 26202 memset(pNew, 0, sizeof(unixFile)); 26511 memset(pNew, 0, sizeof(unixFile)); > 26512 pNew->openFlags = openFlags; > 26513 dummyVfs.pAppData = (void*)&autolockIoFinder; > 26514 pUnused->fd = fd; > 26515 pUnused->flags = openFlags; > 26516 pNew->pUnused = pUnused; 26203 | 26517 26204 /* Call unixOpen() to open the proxy file. The flags passed to unixOpen() < 26205 ** suggest that the file being opened is a "main database". This is < 26206 ** necessary as other file types do not necessarily support locking. It < 26207 ** is better to use unixOpen() instead of opening the file directly with < 26208 ** open(), as unixOpen() sets up the various mechanisms required to < 26209 ** make sure a call to close() does not cause the system to discard < 26210 ** POSIX locks prematurely. < > 26518 rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0); > 26519 if( rc==SQLITE_OK ){ > 26520 *ppFile = pNew; > 26521 return SQLITE_OK; > 26522 } > 26523 end_create_proxy: > 26524 close(fd); /* silently leak fd if error, we're already in error */ > 26525 sqlite3_free(pNew); > 26526 sqlite3_free(pUnused); > 26527 return rc; > 26528 } > 26529 > 26530 #ifdef SQLITE_TEST > 26531 /* simulate multiple hosts by creating unique hostid file paths */ > 26532 SQLITE_API int sqlite3_hostid_num = 0; > 26533 #endif > 26534 > 26535 #define PROXY_HOSTIDLEN 16 /* conch file host id length */ > 26536 > 26537 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN > 26538 ** bytes of writable memory. 26211 ** | 26539 */ 26212 ** It is important that the xOpen member of the VFS object passed to < 26213 ** unixOpen() is NULL. This tells unixOpen() may try to open a proxy-file < 26214 ** for the proxy-file (creating a potential infinite loop). < > 26540 static int proxyGetHostID(unsigned char *pHostID, int *pError){ > 26541 struct timespec timeout = {1, 0}; /* 1 sec timeout */ > 26542 > 26543 assert(PROXY_HOSTIDLEN == sizeof(uuid_t)); > 26544 memset(pHostID, 0, PROXY_HOSTIDLEN); > 26545 if( gethostuuid(pHostID, &timeout) ){ > 26546 int err = errno; > 26547 if( pError ){ > 26548 *pError = err; > 26549 } > 26550 return SQLITE_IOERR; > 26551 } > 26552 #ifdef SQLITE_TEST > 26553 /* simulate multiple hosts by creating unique hostid file paths */ > 26554 if( sqlite3_hostid_num != 0){ > 26555 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF)); > 26556 } > 26557 #endif > 26558 > 26559 return SQLITE_OK; > 26560 } > 26561 > 26562 /* The conch file contains the header, host id and lock file path 26215 */ | 26563 */ 26216 dummyVfs.pAppData = (void*)&autolockIoFinder; < > 26564 #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */ > 26565 #define PROXY_HEADERLEN 1 /* conch file header length */ > 26566 #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN) > 26567 #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN) > 26568 > 26569 /* > 26570 ** Takes an open conch file, copies the contents to a new path and then moves > 26571 ** it back. The newly created file's file descriptor is assigned to the > 26572 ** conch file structure and finally the original conch file descriptor is > 26573 ** closed. Returns zero if successful. > 26574 */ > 26575 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){ > 26576 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; > 26577 unixFile *conchFile = pCtx->conchFile; > 26578 char tPath[MAXPATHLEN]; > 26579 char buf[PROXY_MAXCONCHLEN]; > 26580 char *cPath = pCtx->conchFilePath; > 26581 size_t readLen = 0; > 26582 size_t pathLen = 0; > 26583 char errmsg[64] = ""; > 26584 int fd = -1; > 26585 int rc = -1; > 26586 > 26587 /* create a new path by replace the trailing '-conch' with '-break' */ > 26588 pathLen = strlcpy(tPath, cPath, MAXPATHLEN); > 26589 if( pathLen>MAXPATHLEN || pathLen<6 || > 26590 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){ > 26591 sprintf(errmsg, "path error (len %d)", (int)pathLen); > 26592 goto end_breaklock; > 26593 } > 26594 /* read the conch content */ > 26595 readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0); > 26596 if( readLen<PROXY_PATHINDEX ){ > 26597 sprintf(errmsg, "read error (len %d)", (int)readLen); > 26598 goto end_breaklock; > 26599 } > 26600 /* write it out to the temporary break file */ > 26601 fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS); > 26602 if( fd<0 ){ > 26603 sprintf(errmsg, "create failed (%d)", errno); > 26604 goto end_breaklock; > 26605 } > 26606 if( pwrite(fd, buf, readLen, 0) != readLen ){ > 26607 sprintf(errmsg, "write failed (%d)", errno); > 26608 goto end_breaklock; > 26609 } > 26610 if( rename(tPath, cPath) ){ > 26611 sprintf(errmsg, "rename failed (%d)", errno); > 26612 goto end_breaklock; > 26613 } 26217 dummyVfs.xOpen = 0; | 26614 rc = 0; 26218 rc = unixOpen(&dummyVfs, path, (sqlite3_file *)pNew, flags, &flags); < > 26615 fprintf(stderr, "broke stale lock on %s\n", cPath); > 26616 close(conchFile->h); > 26617 conchFile->h = fd; > 26618 conchFile->openFlags = O_RDWR | O_CREAT; > 26619 > 26620 end_breaklock: > 26621 if( rc ){ > 26622 if( fd>=0 ){ > 26623 unlink(tPath); > 26624 close(fd); > 26625 } > 26626 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg); > 26627 } > 26628 return rc; > 26629 } > 26630 > 26631 /* Take the requested lock on the conch file and break a stale lock if the > 26632 ** host id matches. > 26633 */ > 26634 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){ > 26635 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; > 26636 unixFile *conchFile = pCtx->conchFile; > 26637 int rc = SQLITE_OK; > 26638 int nTries = 0; > 26639 struct timespec conchModTime; > 26640 > 26641 do { > 26642 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType); > 26643 nTries ++; 26219 if( rc==SQLITE_OK && (flags&SQLITE_OPEN_READONLY) ){ | 26644 if( rc==SQLITE_BUSY ){ 26220 pNew->pMethod->xClose((sqlite3_file *)pNew); < > 26645 /* If the lock failed (busy): > 26646 * 1st try: get the mod time of the conch, wait 0.5s and try again. > 26647 * 2nd try: fail if the mod time changed or host id is different, wait > 26648 * 10 sec and try again > 26649 * 3rd try: break the lock unless the mod time has changed. > 26650 */ > 26651 struct stat buf; > 26652 if( fstat(conchFile->h, &buf) ){ > 26653 pFile->lastErrno = errno; > 26654 return SQLITE_IOERR_LOCK; > 26655 } > 26656 > 26657 if( nTries==1 ){ > 26658 conchModTime = buf.st_mtimespec; > 26659 usleep(500000); /* wait 0.5 sec and try the lock again*/ > 26660 continue; > 26661 } > 26662 > 26663 assert( nTries>1 ); > 26664 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || > 26665 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){ 26221 rc = SQLITE_CANTOPEN; | 26666 return SQLITE_BUSY; 26222 } | 26667 } 26223 | 26668 > 26669 if( nTries==2 ){ > 26670 char tBuf[PROXY_MAXCONCHLEN]; > 26671 int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0); > 26672 if( len<0 ){ > 26673 pFile->lastErrno = errno; > 26674 return SQLITE_IOERR_LOCK; > 26675 } > 26676 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){ > 26677 /* don't break the lock if the host id doesn't match */ > 26678 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){ > 26679 return SQLITE_BUSY; > 26680 } > 26681 }else{ > 26682 /* don't break the lock on short read or a version mismatch */ > 26683 return SQLITE_BUSY; > 26684 } > 26685 usleep(10000000); /* wait 10 sec and try the lock again */ > 26686 continue; > 26687 } > 26688 > 26689 assert( nTries==3 ); > 26690 if( 0==proxyBreakConchLock(pFile, myHostID) ){ 26224 if( rc!=SQLITE_OK ){ | 26691 rc = SQLITE_OK; 26225 sqlite3_free(pNew); < 26226 pNew = 0; < > 26692 if( lockType==EXCLUSIVE_LOCK ){ > 26693 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK); 26227 } | 26694 } > 26695 if( !rc ){ > 26696 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType); 26228 | 26697 } 26229 *ppFile = pNew; < > 26698 } > 26699 } > 26700 } while( rc==SQLITE_BUSY && nTries<3 ); > 26701 26230 return rc; 26702 return rc; 26231 } 26703 } 26232 26704 26233 /* takes the conch by taking a shared lock and read the contents conch, if | 26705 /* Takes the conch by taking a shared lock and read the contents conch, if 26234 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL 26706 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL 26235 ** lockPath means that the lockPath in the conch file will be used if the 26707 ** lockPath means that the lockPath in the conch file will be used if the 26236 ** host IDs match, or a new lock path will be generated automatically 26708 ** host IDs match, or a new lock path will be generated automatically 26237 ** and written to the conch file. 26709 ** and written to the conch file. 26238 */ 26710 */ 26239 static int proxyTakeConch(unixFile *pFile){ 26711 static int proxyTakeConch(unixFile *pFile){ 26240 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 26712 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 26241 26713 26242 if( pCtx->conchHeld>0 ){ | 26714 if( pCtx->conchHeld!=0 ){ 26243 return SQLITE_OK; 26715 return SQLITE_OK; 26244 }else{ 26716 }else{ 26245 unixFile *conchFile = pCtx->conchFile; 26717 unixFile *conchFile = pCtx->conchFile; 26246 char testValue[CONCHLEN]; | 26718 uuid_t myHostID; 26247 char conchValue[CONCHLEN]; | 26719 int pError = 0; > 26720 char readBuf[PROXY_MAXCONCHLEN]; 26248 char lockPath[MAXPATHLEN]; 26721 char lockPath[MAXPATHLEN]; 26249 char *tLockPath = NULL; | 26722 char *tempLockPath = NULL; 26250 int rc = SQLITE_OK; 26723 int rc = SQLITE_OK; > 26724 int createConch = 0; > 26725 int hostIdMatch = 0; 26251 int readRc = SQLITE_OK; | 26726 int readLen = 0; 26252 int syncPerms = 0; < > 26727 int tryOldLockPath = 0; > 26728 int forceNewLockPath = 0; 26253 | 26729 26254 OSTRACE4("TAKECONCH %d for %s pid=%d\n", conchFile->h, 26730 OSTRACE4("TAKECONCH %d for %s pid=%d\n", conchFile->h, 26255 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()); 26731 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()); 26256 26732 26257 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK); < 26258 if( rc==SQLITE_OK ){ < 26259 int pError = 0; < 26260 memset(testValue, 0, CONCHLEN); /* conch is fixed size */ < 26261 rc = proxyGetHostID(testValue, &pError); | 26733 rc = proxyGetHostID(myHostID, &pError); 26262 if( (rc&0xff)==SQLITE_IOERR ){ | 26734 if( (rc&0xff)==SQLITE_IOERR ){ 26263 pFile->lastErrno = pError; | 26735 pFile->lastErrno = pError; > 26736 goto end_takeconch; 26264 } | 26737 } 26265 if( pCtx->lockProxyPath ){ < 26266 strlcpy(&testValue[HOSTIDLEN], pCtx->lockProxyPath, MAXPATHLEN); | 26738 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK); 26267 } < 26268 } < 26269 if( rc!=SQLITE_OK ){ 26739 if( rc!=SQLITE_OK ){ 26270 goto end_takeconch; 26740 goto end_takeconch; > 26741 } > 26742 /* read the existing conch file */ > 26743 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN); > 26744 if( readLen<0 ){ > 26745 /* I/O error: lastErrno set by seekAndRead */ > 26746 pFile->lastErrno = conchFile->lastErrno; > 26747 rc = SQLITE_IOERR_READ; > 26748 goto end_takeconch; ................................................................................................................................................................................ 26271 } | 26749 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 26272 < > 26750 readBuf[0]!=(char)PROXY_CONCHVERSION ){ 26273 readRc = unixRead((sqlite3_file *)conchFile, conchValue, CONCHLEN, 0); | 26751 /* a short read or version format mismatch means we need to create a new 26274 if( readRc!=SQLITE_IOERR_SHORT_READ ){ | 26752 ** conch file. 26275 if( readRc!=SQLITE_OK ){ < > 26753 */ 26276 if( (rc&0xff)==SQLITE_IOERR ){ | 26754 createConch = 1; 26277 pFile->lastErrno = conchFile->lastErrno; < 26278 } | 26755 } > 26756 /* if the host id matches and the lock path already exists in the conch 26279 rc = readRc; | 26757 ** we'll try to use the path there, if we can't open that path, we'll 26280 goto end_takeconch; | 26758 ** retry with a new auto-generated path > 26759 */ > 26760 do { /* in case we need to try again for an :auto: named lock file */ 26281 } | 26761 > 26762 if( !createConch && !forceNewLockPath ){ > 26763 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, > 26764 PROXY_HOSTIDLEN); 26282 /* if the conch has data compare the contents */ | 26765 /* if the conch has data compare the contents */ 26283 if( !pCtx->lockProxyPath ){ | 26766 if( !pCtx->lockProxyPath ){ 26284 /* for auto-named local lock file, just check the host ID and we'll | 26767 /* for auto-named local lock file, just check the host ID and we'll 26285 ** use the local lock file path that's already in there */ | 26768 ** use the local lock file path that's already in there 26286 if( !memcmp(testValue, conchValue, HOSTIDLEN) ){ < 26287 tLockPath = (char *)&conchValue[HOSTIDLEN]; < > 26769 */ > 26770 if( hostIdMatch ){ > 26771 size_t pathLen = (readLen - PROXY_PATHINDEX); > 26772 > 26773 if( pathLen>=MAXPATHLEN ){ > 26774 pathLen=MAXPATHLEN-1; > 26775 } > 26776 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen); > 26777 lockPath[pathLen] = 0; > 26778 tempLockPath = lockPath; > 26779 tryOldLockPath = 1; > 26780 /* create a copy of the lock path if the conch is taken */ 26288 goto end_takeconch; | 26781 goto end_takeconch; 26289 } | 26782 } 26290 }else{ | 26783 }else if( hostIdMatch 26291 /* we've got the conch if conchValue matches our path and host ID */ < 26292 if( !memcmp(testValue, conchValue, CONCHLEN) ){ < > 26784 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX], > 26785 readLen-PROXY_PATHINDEX) > 26786 ){ > 26787 /* conch host and lock path match */ 26293 goto end_takeconch; | 26788 goto end_takeconch; 26294 } 26789 } 26295 } 26790 } 26296 }else{ < 26297 /* a short read means we're "creating" the conch (even though it could < 26298 ** have been user-intervention), if we acquire the exclusive lock, < 26299 ** we'll try to match the current on-disk permissions of the database < 26300 */ < 26301 syncPerms = 1; < 26302 } | 26791 > 26792 /* if the conch isn't writable and doesn't match, we can't take it */ > 26793 if( (conchFile->openFlags&O_RDWR) == 0 ){ > 26794 rc = SQLITE_BUSY; > 26795 goto end_takeconch; 26303 | 26796 } 26304 /* either conch was emtpy or didn't match */ < > 26797 > 26798 /* either the conch didn't match or we need to create a new one */ 26305 if( !pCtx->lockProxyPath ){ | 26799 if( !pCtx->lockProxyPath ){ 26306 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN); | 26800 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN); 26307 tLockPath = lockPath; | 26801 tempLockPath = lockPath; 26308 strlcpy(&testValue[HOSTIDLEN], lockPath, MAXPATHLEN); < > 26802 /* create a copy of the lock path _only_ if the conch is taken */ 26309 } | 26803 } 26310 26804 26311 /* update conch with host and path (this will fail if other process | 26805 /* update conch with host and path (this will fail if other process 26312 ** has a shared lock already) */ | 26806 ** has a shared lock already), if the host id matches, use the big > 26807 ** stick. > 26808 */ > 26809 futimes(conchFile->h, NULL); > 26810 if( hostIdMatch && !createConch ){ > 26811 if( conchFile->pLock && conchFile->pLock->cnt>1 ){ > 26812 /* We are trying for an exclusive lock but another thread in this > 26813 ** same process is still holding a shared lock. */ > 26814 rc = SQLITE_BUSY; > 26815 } else { > 26816 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK); > 26817 } > 26818 }else{ 26313 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK); | 26819 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK) > 26820 } 26314 if( rc==SQLITE_OK ){ | 26821 if( rc==SQLITE_OK ){ > 26822 char writeBuffer[PROXY_MAXCONCHLEN]; > 26823 int writeSize = 0; > 26824 > 26825 writeBuffer[0] = (char)PROXY_CONCHVERSION; > 26826 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN); > 26827 if( pCtx->lockProxyPath!=NULL ){ > 26828 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN > 26829 }else{ > 26830 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN); > 26831 } > 26832 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]); > 26833 ftruncate(conchFile->h, writeSize); 26315 rc = unixWrite((sqlite3_file *)conchFile, testValue, CONCHLEN, 0); | 26834 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0); > 26835 fsync(conchFile->h); > 26836 /* If we created a new conch file (not just updated the contents of a > 26837 ** valid conch file), try to match the permissions of the database > 26838 */ 26316 if( rc==SQLITE_OK && syncPerms ){ | 26839 if( rc==SQLITE_OK && createConch ){ 26317 struct stat buf; | 26840 struct stat buf; 26318 int err = fstat(pFile->h, &buf); | 26841 int err = fstat(pFile->h, &buf); 26319 if( err==0 ){ | 26842 if( err==0 ){ > 26843 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP | > 26844 S_IROTH|S_IWOTH); 26320 /* try to match the database file permissions, ignore failure */ | 26845 /* try to match the database file R/W permissions, ignore failure */ 26321 #ifndef SQLITE_PROXY_DEBUG 26846 #ifndef SQLITE_PROXY_DEBUG 26322 fchmod(conchFile->h, buf.st_mode); | 26847 fchmod(conchFile->h, cmode); 26323 #else 26848 #else 26324 if( fchmod(conchFile->h, buf.st_mode)!=0 ){ | 26849 if( fchmod(conchFile->h, cmode)!=0 ){ 26325 int code = errno; | 26850 int code = errno; 26326 fprintf(stderr, "fchmod %o FAILED with %d %s\n", | 26851 fprintf(stderr, "fchmod %o FAILED with %d %s\n", 26327 buf.st_mode, code, strerror(code)); | 26852 cmode, code, strerror(code)); 26328 } else { | 26853 } else { 26329 fprintf(stderr, "fchmod %o SUCCEDED\n",buf.st_mode); | 26854 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode); 26330 } | 26855 } 26331 }else{ | 26856 }else{ 26332 int code = errno; | 26857 int code = errno; 26333 fprintf(stderr, "STAT FAILED[%d] with %d %s\n", | 26858 fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 26334 err, code, strerror(code)); | 26859 err, code, strerror(code)); 26335 #endif 26860 #endif 26336 } | 26861 } 26337 } | 26862 } 26338 } | 26863 } 26339 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK); | 26864 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK); 26340 26865 26341 end_takeconch: | 26866 end_takeconch: 26342 OSTRACE2("TRANSPROXY: CLOSE %d\n", pFile->h); | 26867 OSTRACE2("TRANSPROXY: CLOSE %d\n", pFile->h); 26343 if( rc==SQLITE_OK && pFile->openFlags ){ | 26868 if( rc==SQLITE_OK && pFile->openFlags ){ 26344 if( pFile->h>=0 ){ | 26869 if( pFile->h>=0 ){ 26345 #ifdef STRICT_CLOSE_ERROR 26870 #ifdef STRICT_CLOSE_ERROR 26346 if( close(pFile->h) ){ | 26871 if( close(pFile->h) ){ 26347 pFile->lastErrno = errno; | 26872 pFile->lastErrno = errno; 26348 return SQLITE_IOERR_CLOSE; | 26873 return SQLITE_IOERR_CLOSE; 26349 } | 26874 } 26350 #else 26875 #else 26351 close(pFile->h); /* silently leak fd if fail */ | 26876 close(pFile->h); /* silently leak fd if fail */ 26352 #endif 26877 #endif 26353 } | 26878 } 26354 pFile->h = -1; | 26879 pFile->h = -1; 26355 int fd = open(pCtx->dbPath, pFile->openFlags, | 26880 int fd = open(pCtx->dbPath, pFile->openFlags, 26356 SQLITE_DEFAULT_FILE_PERMISSIONS); | 26881 SQLITE_DEFAULT_FILE_PERMISSIONS); 26357 OSTRACE2("TRANSPROXY: OPEN %d\n", fd); | 26882 OSTRACE2("TRANSPROXY: OPEN %d\n", fd); 26358 if( fd>=0 ){ | 26883 if( fd>=0 ){ 26359 pFile->h = fd; | 26884 pFile->h = fd; 26360 }else{ | 26885 }else{ 26361 rc=SQLITE_CANTOPEN; /* SQLITE_BUSY? proxyTakeConch called | 26886 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called 26362 during locking */ | 26887 during locking */ 26363 } | 26888 } 26364 } | 26889 } 26365 if( rc==SQLITE_OK && !pCtx->lockProxy ){ | 26890 if( rc==SQLITE_OK && !pCtx->lockProxy ){ 26366 char *path = tLockPath ? tLockPath : pCtx->lockProxyPath; | 26891 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath; > 26892 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1); > 26893 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){ > 26894 /* we couldn't create the proxy lock file with the old lock file path > 26895 ** so try again via auto-naming > 26896 */ > 26897 forceNewLockPath = 1; > 26898 tryOldLockPath = 0; > 26899 continue; /* go back to the do {} while start point, try again */ > 26900 } > 26901 } > 26902 if( rc==SQLITE_OK ){ 26367 /* ACS: Need to make a copy of path sometimes */ | 26903 /* Need to make a copy of path if we extracted the value > 26904 ** from the conch file or the path was allocated on the stack > 26905 */ > 26906 if( tempLockPath ){ > 26907 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath); 26368 rc = proxyCreateUnixFile(path, &pCtx->lockProxy); | 26908 if( !pCtx->lockProxyPath ){ > 26909 rc = SQLITE_NOMEM; 26369 } | 26910 } > 26911 } > 26912 } 26370 if( rc==SQLITE_OK ){ | 26913 if( rc==SQLITE_OK ){ 26371 pCtx->conchHeld = 1; | 26914 pCtx->conchHeld = 1; 26372 | 26915 26373 if( tLockPath ){ < 26374 pCtx->lockProxyPath = sqlite3DbStrDup(0, tLockPath); < 26375 if( pCtx->lockProxy->pMethod == &afpIoMethods ){ 26916 if( pCtx->lockProxy->pMethod == &afpIoMethods ){ > 26917 afpLockingContext *afpCtx; 26376 ((afpLockingContext *)pCtx->lockProxy->lockingContext)->dbPath = | 26918 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext; 26377 pCtx->lockProxyPath; | 26919 afpCtx->dbPath = pCtx->lockProxyPath; 26378 } 26920 } 26379 } < 26380 } else { | 26921 } else { 26381 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK); | 26922 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK); 26382 } | 26923 } 26383 OSTRACE3("TAKECONCH %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed"); | 26924 OSTRACE3("TAKECONCH %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed"); 26384 return rc; | 26925 return rc; > 26926 } while (1); /* in case we need to retry the :auto: lock file - we should ne 26385 } 26927 } 26386 } 26928 } 26387 26929 26388 /* 26930 /* 26389 ** If pFile holds a lock on a conch file, then release that lock. 26931 ** If pFile holds a lock on a conch file, then release that lock. 26390 */ 26932 */ 26391 static int proxyReleaseConch(unixFile *pFile){ 26933 static int proxyReleaseConch(unixFile *pFile){ ................................................................................................................................................................................ 26394 unixFile *conchFile; /* Name of the conch file */ 26936 unixFile *conchFile; /* Name of the conch file */ 26395 26937 26396 pCtx = (proxyLockingContext *)pFile->lockingContext; 26938 pCtx = (proxyLockingContext *)pFile->lockingContext; 26397 conchFile = pCtx->conchFile; 26939 conchFile = pCtx->conchFile; 26398 OSTRACE4("RELEASECONCH %d for %s pid=%d\n", conchFile->h, 26940 OSTRACE4("RELEASECONCH %d for %s pid=%d\n", conchFile->h, 26399 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 26941 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 26400 getpid()); 26942 getpid()); 26401 pCtx->conchHeld = 0; | 26943 if( pCtx->conchHeld>0 ){ 26402 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK); | 26944 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK); > 26945 } > 26946 pCtx->conchHeld = 0; 26403 OSTRACE3("RELEASECONCH %d %s\n", conchFile->h, 26947 OSTRACE3("RELEASECONCH %d %s\n", conchFile->h, 26404 (rc==SQLITE_OK ? "ok" : "failed")); 26948 (rc==SQLITE_OK ? "ok" : "failed")); 26405 return rc; 26949 return rc; 26406 } 26950 } 26407 26951 26408 /* 26952 /* 26409 ** Given the name of a database file, compute the name of its conch file. 26953 ** Given the name of a database file, compute the name of its conch file. ................................................................................................................................................................................ 26491 */ 27035 */ 26492 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){ 27036 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){ 26493 #if defined(__APPLE__) 27037 #if defined(__APPLE__) 26494 if( pFile->pMethod == &afpIoMethods ){ 27038 if( pFile->pMethod == &afpIoMethods ){ 26495 /* afp style keeps a reference to the db path in the filePath field 27039 /* afp style keeps a reference to the db path in the filePath field 26496 ** of the struct */ 27040 ** of the struct */ 26497 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN ); 27041 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN ); 26498 strcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath); | 27042 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPAT 26499 }else | 27043 } else 26500 #endif 27044 #endif 26501 if( pFile->pMethod == &dotlockIoMethods ){ 27045 if( pFile->pMethod == &dotlockIoMethods ){ 26502 /* dot lock style uses the locking context to store the dot lock 27046 /* dot lock style uses the locking context to store the dot lock 26503 ** file path */ 27047 ** file path */ 26504 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX); 27048 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX); 26505 memcpy(dbPath, (char *)pFile->lockingContext, len + 1); 27049 memcpy(dbPath, (char *)pFile->lockingContext, len + 1); 26506 }else{ 27050 }else{ 26507 /* all other styles use the locking context to store the db file path */ 27051 /* all other styles use the locking context to store the db file path */ 26508 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN ); 27052 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN ); 26509 strcpy(dbPath, (char *)pFile->lockingContext); | 27053 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN); 26510 } 27054 } 26511 return SQLITE_OK; 27055 return SQLITE_OK; 26512 } 27056 } 26513 27057 26514 /* 27058 /* 26515 ** Takes an already filled in unix file and alters it so all file locking 27059 ** Takes an already filled in unix file and alters it so all file locking 26516 ** will be performed on the local proxy lock file. The following fields 27060 ** will be performed on the local proxy lock file. The following fields ................................................................................................................................................................................ 26542 if( pCtx==0 ){ 27086 if( pCtx==0 ){ 26543 return SQLITE_NOMEM; 27087 return SQLITE_NOMEM; 26544 } 27088 } 26545 memset(pCtx, 0, sizeof(*pCtx)); 27089 memset(pCtx, 0, sizeof(*pCtx)); 26546 27090 26547 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath); 27091 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath); 26548 if( rc==SQLITE_OK ){ 27092 if( rc==SQLITE_OK ){ 26549 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile); | 27093 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0); > 27094 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){ > 27095 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and > 27096 ** (c) the file system is read-only, then enable no-locking access. > 27097 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts > 27098 ** that openFlags will have only one of O_RDONLY or O_RDWR. > 27099 */ > 27100 struct statfs fsInfo; > 27101 struct stat conchInfo; > 27102 int goLockless = 0; > 27103 > 27104 if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) { > 27105 int err = errno; > 27106 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){ > 27107 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY; > 27108 } > 27109 } > 27110 if( goLockless ){ > 27111 pCtx->conchHeld = -1; /* read only FS/ lockless */ > 27112 rc = SQLITE_OK; > 27113 } > 27114 } 26550 } 27115 } 26551 if( rc==SQLITE_OK && lockPath ){ 27116 if( rc==SQLITE_OK && lockPath ){ 26552 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath); 27117 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath); 26553 } 27118 } 26554 27119 > 27120 if( rc==SQLITE_OK ){ > 27121 pCtx->dbPath = sqlite3DbStrDup(0, dbPath); > 27122 if( pCtx->dbPath==NULL ){ > 27123 rc = SQLITE_NOMEM; > 27124 } > 27125 } 26555 if( rc==SQLITE_OK ){ 27126 if( rc==SQLITE_OK ){ 26556 /* all memory is allocated, proxys are created and assigned, 27127 /* all memory is allocated, proxys are created and assigned, 26557 ** switch the locking context and pMethod then return. 27128 ** switch the locking context and pMethod then return. 26558 */ 27129 */ 26559 pCtx->dbPath = sqlite3DbStrDup(0, dbPath); < 26560 pCtx->oldLockingContext = pFile->lockingContext; 27130 pCtx->oldLockingContext = pFile->lockingContext; 26561 pFile->lockingContext = pCtx; 27131 pFile->lockingContext = pCtx; 26562 pCtx->pOldMethod = pFile->pMethod; 27132 pCtx->pOldMethod = pFile->pMethod; 26563 pFile->pMethod = &proxyIoMethods; 27133 pFile->pMethod = &proxyIoMethods; 26564 }else{ 27134 }else{ 26565 if( pCtx->conchFile ){ 27135 if( pCtx->conchFile ){ 26566 rc = pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile); | 27136 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile); 26567 if( rc ) return rc; < 26568 sqlite3_free(pCtx->conchFile); 27137 sqlite3_free(pCtx->conchFile); 26569 } 27138 } > 27139 sqlite3_free(pCtx->lockProxyPath); 26570 sqlite3_free(pCtx->conchFilePath); 27140 sqlite3_free(pCtx->conchFilePath); 26571 sqlite3_free(pCtx); 27141 sqlite3_free(pCtx); 26572 } 27142 } 26573 OSTRACE3("TRANSPROXY %d %s\n", pFile->h, 27143 OSTRACE3("TRANSPROXY %d %s\n", pFile->h, 26574 (rc==SQLITE_OK ? "ok" : "failed")); 27144 (rc==SQLITE_OK ? "ok" : "failed")); 26575 return rc; 27145 return rc; 26576 } 27146 } ................................................................................................................................................................................ 26651 ** is set to SQLITE_OK unless an I/O error occurs during lock checking. 27221 ** is set to SQLITE_OK unless an I/O error occurs during lock checking. 26652 */ 27222 */ 26653 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) { 27223 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) { 26654 unixFile *pFile = (unixFile*)id; 27224 unixFile *pFile = (unixFile*)id; 26655 int rc = proxyTakeConch(pFile); 27225 int rc = proxyTakeConch(pFile); 26656 if( rc==SQLITE_OK ){ 27226 if( rc==SQLITE_OK ){ 26657 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 27227 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; > 27228 if( pCtx->conchHeld>0 ){ 26658 unixFile *proxy = pCtx->lockProxy; | 27229 unixFile *proxy = pCtx->lockProxy; 26659 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut); | 27230 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut); > 27231 }else{ /* conchHeld < 0 is lockless */ > 27232 pResOut=0; > 27233 } 26660 } 27234 } 26661 return rc; 27235 return rc; 26662 } 27236 } 26663 27237 26664 /* 27238 /* 26665 ** Lock the file with the lock specified by parameter locktype - one 27239 ** Lock the file with the lock specified by parameter locktype - one 26666 ** of the following: 27240 ** of the following: ................................................................................................................................................................................ 26686 ** routine to lower a locking level. 27260 ** routine to lower a locking level. 26687 */ 27261 */ 26688 static int proxyLock(sqlite3_file *id, int locktype) { 27262 static int proxyLock(sqlite3_file *id, int locktype) { 26689 unixFile *pFile = (unixFile*)id; 27263 unixFile *pFile = (unixFile*)id; 26690 int rc = proxyTakeConch(pFile); 27264 int rc = proxyTakeConch(pFile); 26691 if( rc==SQLITE_OK ){ 27265 if( rc==SQLITE_OK ){ 26692 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 27266 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; > 27267 if( pCtx->conchHeld>0 ){ 26693 unixFile *proxy = pCtx->lockProxy; | 27268 unixFile *proxy = pCtx->lockProxy; 26694 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype); | 27269 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype); 26695 pFile->locktype = proxy->locktype; | 27270 pFile->locktype = proxy->locktype; > 27271 }else{ > 27272 /* conchHeld < 0 is lockless */ > 27273 } 26696 } 27274 } 26697 return rc; 27275 return rc; 26698 } 27276 } 26699 27277 26700 27278 26701 /* 27279 /* 26702 ** Lower the locking level on file descriptor pFile to locktype. locktype 27280 ** Lower the locking level on file descriptor pFile to locktype. locktype ................................................................................................................................................................................ 26706 ** the requested locking level, this routine is a no-op. 27284 ** the requested locking level, this routine is a no-op. 26707 */ 27285 */ 26708 static int proxyUnlock(sqlite3_file *id, int locktype) { 27286 static int proxyUnlock(sqlite3_file *id, int locktype) { 26709 unixFile *pFile = (unixFile*)id; 27287 unixFile *pFile = (unixFile*)id; 26710 int rc = proxyTakeConch(pFile); 27288 int rc = proxyTakeConch(pFile); 26711 if( rc==SQLITE_OK ){ 27289 if( rc==SQLITE_OK ){ 26712 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 27290 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; > 27291 if( pCtx->conchHeld>0 ){ 26713 unixFile *proxy = pCtx->lockProxy; | 27292 unixFile *proxy = pCtx->lockProxy; 26714 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype); | 27293 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype); 26715 pFile->locktype = proxy->locktype; | 27294 pFile->locktype = proxy->locktype; > 27295 }else{ > 27296 /* conchHeld < 0 is lockless */ > 27297 } 26716 } 27298 } 26717 return rc; 27299 return rc; 26718 } 27300 } 26719 27301 26720 /* 27302 /* 26721 ** Close a file that uses proxy locks. 27303 ** Close a file that uses proxy locks. 26722 */ 27304 */ ................................................................................................................................................................................ 26835 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__)) 27417 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__)) 26836 UNIXVFS("unix", autolockIoFinder ), 27418 UNIXVFS("unix", autolockIoFinder ), 26837 #else 27419 #else 26838 UNIXVFS("unix", posixIoFinder ), 27420 UNIXVFS("unix", posixIoFinder ), 26839 #endif 27421 #endif 26840 UNIXVFS("unix-none", nolockIoFinder ), 27422 UNIXVFS("unix-none", nolockIoFinder ), 26841 UNIXVFS("unix-dotfile", dotlockIoFinder ), 27423 UNIXVFS("unix-dotfile", dotlockIoFinder ), 26842 UNIXVFS("unix-wfl", posixWflIoFinder ), < 26843 #if OS_VXWORKS 27424 #if OS_VXWORKS 26844 UNIXVFS("unix-namedsem", semIoFinder ), 27425 UNIXVFS("unix-namedsem", semIoFinder ), 26845 #endif 27426 #endif 26846 #if SQLITE_ENABLE_LOCKING_STYLE 27427 #if SQLITE_ENABLE_LOCKING_STYLE 26847 UNIXVFS("unix-posix", posixIoFinder ), 27428 UNIXVFS("unix-posix", posixIoFinder ), 26848 #if !OS_VXWORKS 27429 #if !OS_VXWORKS 26849 UNIXVFS("unix-flock", flockIoFinder ), 27430 UNIXVFS("unix-flock", flockIoFinder ), 26850 #endif 27431 #endif 26851 #endif 27432 #endif 26852 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) 27433 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) 26853 UNIXVFS("unix-afp", afpIoFinder ), 27434 UNIXVFS("unix-afp", afpIoFinder ), > 27435 UNIXVFS("unix-nfs", nfsIoFinder ), 26854 UNIXVFS("unix-proxy", proxyIoFinder ), 27436 UNIXVFS("unix-proxy", proxyIoFinder ), 26855 #endif 27437 #endif 26856 }; 27438 }; 26857 unsigned int i; /* Loop counter */ 27439 unsigned int i; /* Loop counter */ 26858 27440 26859 /* Register all VFSes defined in the aVfs[] array */ 27441 /* Register all VFSes defined in the aVfs[] array */ 26860 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){ 27442 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){ ................................................................................................................................................................................ 28510 } 29092 } 28511 if( h==INVALID_HANDLE_VALUE ){ 29093 if( h==INVALID_HANDLE_VALUE ){ 28512 free(zConverted); 29094 free(zConverted); 28513 if( flags & SQLITE_OPEN_READWRITE ){ 29095 if( flags & SQLITE_OPEN_READWRITE ){ 28514 return winOpen(pVfs, zName, id, 29096 return winOpen(pVfs, zName, id, 28515 ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags); 29097 ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags); 28516 }else{ 29098 }else{ 28517 return SQLITE_CANTOPEN; | 29099 return SQLITE_CANTOPEN_BKPT; 28518 } 29100 } 28519 } 29101 } 28520 if( pOutFlags ){ 29102 if( pOutFlags ){ 28521 if( flags & SQLITE_OPEN_READWRITE ){ 29103 if( flags & SQLITE_OPEN_READWRITE ){ 28522 *pOutFlags = SQLITE_OPEN_READWRITE; 29104 *pOutFlags = SQLITE_OPEN_READWRITE; 28523 }else{ 29105 }else{ 28524 *pOutFlags = SQLITE_OPEN_READONLY; 29106 *pOutFlags = SQLITE_OPEN_READONLY; ................................................................................................................................................................................ 28532 #if SQLITE_OS_WINCE 29114 #if SQLITE_OS_WINCE 28533 if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) == 29115 if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) == 28534 (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB) 29116 (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB) 28535 && !winceCreateLock(zName, pFile) 29117 && !winceCreateLock(zName, pFile) 28536 ){ 29118 ){ 28537 CloseHandle(h); 29119 CloseHandle(h); 28538 free(zConverted); 29120 free(zConverted); 28539 return SQLITE_CANTOPEN; | 29121 return SQLITE_CANTOPEN_BKPT; 28540 } 29122 } 28541 if( isTemp ){ 29123 if( isTemp ){ 28542 pFile->zDeleteOnClose = zConverted; 29124 pFile->zDeleteOnClose = zConverted; 28543 }else 29125 }else 28544 #endif 29126 #endif 28545 { 29127 { 28546 free(zConverted); 29128 free(zConverted); ................................................................................................................................................................................ 29619 ** are no outstanding page references when this function is called. 30201 ** are no outstanding page references when this function is called. 29620 */ 30202 */ 29621 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){ 30203 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){ 29622 assert( pCache->nRef==0 && pCache->pDirty==0 ); 30204 assert( pCache->nRef==0 && pCache->pDirty==0 ); 29623 if( pCache->pCache ){ 30205 if( pCache->pCache ){ 29624 sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache); 30206 sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache); 29625 pCache->pCache = 0; 30207 pCache->pCache = 0; > 30208 pCache->pPage1 = 0; 29626 } 30209 } 29627 pCache->szPage = szPage; 30210 pCache->szPage = szPage; 29628 } 30211 } 29629 30212 29630 /* 30213 /* 29631 ** Try to obtain a page from the cache. 30214 ** Try to obtain a page from the cache. 29632 */ 30215 */ ................................................................................................................................................................................ 29672 ** unreferenced dirty page. 30255 ** unreferenced dirty page. 29673 */ 30256 */ 29674 expensive_assert( pcacheCheckSynced(pCache) ); 30257 expensive_assert( pcacheCheckSynced(pCache) ); 29675 for(pPg=pCache->pSynced; 30258 for(pPg=pCache->pSynced; 29676 pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 30259 pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 29677 pPg=pPg->pDirtyPrev 30260 pPg=pPg->pDirtyPrev 29678 ); 30261 ); > 30262 pCache->pSynced = pPg; 29679 if( !pPg ){ 30263 if( !pPg ){ 29680 for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev); 30264 for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev); 29681 } 30265 } 29682 if( pPg ){ 30266 if( pPg ){ 29683 int rc; 30267 int rc; 29684 rc = pCache->xStress(pCache->pStress, pPg); 30268 rc = pCache->xStress(pCache->pStress, pPg); 29685 if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){ 30269 if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){ ................................................................................................................................................................................ 34086 34670 34087 /* If there are dirty pages in the page cache with page numbers greater 34671 /* If there are dirty pages in the page cache with page numbers greater 34088 ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to 34672 ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to 34089 ** make the file smaller (presumably by auto-vacuum code). Do not write 34673 ** make the file smaller (presumably by auto-vacuum code). Do not write 34090 ** any such pages to the file. 34674 ** any such pages to the file. 34091 ** 34675 ** 34092 ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag 34676 ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag 34093 ** set (set by sqlite3PagerDontWrite()). Note that if compiled with | 34677 ** set (set by sqlite3PagerDontWrite()). 34094 ** SQLITE_SECURE_DELETE the PGHDR_DONT_WRITE bit is never set and so < 34095 ** the second test is always true. < 34096 */ 34678 */ 34097 if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){ 34679 if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){ 34098 i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */ 34680 i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */ 34099 char *pData; /* Data to write */ 34681 char *pData; /* Data to write */ 34100 34682 34101 /* Encode the database */ 34683 /* Encode the database */ 34102 CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData); 34684 CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData); ................................................................................................................................................................................ 34375 if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){ 34957 if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){ 34376 /* This branch is taken when the journal path required by 34958 /* This branch is taken when the journal path required by 34377 ** the database being opened will be more than pVfs->mxPathname 34959 ** the database being opened will be more than pVfs->mxPathname 34378 ** bytes in length. This means the database cannot be opened, 34960 ** bytes in length. This means the database cannot be opened, 34379 ** as it will not be possible to open the journal file or even 34961 ** as it will not be possible to open the journal file or even 34380 ** check for a hot-journal before reading. 34962 ** check for a hot-journal before reading. 34381 */ 34963 */ 34382 rc = SQLITE_CANTOPEN; | 34964 rc = SQLITE_CANTOPEN_BKPT; 34383 } 34965 } 34384 if( rc!=SQLITE_OK ){ 34966 if( rc!=SQLITE_OK ){ 34385 sqlite3_free(zPathname); 34967 sqlite3_free(zPathname); 34386 return rc; 34968 return rc; 34387 } 34969 } 34388 } 34970 } 34389 34971 ................................................................................................................................................................................ 34552 }else if( memDb ){ 35134 }else if( memDb ){ 34553 pPager->journalMode = PAGER_JOURNALMODE_MEMORY; 35135 pPager->journalMode = PAGER_JOURNALMODE_MEMORY; 34554 } 35136 } 34555 /* pPager->xBusyHandler = 0; */ 35137 /* pPager->xBusyHandler = 0; */ 34556 /* pPager->pBusyHandlerArg = 0; */ 35138 /* pPager->pBusyHandlerArg = 0; */ 34557 pPager->xReiniter = xReinit; 35139 pPager->xReiniter = xReinit; 34558 /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */ 35140 /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */ > 35141 34559 *ppPager = pPager; 35142 *ppPager = pPager; 34560 return SQLITE_OK; 35143 return SQLITE_OK; 34561 } 35144 } 34562 35145 34563 35146 34564 35147 34565 /* 35148 /* ................................................................................................................................................................................ 34701 } 35284 } 34702 iOffset = (pgno-1)*(i64)pPager->pageSize; 35285 iOffset = (pgno-1)*(i64)pPager->pageSize; 34703 rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset); 35286 rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset); 34704 if( rc==SQLITE_IOERR_SHORT_READ ){ 35287 if( rc==SQLITE_IOERR_SHORT_READ ){ 34705 rc = SQLITE_OK; 35288 rc = SQLITE_OK; 34706 } 35289 } 34707 if( pgno==1 ){ 35290 if( pgno==1 ){ > 35291 if( rc ){ > 35292 /* If the read is unsuccessful, set the dbFileVers[] to something > 35293 ** that will never be a valid file version. dbFileVers[] is a copy > 35294 ** of bytes 24..39 of the database. Bytes 28..31 should always be > 35295 ** zero. Bytes 32..35 and 35..39 should be page numbers which are > 35296 ** never 0xffffffff. So filling pPager->dbFileVers[] with all 0xff > 35297 ** bytes should suffice. > 35298 ** > 35299 ** For an encrypted database, the situation is more complex: bytes > 35300 ** 24..39 of the database are white noise. But the probability of > 35301 ** white noising equaling 16 bytes of 0xff is vanishingly small so > 35302 ** we should still be ok. > 35303 */ > 35304 memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers)); > 35305 }else{ 34708 u8 *dbFileVers = &((u8*)pPg->pData)[24]; | 35306 u8 *dbFileVers = &((u8*)pPg->pData)[24]; 34709 memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers)); | 35307 memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers)); > 35308 } 34710 } 35309 } 34711 CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM); 35310 CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM); 34712 35311 34713 PAGER_INCR(sqlite3_pager_readdb_count); 35312 PAGER_INCR(sqlite3_pager_readdb_count); 34714 PAGER_INCR(pPager->nRead); 35313 PAGER_INCR(pPager->nRead); 34715 IOTRACE(("PGIN %p %d\n", pPager, pgno)); 35314 IOTRACE(("PGIN %p %d\n", pPager, pgno)); 34716 PAGERTRACE(("FETCH %d page %d hash(%08x)\n", 35315 PAGERTRACE(("FETCH %d page %d hash(%08x)\n", ................................................................................................................................................................................ 34834 if( res ){ 35433 if( res ){ 34835 int fout = 0; 35434 int fout = 0; 34836 int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL; 35435 int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL; 34837 assert( !pPager->tempFile ); 35436 assert( !pPager->tempFile ); 34838 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout); 35437 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout); 34839 assert( rc!=SQLITE_OK || isOpen(pPager->jfd) ); 35438 assert( rc!=SQLITE_OK || isOpen(pPager->jfd) ); 34840 if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){ 35439 if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){ 34841 rc = SQLITE_CANTOPEN; | 35440 rc = SQLITE_CANTOPEN_BKPT; 34842 sqlite3OsClose(pPager->jfd); 35441 sqlite3OsClose(pPager->jfd); 34843 } 35442 } 34844 }else{ 35443 }else{ 34845 /* If the journal does not exist, it usually means that some 35444 /* If the journal does not exist, it usually means that some 34846 ** other connection managed to get in and roll it back before 35445 ** other connection managed to get in and roll it back before 34847 ** this connection obtained the exclusive lock above. Or, it 35446 ** this connection obtained the exclusive lock above. Or, it 34848 ** may mean that the pager was in the error-state when this 35447 ** may mean that the pager was in the error-state when this ................................................................................................................................................................................ 35053 } 35652 } 35054 35653 35055 rc = sqlite3PagerPagecount(pPager, &nMax); 35654 rc = sqlite3PagerPagecount(pPager, &nMax); 35056 if( rc!=SQLITE_OK ){ 35655 if( rc!=SQLITE_OK ){ 35057 goto pager_acquire_err; 35656 goto pager_acquire_err; 35058 } 35657 } 35059 35658 35060 if( MEMDB || nMax<(int)pgno || noContent ){ | 35659 if( MEMDB || nMax<(int)pgno || noContent || !isOpen(pPager->fd) ){ 35061 if( pgno>pPager->mxPgno ){ 35660 if( pgno>pPager->mxPgno ){ 35062 rc = SQLITE_FULL; 35661 rc = SQLITE_FULL; 35063 goto pager_acquire_err; 35662 goto pager_acquire_err; 35064 } 35663 } 35065 if( noContent ){ 35664 if( noContent ){ 35066 /* Failure to set the bits in the InJournal bit-vectors is benign. 35665 /* Failure to set the bits in the InJournal bit-vectors is benign. 35067 ** It merely means that we might do some extra work to journal a 35666 ** It merely means that we might do some extra work to journal a ................................................................................................................................................................................ 35596 */ 36195 */ 35597 #ifndef NDEBUG 36196 #ifndef NDEBUG 35598 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){ 36197 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){ 35599 return pPg->flags&PGHDR_DIRTY; 36198 return pPg->flags&PGHDR_DIRTY; 35600 } 36199 } 35601 #endif 36200 #endif 35602 36201 35603 #ifndef SQLITE_SECURE_DELETE < 35604 /* 36202 /* 35605 ** A call to this routine tells the pager that it is not necessary to 36203 ** A call to this routine tells the pager that it is not necessary to 35606 ** write the information on page pPg back to the disk, even though 36204 ** write the information on page pPg back to the disk, even though 35607 ** that page might be marked as dirty. This happens, for example, when 36205 ** that page might be marked as dirty. This happens, for example, when 35608 ** the page has been added as a leaf of the freelist and so its 36206 ** the page has been added as a leaf of the freelist and so its 35609 ** content no longer matters. 36207 ** content no longer matters. 35610 ** 36208 ** ................................................................................................................................................................................ 35622 IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno)) 36220 IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno)) 35623 pPg->flags |= PGHDR_DONT_WRITE; 36221 pPg->flags |= PGHDR_DONT_WRITE; 35624 #ifdef SQLITE_CHECK_PAGES 36222 #ifdef SQLITE_CHECK_PAGES 35625 pPg->pageHash = pager_pagehash(pPg); 36223 pPg->pageHash = pager_pagehash(pPg); 35626 #endif 36224 #endif 35627 } 36225 } 35628 } 36226 } 35629 #endif /* !defined(SQLITE_SECURE_DELETE) */ < 35630 36227 35631 /* 36228 /* 35632 ** This routine is called to increment the value of the database file 36229 ** This routine is called to increment the value of the database file 35633 ** change-counter, stored as a 4-byte big-endian integer starting at 36230 ** change-counter, stored as a 4-byte big-endian integer starting at 35634 ** byte offset 24 of the pager file. 36231 ** byte offset 24 of the pager file. 35635 ** 36232 ** 35636 ** If the isDirectMode flag is zero, then this is done by calling 36233 ** If the isDirectMode flag is zero, then this is done by calling ................................................................................................................................................................................ 36192 int ii; /* Iterator variable */ 36789 int ii; /* Iterator variable */ 36193 int nNew; /* Number of remaining savepoints after this op. */ 36790 int nNew; /* Number of remaining savepoints after this op. */ 36194 36791 36195 /* Figure out how many savepoints will still be active after this 36792 /* Figure out how many savepoints will still be active after this 36196 ** operation. Store this value in nNew. Then free resources associated 36793 ** operation. Store this value in nNew. Then free resources associated 36197 ** with any savepoints that are destroyed by this operation. 36794 ** with any savepoints that are destroyed by this operation. 36198 */ 36795 */ 36199 nNew = iSavepoint + (op==SAVEPOINT_ROLLBACK); | 36796 nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1); 36200 for(ii=nNew; ii<pPager->nSavepoint; ii++){ 36797 for(ii=nNew; ii<pPager->nSavepoint; ii++){ 36201 sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint); 36798 sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint); 36202 } 36799 } 36203 pPager->nSavepoint = nNew; 36800 pPager->nSavepoint = nNew; 36204 36801 > 36802 /* If this is a release of the outermost savepoint, truncate > 36803 ** the sub-journal to zero bytes in size. */ > 36804 if( op==SAVEPOINT_RELEASE ){ > 36805 if( nNew==0 && isOpen(pPager->sjfd) ){ > 36806 /* Only truncate if it is an in-memory sub-journal. */ > 36807 if( sqlite3IsMemJournal(pPager->sjfd) ){ > 36808 rc = sqlite3OsTruncate(pPager->sjfd, 0); > 36809 assert( rc==SQLITE_OK ); > 36810 } > 36811 pPager->nSubRec = 0; > 36812 } > 36813 } 36205 /* If this is a rollback operation, playback the specified savepoint. | 36814 /* Else this is a rollback operation, playback the specified savepoint. 36206 ** If this is a temp-file, it is possible that the journal file has 36815 ** If this is a temp-file, it is possible that the journal file has 36207 ** not yet been opened. In this case there have been no changes to 36816 ** not yet been opened. In this case there have been no changes to 36208 ** the database file, so the playback operation can be skipped. 36817 ** the database file, so the playback operation can be skipped. 36209 */ 36818 */ 36210 if( op==SAVEPOINT_ROLLBACK && isOpen(pPager->jfd) ){ | 36819 else if( isOpen(pPager->jfd) ){ 36211 PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1]; 36820 PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1]; 36212 rc = pagerPlaybackSavepoint(pPager, pSavepoint); 36821 rc = pagerPlaybackSavepoint(pPager, pSavepoint); 36213 assert(rc!=SQLITE_DONE); 36822 assert(rc!=SQLITE_DONE); 36214 } 36823 } 36215 36824 36216 /* If this is a release of the outermost savepoint, truncate < 36217 ** the sub-journal to zero bytes in size. */ < 36218 if( nNew==0 && op==SAVEPOINT_RELEASE && isOpen(pPager->sjfd) ){ < 36219 assert( rc==SQLITE_OK ); < 36220 rc = sqlite3OsTruncate(pPager->sjfd, 0); < 36221 pPager->nSubRec = 0; < 36222 } < 36223 } 36825 } 36224 return rc; 36826 return rc; 36225 } 36827 } 36226 36828 36227 /* 36829 /* 36228 ** Return the full pathname of the database file. 36830 ** Return the full pathname of the database file. 36229 */ 36831 */ ................................................................................................................................................................................ 36975 struct BtShared { 37577 struct BtShared { 36976 Pager *pPager; /* The page cache */ 37578 Pager *pPager; /* The page cache */ 36977 sqlite3 *db; /* Database connection currently using this Btree */ 37579 sqlite3 *db; /* Database connection currently using this Btree */ 36978 BtCursor *pCursor; /* A list of all open cursors */ 37580 BtCursor *pCursor; /* A list of all open cursors */ 36979 MemPage *pPage1; /* First page of the database */ 37581 MemPage *pPage1; /* First page of the database */ 36980 u8 readOnly; /* True if the underlying file is readonly */ 37582 u8 readOnly; /* True if the underlying file is readonly */ 36981 u8 pageSizeFixed; /* True if the page size can no longer be changed */ 37583 u8 pageSizeFixed; /* True if the page size can no longer be changed */ > 37584 u8 secureDelete; /* True if secure_delete is enabled */ 36982 #ifndef SQLITE_OMIT_AUTOVACUUM 37585 #ifndef SQLITE_OMIT_AUTOVACUUM 36983 u8 autoVacuum; /* True if auto-vacuum is enabled */ 37586 u8 autoVacuum; /* True if auto-vacuum is enabled */ 36984 u8 incrVacuum; /* True if incr-vacuum is enabled */ 37587 u8 incrVacuum; /* True if incr-vacuum is enabled */ 36985 #endif 37588 #endif 36986 u16 pageSize; /* Total number of bytes on a page */ 37589 u16 pageSize; /* Total number of bytes on a page */ 36987 u16 usableSize; /* Number of usable bytes on each page */ 37590 u16 usableSize; /* Number of usable bytes on each page */ 36988 u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */ 37591 u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */ ................................................................................................................................................................................ 38798 assert( pPage->pBt!=0 ); 39401 assert( pPage->pBt!=0 ); 38799 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 39402 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 38800 assert( start>=pPage->hdrOffset+6+pPage->childPtrSize ); 39403 assert( start>=pPage->hdrOffset+6+pPage->childPtrSize ); 38801 assert( (start + size)<=pPage->pBt->usableSize ); 39404 assert( (start + size)<=pPage->pBt->usableSize ); 38802 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 39405 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); 38803 assert( size>=0 ); /* Minimum cell size is 4 */ 39406 assert( size>=0 ); /* Minimum cell size is 4 */ 38804 39407 38805 #ifdef SQLITE_SECURE_DELETE | 39408 if( pPage->pBt->secureDelete ){ 38806 /* Overwrite deleted information with zeros when the SECURE_DELETE | 39409 /* Overwrite deleted information with zeros when the secure_delete 38807 ** option is enabled at compile-time */ | 39410 ** option is enabled */ 38808 memset(&data[start], 0, size); | 39411 memset(&data[start], 0, size); 38809 #endif < > 39412 } 38810 39413 38811 /* Add the space back into the linked list of freeblocks. Note that 39414 /* Add the space back into the linked list of freeblocks. Note that 38812 ** even though the freeblock list was checked by btreeInitPage(), 39415 ** even though the freeblock list was checked by btreeInitPage(), 38813 ** btreeInitPage() did not detect overlapping cells or 39416 ** btreeInitPage() did not detect overlapping cells or 38814 ** freeblocks that overlapped cells. Nor does it detect when the 39417 ** freeblocks that overlapped cells. Nor does it detect when the 38815 ** cell content area exceeds the value in the page header. If these 39418 ** cell content area exceeds the value in the page header. If these 38816 ** situations arise, then subsequent insert operations might corrupt 39419 ** situations arise, then subsequent insert operations might corrupt ................................................................................................................................................................................ 39034 u16 first; 39637 u16 first; 39035 39638 39036 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno ); 39639 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno ); 39037 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); 39640 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); 39038 assert( sqlite3PagerGetData(pPage->pDbPage) == data ); 39641 assert( sqlite3PagerGetData(pPage->pDbPage) == data ); 39039 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 39642 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); 39040 assert( sqlite3_mutex_held(pBt->mutex) ); 39643 assert( sqlite3_mutex_held(pBt->mutex) ); 39041 #ifdef SQLITE_SECURE_DELETE | 39644 if( pBt->secureDelete ){ 39042 memset(&data[hdr], 0, pBt->usableSize - hdr); | 39645 memset(&data[hdr], 0, pBt->usableSize - hdr); 39043 #endif < > 39646 } 39044 data[hdr] = (char)flags; 39647 data[hdr] = (char)flags; 39045 first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0); 39648 first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0); 39046 memset(&data[hdr+1], 0, 4); 39649 memset(&data[hdr+1], 0, 4); 39047 data[hdr+7] = 0; 39650 data[hdr+7] = 0; 39048 put2byte(&data[hdr+5], pBt->usableSize); 39651 put2byte(&data[hdr+5], pBt->usableSize); 39049 pPage->nFree = pBt->usableSize - first; 39652 pPage->nFree = pBt->usableSize - first; 39050 decodeFlags(pPage, flags); 39653 decodeFlags(pPage, flags); ................................................................................................................................................................................ 39356 pBt->db = db; 39959 pBt->db = db; 39357 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt); 39960 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt); 39358 p->pBt = pBt; 39961 p->pBt = pBt; 39359 39962 39360 pBt->pCursor = 0; 39963 pBt->pCursor = 0; 39361 pBt->pPage1 = 0; 39964 pBt->pPage1 = 0; 39362 pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager); 39965 pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager); > 39966 #ifdef SQLITE_SECURE_DELETE > 39967 pBt->secureDelete = 1; > 39968 #endif 39363 pBt->pageSize = get2byte(&zDbHeader[16]); 39969 pBt->pageSize = get2byte(&zDbHeader[16]); 39364 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE 39970 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE 39365 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){ 39971 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){ 39366 pBt->pageSize = 0; 39972 pBt->pageSize = 0; 39367 #ifndef SQLITE_OMIT_AUTOVACUUM 39973 #ifndef SQLITE_OMIT_AUTOVACUUM 39368 /* If the magic name ":memory:" will create an in-memory database, then 39974 /* If the magic name ":memory:" will create an in-memory database, then 39369 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if 39975 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if ................................................................................................................................................................................ 39712 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){ 40318 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){ 39713 int n; 40319 int n; 39714 sqlite3BtreeEnter(p); 40320 sqlite3BtreeEnter(p); 39715 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage); 40321 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage); 39716 sqlite3BtreeLeave(p); 40322 sqlite3BtreeLeave(p); 39717 return n; 40323 return n; 39718 } 40324 } > 40325 > 40326 /* > 40327 ** Set the secureDelete flag if newFlag is 0 or 1. If newFlag is -1, > 40328 ** then make no changes. Always return the value of the secureDelete > 40329 ** setting after the change. > 40330 */ > 40331 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){ > 40332 int b; > 40333 if( p==0 ) return 0; > 40334 sqlite3BtreeEnter(p); > 40335 if( newFlag>=0 ){ > 40336 p->pBt->secureDelete = (newFlag!=0) ? 1 : 0; > 40337 } > 40338 b = p->pBt->secureDelete; > 40339 sqlite3BtreeLeave(p); > 40340 return b; > 40341 } 39719 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */ 40342 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */ 39720 40343 39721 /* 40344 /* 39722 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum' 40345 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum' 39723 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it 40346 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it 39724 ** is disabled. The default value for the auto-vacuum property is 40347 ** is disabled. The default value for the auto-vacuum property is 39725 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro. 40348 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro. ................................................................................................................................................................................ 42455 43078 42456 /* Increment the free page count on pPage1 */ 43079 /* Increment the free page count on pPage1 */ 42457 rc = sqlite3PagerWrite(pPage1->pDbPage); 43080 rc = sqlite3PagerWrite(pPage1->pDbPage); 42458 if( rc ) goto freepage_out; 43081 if( rc ) goto freepage_out; 42459 nFree = get4byte(&pPage1->aData[36]); 43082 nFree = get4byte(&pPage1->aData[36]); 42460 put4byte(&pPage1->aData[36], nFree+1); 43083 put4byte(&pPage1->aData[36], nFree+1); 42461 43084 42462 #ifdef SQLITE_SECURE_DELETE | 43085 if( pBt->secureDelete ){ 42463 /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then | 43086 /* If the secure_delete option is enabled, then 42464 ** always fully overwrite deleted information with zeros. | 43087 ** always fully overwrite deleted information with zeros. 42465 */ | 43088 */ 42466 if( (!pPage && (rc = btreeGetPage(pBt, iPage, &pPage, 0))) | 43089 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) ) 42467 || (rc = sqlite3PagerWrite(pPage->pDbPage)) | 43090 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0) 42468 ){ | 43091 ){ 42469 goto freepage_out; | 43092 goto freepage_out; 42470 } | 43093 } 42471 memset(pPage->aData, 0, pPage->pBt->pageSize); | 43094 memset(pPage->aData, 0, pPage->pBt->pageSize); 42472 #endif < > 43095 } 42473 43096 42474 /* If the database supports auto-vacuum, write an entry in the pointer-map 43097 /* If the database supports auto-vacuum, write an entry in the pointer-map 42475 ** to indicate that the page is free. 43098 ** to indicate that the page is free. 42476 */ 43099 */ 42477 if( ISAUTOVACUUM ){ 43100 if( ISAUTOVACUUM ){ 42478 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc); 43101 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc); 42479 if( rc ) goto freepage_out; 43102 if( rc ) goto freepage_out; ................................................................................................................................................................................ 42516 ** to 3.6.0 or later) we should consider fixing the conditional above 43139 ** to 3.6.0 or later) we should consider fixing the conditional above 42517 ** to read "usableSize/4-2" instead of "usableSize/4-8". 43140 ** to read "usableSize/4-2" instead of "usableSize/4-8". 42518 */ 43141 */ 42519 rc = sqlite3PagerWrite(pTrunk->pDbPage); 43142 rc = sqlite3PagerWrite(pTrunk->pDbPage); 42520 if( rc==SQLITE_OK ){ 43143 if( rc==SQLITE_OK ){ 42521 put4byte(&pTrunk->aData[4], nLeaf+1); 43144 put4byte(&pTrunk->aData[4], nLeaf+1); 42522 put4byte(&pTrunk->aData[8+nLeaf*4], iPage); 43145 put4byte(&pTrunk->aData[8+nLeaf*4], iPage); 42523 #ifndef SQLITE_SECURE_DELETE < 42524 if( pPage ){ | 43146 if( pPage && !pBt->secureDelete ){ 42525 sqlite3PagerDontWrite(pPage->pDbPage); 43147 sqlite3PagerDontWrite(pPage->pDbPage); 42526 } 43148 } 42527 #endif < 42528 rc = btreeSetHasContent(pBt, iPage); 43149 rc = btreeSetHasContent(pBt, iPage); 42529 } 43150 } 42530 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno)); 43151 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno)); 42531 goto freepage_out; 43152 goto freepage_out; 42532 } 43153 } 42533 } 43154 } 42534 43155 ................................................................................................................................................................................ 42594 ** file the database must be corrupt. */ 43215 ** file the database must be corrupt. */ 42595 return SQLITE_CORRUPT_BKPT; 43216 return SQLITE_CORRUPT_BKPT; 42596 } 43217 } 42597 if( nOvfl ){ 43218 if( nOvfl ){ 42598 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext); 43219 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext); 42599 if( rc ) return rc; 43220 if( rc ) return rc; 42600 } 43221 } > 43222 > 43223 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) ) > 43224 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1 > 43225 ){ > 43226 /* There is no reason any cursor should have an outstanding reference > 43227 ** to an overflow page belonging to a cell that is being deleted/updated. > 43228 ** So if there exists more than one reference to this page, then it > 43229 ** must not really be an overflow page and the database must be corrupt. > 43230 ** It is helpful to detect this before calling freePage2(), as > 43231 ** freePage2() may zero the page contents if secure-delete mode is > 43232 ** enabled. If this 'overflow' page happens to be a page that the > 43233 ** caller is iterating through or using in some other way, this > 43234 ** can be problematic. > 43235 */ > 43236 rc = SQLITE_CORRUPT_BKPT; > 43237 }else{ 42601 rc = freePage2(pBt, pOvfl, ovflPgno); | 43238 rc = freePage2(pBt, pOvfl, ovflPgno); > 43239 } > 43240 42602 if( pOvfl ){ 43241 if( pOvfl ){ 42603 sqlite3PagerUnref(pOvfl->pDbPage); 43242 sqlite3PagerUnref(pOvfl->pDbPage); 42604 } 43243 } 42605 if( rc ) return rc; 43244 if( rc ) return rc; 42606 ovflPgno = iNext; 43245 ovflPgno = iNext; 42607 } 43246 } 42608 return SQLITE_OK; 43247 return SQLITE_OK; ................................................................................................................................................................................ 42838 int i, /* New cell becomes the i-th cell of the page */ 43477 int i, /* New cell becomes the i-th cell of the page */ 42839 u8 *pCell, /* Content of the new cell */ 43478 u8 *pCell, /* Content of the new cell */ 42840 int sz, /* Bytes of content in pCell */ 43479 int sz, /* Bytes of content in pCell */ 42841 u8 *pTemp, /* Temp storage space for pCell, if needed */ 43480 u8 *pTemp, /* Temp storage space for pCell, if needed */ 42842 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */ 43481 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */ 42843 int *pRC /* Read and write return code from here */ 43482 int *pRC /* Read and write return code from here */ 42844 ){ 43483 ){ 42845 int idx; /* Where to write new cell content in data[] */ | 43484 int idx = 0; /* Where to write new cell content in data[] */ 42846 int j; /* Loop counter */ 43485 int j; /* Loop counter */ 42847 int end; /* First byte past the last cell pointer in data[] */ 43486 int end; /* First byte past the last cell pointer in data[] */ 42848 int ins; /* Index in data[] where new cell pointer is inserted */ 43487 int ins; /* Index in data[] where new cell pointer is inserted */ 42849 int cellOffset; /* Address of first cell pointer in data[] */ 43488 int cellOffset; /* Address of first cell pointer in data[] */ 42850 u8 *data; /* The content of the whole page */ 43489 u8 *data; /* The content of the whole page */ 42851 u8 *ptr; /* Used for moving information around in data[] */ 43490 u8 *ptr; /* Used for moving information around in data[] */ 42852 43491 ................................................................................................................................................................................ 43329 ** later on. 43968 ** later on. 43330 ** 43969 ** 43331 ** Unless SQLite is compiled in secure-delete mode. In this case, 43970 ** Unless SQLite is compiled in secure-delete mode. In this case, 43332 ** the dropCell() routine will overwrite the entire cell with zeroes. 43971 ** the dropCell() routine will overwrite the entire cell with zeroes. 43333 ** In this case, temporarily copy the cell into the aOvflSpace[] 43972 ** In this case, temporarily copy the cell into the aOvflSpace[] 43334 ** buffer. It will be copied out again as soon as the aSpace[] buffer 43973 ** buffer. It will be copied out again as soon as the aSpace[] buffer 43335 ** is allocated. */ 43974 ** is allocated. */ 43336 #ifdef SQLITE_SECURE_DELETE | 43975 if( pBt->secureDelete ){ > 43976 int iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aDat > 43977 if( (iOff+szNew[i])>pBt->usableSize ){ > 43978 rc = SQLITE_CORRUPT_BKPT; > 43979 memset(apOld, 0, (i+1)*sizeof(MemPage*)); > 43980 goto balance_cleanup; > 43981 }else{ 43337 memcpy(&aOvflSpace[apDiv[i]-pParent->aData], apDiv[i], szNew[i]); | 43982 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]); 43338 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData]; | 43983 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData]; 43339 #endif < > 43984 } > 43985 } 43340 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc); 43986 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc); 43341 } 43987 } 43342 } 43988 } 43343 43989 43344 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte 43990 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte 43345 ** alignment */ 43991 ** alignment */ 43346 nMaxCells = (nMaxCells + 3)&~3; 43992 nMaxCells = (nMaxCells + 3)&~3; ................................................................................................................................................................................ 43452 subtotal += szCell[i] + 2; 44098 subtotal += szCell[i] + 2; 43453 if( subtotal > usableSpace ){ 44099 if( subtotal > usableSpace ){ 43454 szNew[k] = subtotal - szCell[i]; 44100 szNew[k] = subtotal - szCell[i]; 43455 cntNew[k] = i; 44101 cntNew[k] = i; 43456 if( leafData ){ i--; } 44102 if( leafData ){ i--; } 43457 subtotal = 0; 44103 subtotal = 0; 43458 k++; 44104 k++; 43459 if( k>NB+1 ){ rc = SQLITE_CORRUPT; goto balance_cleanup; } | 44105 if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; } 43460 } 44106 } 43461 } 44107 } 43462 szNew[k] = subtotal; 44108 szNew[k] = subtotal; 43463 cntNew[k] = nCell; 44109 cntNew[k] = nCell; 43464 k++; 44110 k++; 43465 44111 43466 /* 44112 /* ................................................................................................................................................................................ 43506 nOld>=3 ? apOld[2]->pgno : 0 44152 nOld>=3 ? apOld[2]->pgno : 0 43507 )); 44153 )); 43508 44154 43509 /* 44155 /* 43510 ** Allocate k new pages. Reuse old pages where possible. 44156 ** Allocate k new pages. Reuse old pages where possible. 43511 */ 44157 */ 43512 if( apOld[0]->pgno<=1 ){ 44158 if( apOld[0]->pgno<=1 ){ 43513 rc = SQLITE_CORRUPT; | 44159 rc = SQLITE_CORRUPT_BKPT; 43514 goto balance_cleanup; 44160 goto balance_cleanup; 43515 } 44161 } 43516 pageFlags = apOld[0]->aData[0]; 44162 pageFlags = apOld[0]->aData[0]; 43517 for(i=0; i<k; i++){ 44163 for(i=0; i<k; i++){ 43518 MemPage *pNew; 44164 MemPage *pNew; 43519 if( i<nOld ){ 44165 if( i<nOld ){ 43520 pNew = apNew[i] = apOld[i]; 44166 pNew = apNew[i] = apOld[i]; ................................................................................................................................................................................ 44944 ** 7. Verify that the depth of all children is the same. 45590 ** 7. Verify that the depth of all children is the same. 44945 ** 8. Make sure this page is at least 33% full or else it is 45591 ** 8. Make sure this page is at least 33% full or else it is 44946 ** the root of the tree. 45592 ** the root of the tree. 44947 */ 45593 */ 44948 static int checkTreePage( 45594 static int checkTreePage( 44949 IntegrityCk *pCheck, /* Context for the sanity check */ 45595 IntegrityCk *pCheck, /* Context for the sanity check */ 44950 int iPage, /* Page number of the page to check */ 45596 int iPage, /* Page number of the page to check */ 44951 char *zParentContext /* Parent context */ | 45597 char *zParentContext, /* Parent context */ > 45598 i64 *pnParentMinKey, > 45599 i64 *pnParentMaxKey 44952 ){ 45600 ){ 44953 MemPage *pPage; 45601 MemPage *pPage; 44954 int i, rc, depth, d2, pgno, cnt; 45602 int i, rc, depth, d2, pgno, cnt; 44955 int hdr, cellStart; 45603 int hdr, cellStart; 44956 int nCell; 45604 int nCell; 44957 u8 *data; 45605 u8 *data; 44958 BtShared *pBt; 45606 BtShared *pBt; 44959 int usableSize; 45607 int usableSize; 44960 char zContext[100]; 45608 char zContext[100]; 44961 char *hit = 0; 45609 char *hit = 0; > 45610 i64 nMinKey = 0; > 45611 i64 nMaxKey = 0; 44962 45612 44963 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage); 45613 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage); 44964 45614 44965 /* Check that the page exists 45615 /* Check that the page exists 44966 */ 45616 */ 44967 pBt = pCheck->pBt; 45617 pBt = pCheck->pBt; 44968 usableSize = pBt->usableSize; 45618 usableSize = pBt->usableSize; ................................................................................................................................................................................ 44997 */ 45647 */ 44998 sqlite3_snprintf(sizeof(zContext), zContext, 45648 sqlite3_snprintf(sizeof(zContext), zContext, 44999 "On tree page %d cell %d: ", iPage, i); 45649 "On tree page %d cell %d: ", iPage, i); 45000 pCell = findCell(pPage,i); 45650 pCell = findCell(pPage,i); 45001 btreeParseCellPtr(pPage, pCell, &info); 45651 btreeParseCellPtr(pPage, pCell, &info); 45002 sz = info.nData; 45652 sz = info.nData; 45003 if( !pPage->intKey ) sz += (int)info.nKey; 45653 if( !pPage->intKey ) sz += (int)info.nKey; > 45654 /* For intKey pages, check that the keys are in order. > 45655 */ > 45656 else if( i==0 ) nMinKey = nMaxKey = info.nKey; > 45657 else{ > 45658 if( info.nKey <= nMaxKey ){ > 45659 checkAppendMsg(pCheck, zContext, > 45660 "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey); > 45661 } > 45662 nMaxKey = info.nKey; > 45663 } 45004 assert( sz==info.nPayload ); 45664 assert( sz==info.nPayload ); 45005 if( (sz>info.nLocal) 45665 if( (sz>info.nLocal) 45006 && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize]) 45666 && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize]) 45007 ){ 45667 ){ 45008 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4); 45668 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4); 45009 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]); 45669 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]); 45010 #ifndef SQLITE_OMIT_AUTOVACUUM 45670 #ifndef SQLITE_OMIT_AUTOVACUUM ................................................................................................................................................................................ 45020 if( !pPage->leaf ){ 45680 if( !pPage->leaf ){ 45021 pgno = get4byte(pCell); 45681 pgno = get4byte(pCell); 45022 #ifndef SQLITE_OMIT_AUTOVACUUM 45682 #ifndef SQLITE_OMIT_AUTOVACUUM 45023 if( pBt->autoVacuum ){ 45683 if( pBt->autoVacuum ){ 45024 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext); 45684 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext); 45025 } 45685 } 45026 #endif 45686 #endif 45027 d2 = checkTreePage(pCheck, pgno, zContext); | 45687 d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKe 45028 if( i>0 && d2!=depth ){ 45688 if( i>0 && d2!=depth ){ 45029 checkAppendMsg(pCheck, zContext, "Child page depth differs"); 45689 checkAppendMsg(pCheck, zContext, "Child page depth differs"); 45030 } 45690 } 45031 depth = d2; 45691 depth = d2; 45032 } 45692 } 45033 } 45693 } > 45694 45034 if( !pPage->leaf ){ 45695 if( !pPage->leaf ){ 45035 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); 45696 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); 45036 sqlite3_snprintf(sizeof(zContext), zContext, 45697 sqlite3_snprintf(sizeof(zContext), zContext, 45037 "On page %d at right child: ", iPage); 45698 "On page %d at right child: ", iPage); 45038 #ifndef SQLITE_OMIT_AUTOVACUUM 45699 #ifndef SQLITE_OMIT_AUTOVACUUM 45039 if( pBt->autoVacuum ){ 45700 if( pBt->autoVacuum ){ 45040 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0); | 45701 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext); 45041 } 45702 } 45042 #endif 45703 #endif 45043 checkTreePage(pCheck, pgno, zContext); | 45704 checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey) 45044 } 45705 } 45045 45706 > 45707 /* For intKey leaf pages, check that the min/max keys are in order > 45708 ** with any left/parent/right pages. > 45709 */ > 45710 if( pPage->leaf && pPage->intKey ){ > 45711 /* if we are a left child page */ > 45712 if( pnParentMinKey ){ > 45713 /* if we are the left most child page */ > 45714 if( !pnParentMaxKey ){ > 45715 if( nMaxKey > *pnParentMinKey ){ > 45716 checkAppendMsg(pCheck, zContext, > 45717 "Rowid %lld out of order (max larger than parent min of %lld)", > 45718 nMaxKey, *pnParentMinKey); > 45719 } > 45720 }else{ > 45721 if( nMinKey <= *pnParentMinKey ){ > 45722 checkAppendMsg(pCheck, zContext, > 45723 "Rowid %lld out of order (min less than parent min of %lld)", > 45724 nMinKey, *pnParentMinKey); > 45725 } > 45726 if( nMaxKey > *pnParentMaxKey ){ > 45727 checkAppendMsg(pCheck, zContext, > 45728 "Rowid %lld out of order (max larger than parent max of %lld)", > 45729 nMaxKey, *pnParentMaxKey); > 45730 } > 45731 *pnParentMinKey = nMaxKey; > 45732 } > 45733 /* else if we're a right child page */ > 45734 } else if( pnParentMaxKey ){ > 45735 if( nMinKey <= *pnParentMaxKey ){ > 45736 checkAppendMsg(pCheck, zContext, > 45737 "Rowid %lld out of order (min less than parent max of %lld)", > 45738 nMinKey, *pnParentMaxKey); > 45739 } > 45740 } > 45741 } > 45742 45046 /* Check for complete coverage of the page 45743 /* Check for complete coverage of the page 45047 */ 45744 */ 45048 data = pPage->aData; 45745 data = pPage->aData; 45049 hdr = pPage->hdrOffset; 45746 hdr = pPage->hdrOffset; 45050 hit = sqlite3PageMalloc( pBt->pageSize ); 45747 hit = sqlite3PageMalloc( pBt->pageSize ); 45051 if( hit==0 ){ 45748 if( hit==0 ){ 45052 pCheck->mallocFailed = 1; 45749 pCheck->mallocFailed = 1; ................................................................................................................................................................................ 45062 u16 size = 1024; 45759 u16 size = 1024; 45063 int j; 45760 int j; 45064 if( pc<=usableSize-4 ){ 45761 if( pc<=usableSize-4 ){ 45065 size = cellSizePtr(pPage, &data[pc]); 45762 size = cellSizePtr(pPage, &data[pc]); 45066 } 45763 } 45067 if( (pc+size-1)>=usableSize ){ 45764 if( (pc+size-1)>=usableSize ){ 45068 checkAppendMsg(pCheck, 0, 45765 checkAppendMsg(pCheck, 0, 45069 "Corruption detected in cell %d on page %d",i,iPage,0); | 45766 "Corruption detected in cell %d on page %d",i,iPage); 45070 }else{ 45767 }else{ 45071 for(j=pc+size-1; j>=pc; j--) hit[j]++; 45768 for(j=pc+size-1; j>=pc; j--) hit[j]++; 45072 } 45769 } 45073 } 45770 } 45074 i = get2byte(&data[hdr+1]); 45771 i = get2byte(&data[hdr+1]); 45075 while( i>0 ){ 45772 while( i>0 ){ 45076 int size, j; 45773 int size, j; ................................................................................................................................................................................ 45168 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){ 45865 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){ 45169 if( aRoot[i]==0 ) continue; 45866 if( aRoot[i]==0 ) continue; 45170 #ifndef SQLITE_OMIT_AUTOVACUUM 45867 #ifndef SQLITE_OMIT_AUTOVACUUM 45171 if( pBt->autoVacuum && aRoot[i]>1 ){ 45868 if( pBt->autoVacuum && aRoot[i]>1 ){ 45172 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0); 45869 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0); 45173 } 45870 } 45174 #endif 45871 #endif 45175 checkTreePage(&sCheck, aRoot[i], "List of tree roots: "); | 45872 checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL); 45176 } 45873 } 45177 45874 45178 /* Make sure every page in the file is referenced 45875 /* Make sure every page in the file is referenced 45179 */ 45876 */ 45180 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){ 45877 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){ 45181 #ifdef SQLITE_OMIT_AUTOVACUUM 45878 #ifdef SQLITE_OMIT_AUTOVACUUM 45182 if( sCheck.anRef[i]==0 ){ 45879 if( sCheck.anRef[i]==0 ){ ................................................................................................................................................................................ 45501 pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse)); 46198 pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse)); 45502 if( pParse==0 ){ 46199 if( pParse==0 ){ 45503 sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory"); 46200 sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory"); 45504 rc = SQLITE_NOMEM; 46201 rc = SQLITE_NOMEM; 45505 }else{ 46202 }else{ 45506 pParse->db = pDb; 46203 pParse->db = pDb; 45507 if( sqlite3OpenTempDatabase(pParse) ){ 46204 if( sqlite3OpenTempDatabase(pParse) ){ 45508 sqlite3ErrorClear(pParse); < 45509 sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg); 46205 sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg); 45510 rc = SQLITE_ERROR; 46206 rc = SQLITE_ERROR; 45511 } 46207 } > 46208 sqlite3DbFree(pErrorDb, pParse->zErrMsg); 45512 sqlite3StackFree(pErrorDb, pParse); 46209 sqlite3StackFree(pErrorDb, pParse); 45513 } 46210 } 45514 if( rc ){ 46211 if( rc ){ 45515 return 0; 46212 return 0; 45516 } 46213 } 45517 } 46214 } 45518 46215 ................................................................................................................................................................................ 46347 ** there are reports that windows throws an expection 47044 ** there are reports that windows throws an expection 46348 ** if the floating point value is out of range. (See ticket #2880.) 47045 ** if the floating point value is out of range. (See ticket #2880.) 46349 ** Because we do not completely understand the problem, we will 47046 ** Because we do not completely understand the problem, we will 46350 ** take the conservative approach and always do range tests 47047 ** take the conservative approach and always do range tests 46351 ** before attempting the conversion. 47048 ** before attempting the conversion. 46352 */ 47049 */ 46353 static i64 doubleToInt64(double r){ 47050 static i64 doubleToInt64(double r){ > 47051 #ifdef SQLITE_OMIT_FLOATING_POINT > 47052 /* When floating-point is omitted, double and int64 are the same thing */ > 47053 return r; > 47054 #else 46354 /* 47055 /* 46355 ** Many compilers we encounter do not define constants for the 47056 ** Many compilers we encounter do not define constants for the 46356 ** minimum and maximum 64-bit integers, or they define them 47057 ** minimum and maximum 64-bit integers, or they define them 46357 ** inconsistently. And many do not understand the "LL" notation. 47058 ** inconsistently. And many do not understand the "LL" notation. 46358 ** So we define our own static constants here using nothing 47059 ** So we define our own static constants here using nothing 46359 ** larger than a 32-bit integer constant. 47060 ** larger than a 32-bit integer constant. 46360 */ 47061 */ ................................................................................................................................................................................ 46368 ** a very large positive number to an integer results in a very large 47069 ** a very large positive number to an integer results in a very large 46369 ** negative integer. This makes no sense, but it is what x86 hardware 47070 ** negative integer. This makes no sense, but it is what x86 hardware 46370 ** does so for compatibility we will do the same in software. */ 47071 ** does so for compatibility we will do the same in software. */ 46371 return minInt; 47072 return minInt; 46372 }else{ 47073 }else{ 46373 return (i64)r; 47074 return (i64)r; 46374 } 47075 } > 47076 #endif 46375 } 47077 } 46376 47078 46377 /* 47079 /* 46378 ** Return some kind of integer value which is the best we can do 47080 ** Return some kind of integer value which is the best we can do 46379 ** at representing the value that *pMem describes as an integer. 47081 ** at representing the value that *pMem describes as an integer. 46380 ** If pMem is an integer, then the value is exact. If pMem is 47082 ** If pMem is an integer, then the value is exact. If pMem is 46381 ** a floating-point then the value returned is the integer part. 47083 ** a floating-point then the value returned is the integer part. ................................................................................................................................................................................ 46495 MemSetTypeFlag(pMem, MEM_Real); 47197 MemSetTypeFlag(pMem, MEM_Real); 46496 return SQLITE_OK; 47198 return SQLITE_OK; 46497 } 47199 } 46498 47200 46499 /* 47201 /* 46500 ** Convert pMem so that it has types MEM_Real or MEM_Int or both. 47202 ** Convert pMem so that it has types MEM_Real or MEM_Int or both. 46501 ** Invalidate any prior representations. 47203 ** Invalidate any prior representations. > 47204 ** > 47205 ** Every effort is made to force the conversion, even if the input > 47206 ** is a string that does not look completely like a number. Convert > 47207 ** as much of the string as we can and ignore the rest. 46502 */ 47208 */ 46503 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){ 47209 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){ 46504 double r1, r2; < 46505 i64 i; < > 47210 int rc; 46506 assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ); 47211 assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ); 46507 assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 ); 47212 assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 ); 46508 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); 47213 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); 46509 r1 = sqlite3VdbeRealValue(pMem); | 47214 rc = sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8); 46510 i = doubleToInt64(r1); | 47215 if( rc ) return rc; 46511 r2 = (double)i; | 47216 rc = sqlite3VdbeMemNulTerminate(pMem); 46512 if( r1==r2 ){ | 47217 if( rc ) return rc; 46513 sqlite3VdbeMemIntegerify(pMem); | 47218 if( sqlite3Atoi64(pMem->z, &pMem->u.i) ){ > 47219 MemSetTypeFlag(pMem, MEM_Int); 46514 }else{ 47220 }else{ 46515 pMem->r = r1; | 47221 pMem->r = sqlite3VdbeRealValue(pMem); 46516 MemSetTypeFlag(pMem, MEM_Real); 47222 MemSetTypeFlag(pMem, MEM_Real); > 47223 sqlite3VdbeIntegerAffinity(pMem); 46517 } 47224 } 46518 return SQLITE_OK; 47225 return SQLITE_OK; 46519 } 47226 } 46520 47227 46521 /* 47228 /* 46522 ** Delete any previous value and set the value stored in *pMem to NULL. 47229 ** Delete any previous value and set the value stored in *pMem to NULL. 46523 */ 47230 */ ................................................................................................................................................................................ 46561 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){ 47268 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){ 46562 sqlite3VdbeMemRelease(pMem); 47269 sqlite3VdbeMemRelease(pMem); 46563 pMem->u.i = val; 47270 pMem->u.i = val; 46564 pMem->flags = MEM_Int; 47271 pMem->flags = MEM_Int; 46565 pMem->type = SQLITE_INTEGER; 47272 pMem->type = SQLITE_INTEGER; 46566 } 47273 } 46567 47274 > 47275 #ifndef SQLITE_OMIT_FLOATING_POINT 46568 /* 47276 /* 46569 ** Delete any previous value and set the value stored in *pMem to val, 47277 ** Delete any previous value and set the value stored in *pMem to val, 46570 ** manifest type REAL. 47278 ** manifest type REAL. 46571 */ 47279 */ 46572 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){ 47280 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){ 46573 if( sqlite3IsNaN(val) ){ 47281 if( sqlite3IsNaN(val) ){ 46574 sqlite3VdbeMemSetNull(pMem); 47282 sqlite3VdbeMemSetNull(pMem); ................................................................................................................................................................................ 46575 }else{ 47283 }else{ 46576 sqlite3VdbeMemRelease(pMem); 47284 sqlite3VdbeMemRelease(pMem); 46577 pMem->r = val; 47285 pMem->r = val; 46578 pMem->flags = MEM_Real; 47286 pMem->flags = MEM_Real; 46579 pMem->type = SQLITE_FLOAT; 47287 pMem->type = SQLITE_FLOAT; 46580 } 47288 } 46581 } 47289 } > 47290 #endif 46582 47291 46583 /* 47292 /* 46584 ** Delete any previous value and set the value of pMem to be an 47293 ** Delete any previous value and set the value of pMem to be an 46585 ** empty boolean index. 47294 ** empty boolean index. 46586 */ 47295 */ 46587 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){ 47296 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){ 46588 sqlite3 *db = pMem->db; 47297 sqlite3 *db = pMem->db; ................................................................................................................................................................................ 46629 ** and flags gets srcType (either MEM_Ephem or MEM_Static). 47338 ** and flags gets srcType (either MEM_Ephem or MEM_Static). 46630 */ 47339 */ 46631 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int sr 47340 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int sr 46632 assert( (pFrom->flags & MEM_RowSet)==0 ); 47341 assert( (pFrom->flags & MEM_RowSet)==0 ); 46633 sqlite3VdbeMemReleaseExternal(pTo); 47342 sqlite3VdbeMemReleaseExternal(pTo); 46634 memcpy(pTo, pFrom, MEMCELLSIZE); 47343 memcpy(pTo, pFrom, MEMCELLSIZE); 46635 pTo->xDel = 0; 47344 pTo->xDel = 0; 46636 if( (pFrom->flags&MEM_Dyn)!=0 || pFrom->z==pFrom->zMalloc ){ | 47345 if( (pFrom->flags&MEM_Static)==0 ){ 46637 pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem); 47346 pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem); 46638 assert( srcType==MEM_Ephem || srcType==MEM_Static ); 47347 assert( srcType==MEM_Ephem || srcType==MEM_Static ); 46639 pTo->flags |= srcType; 47348 pTo->flags |= srcType; 46640 } 47349 } 46641 } 47350 } 46642 47351 46643 /* 47352 /* ................................................................................................................................................................................ 47200 } 47909 } 47201 47910 47202 /* 47911 /* 47203 ** Return the SQL associated with a prepared statement 47912 ** Return the SQL associated with a prepared statement 47204 */ 47913 */ 47205 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){ 47914 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){ 47206 Vdbe *p = (Vdbe *)pStmt; 47915 Vdbe *p = (Vdbe *)pStmt; 47207 return (p->isPrepareV2 ? p->zSql : 0); | 47916 return (p && p->isPrepareV2) ? p->zSql : 0; 47208 } 47917 } 47209 47918 47210 /* 47919 /* 47211 ** Swap all content between two VDBE structures. 47920 ** Swap all content between two VDBE structures. 47212 */ 47921 */ 47213 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){ 47922 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){ 47214 Vdbe tmp, *pTmp; 47923 Vdbe tmp, *pTmp; ................................................................................................................................................................................ 47388 int j = -1-x; 48097 int j = -1-x; 47389 assert( p->magic==VDBE_MAGIC_INIT ); 48098 assert( p->magic==VDBE_MAGIC_INIT ); 47390 assert( j>=0 && j<p->nLabel ); 48099 assert( j>=0 && j<p->nLabel ); 47391 if( p->aLabel ){ 48100 if( p->aLabel ){ 47392 p->aLabel[j] = p->nOp; 48101 p->aLabel[j] = p->nOp; 47393 } 48102 } 47394 } 48103 } > 48104 > 48105 /* > 48106 ** Mark the VDBE as one that can only be run one time. > 48107 */ > 48108 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){ > 48109 p->runOnlyOnce = 1; > 48110 } 47395 48111 47396 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */ 48112 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */ 47397 48113 47398 /* 48114 /* 47399 ** The following type and function are used to iterate through all opcodes 48115 ** The following type and function are used to iterate through all opcodes 47400 ** in a Vdbe main program and each of the sub-programs (triggers) it may 48116 ** in a Vdbe main program and each of the sub-programs (triggers) it may 47401 ** invoke directly or indirectly. It should be used as follows: 48117 ** invoke directly or indirectly. It should be used as follows: ................................................................................................................................................................................ 48193 sqlite3 *db = p->db; /* The database connection */ 48909 sqlite3 *db = p->db; /* The database connection */ 48194 int i; /* Loop counter */ 48910 int i; /* Loop counter */ 48195 int rc = SQLITE_OK; /* Return code */ 48911 int rc = SQLITE_OK; /* Return code */ 48196 Mem *pMem = p->pResultSet = &p->aMem[1]; /* First Mem of result set */ 48912 Mem *pMem = p->pResultSet = &p->aMem[1]; /* First Mem of result set */ 48197 48913 48198 assert( p->explain ); 48914 assert( p->explain ); 48199 assert( p->magic==VDBE_MAGIC_RUN ); 48915 assert( p->magic==VDBE_MAGIC_RUN ); 48200 assert( db->magic==SQLITE_MAGIC_BUSY ); < 48201 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM ); 48916 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM ); 48202 48917 48203 /* Even though this opcode does not use dynamic strings for 48918 /* Even though this opcode does not use dynamic strings for 48204 ** the result, result columns may become dynamic if the user calls 48919 ** the result, result columns may become dynamic if the user calls 48205 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding. 48920 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding. 48206 */ 48921 */ 48207 releaseMemArray(pMem, 8); 48922 releaseMemArray(pMem, 8); ................................................................................................................................................................................ 48608 sqlite3BtreeCloseCursor(pCx->pCursor); 49323 sqlite3BtreeCloseCursor(pCx->pCursor); 48609 } 49324 } 48610 #ifndef SQLITE_OMIT_VIRTUALTABLE 49325 #ifndef SQLITE_OMIT_VIRTUALTABLE 48611 if( pCx->pVtabCursor ){ 49326 if( pCx->pVtabCursor ){ 48612 sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor; 49327 sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor; 48613 const sqlite3_module *pModule = pCx->pModule; 49328 const sqlite3_module *pModule = pCx->pModule; 48614 p->inVtabMethod = 1; 49329 p->inVtabMethod = 1; 48615 (void)sqlite3SafetyOff(p->db); < 48616 pModule->xClose(pVtabCursor); 49330 pModule->xClose(pVtabCursor); 48617 (void)sqlite3SafetyOn(p->db); < 48618 p->inVtabMethod = 0; 49331 p->inVtabMethod = 0; 48619 } 49332 } 48620 #endif 49333 #endif 48621 } 49334 } 48622 49335 48623 /* 49336 /* 48624 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This 49337 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This ................................................................................................................................................................................ 48791 needXcommit = 1; 49504 needXcommit = 1; 48792 if( i!=1 ) nTrans++; 49505 if( i!=1 ) nTrans++; 48793 } 49506 } 48794 } 49507 } 48795 49508 48796 /* If there are any write-transactions at all, invoke the commit hook */ 49509 /* If there are any write-transactions at all, invoke the commit hook */ 48797 if( needXcommit && db->xCommitCallback ){ 49510 if( needXcommit && db->xCommitCallback ){ 48798 (void)sqlite3SafetyOff(db); < 48799 rc = db->xCommitCallback(db->pCommitArg); 49511 rc = db->xCommitCallback(db->pCommitArg); 48800 (void)sqlite3SafetyOn(db); < 48801 if( rc ){ 49512 if( rc ){ 48802 return SQLITE_CONSTRAINT; 49513 return SQLITE_CONSTRAINT; 48803 } 49514 } 48804 } 49515 } 48805 49516 48806 /* The simple case - no more than one database file (not counting the 49517 /* The simple case - no more than one database file (not counting the 48807 ** TEMP database) has a transaction active. There is no need for the 49518 ** TEMP database) has a transaction active. There is no need for the ................................................................................................................................................................................ 49259 db->autoCommit = 1; 49970 db->autoCommit = 1; 49260 } 49971 } 49261 } 49972 } 49262 49973 49263 /* If eStatementOp is non-zero, then a statement transaction needs to 49974 /* If eStatementOp is non-zero, then a statement transaction needs to 49264 ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to 49975 ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to 49265 ** do so. If this operation returns an error, and the current statement 49976 ** do so. If this operation returns an error, and the current statement 49266 ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then set the error | 49977 ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the 49267 ** code to the new value. | 49978 ** current statement error code. > 49979 ** > 49980 ** Note that sqlite3VdbeCloseStatement() can only fail if eStatementOp > 49981 ** is SAVEPOINT_ROLLBACK. But if p->rc==SQLITE_OK then eStatementOp > 49982 ** must be SAVEPOINT_RELEASE. Hence the NEVER(p->rc==SQLITE_OK) in > 49983 ** the following code. 49268 */ 49984 */ 49269 if( eStatementOp ){ 49985 if( eStatementOp ){ 49270 rc = sqlite3VdbeCloseStatement(p, eStatementOp); 49986 rc = sqlite3VdbeCloseStatement(p, eStatementOp); 49271 if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){ | 49987 if( rc && (NEVER(p->rc==SQLITE_OK) || p->rc==SQLITE_CONSTRAINT) ){ 49272 p->rc = rc; 49988 p->rc = rc; 49273 sqlite3DbFree(db, p->zErrMsg); 49989 sqlite3DbFree(db, p->zErrMsg); 49274 p->zErrMsg = 0; 49990 p->zErrMsg = 0; 49275 } 49991 } 49276 } 49992 } 49277 49993 49278 /* If this was an INSERT, UPDATE or DELETE and no statement transaction 49994 /* If this was an INSERT, UPDATE or DELETE and no statement transaction ................................................................................................................................................................................ 49347 sqlite3 *db; 50063 sqlite3 *db; 49348 db = p->db; 50064 db = p->db; 49349 50065 49350 /* If the VM did not run to completion or if it encountered an 50066 /* If the VM did not run to completion or if it encountered an 49351 ** error, then it might not have been halted properly. So halt 50067 ** error, then it might not have been halted properly. So halt 49352 ** it now. 50068 ** it now. 49353 */ 50069 */ 49354 (void)sqlite3SafetyOn(db); < 49355 sqlite3VdbeHalt(p); 50070 sqlite3VdbeHalt(p); 49356 (void)sqlite3SafetyOff(db); < 49357 50071 49358 /* If the VDBE has be run even partially, then transfer the error code 50072 /* If the VDBE has be run even partially, then transfer the error code 49359 ** and error message from the VDBE into the main database structure. But 50073 ** and error message from the VDBE into the main database structure. But 49360 ** if the VDBE has just been set to run but has not actually executed any 50074 ** if the VDBE has just been set to run but has not actually executed any 49361 ** instructions yet, leave the main database error information unchanged. 50075 ** instructions yet, leave the main database error information unchanged. 49362 */ 50076 */ 49363 if( p->pc>=0 ){ 50077 if( p->pc>=0 ){ ................................................................................................................................................................................ 49369 sqlite3DbFree(db, p->zErrMsg); 50083 sqlite3DbFree(db, p->zErrMsg); 49370 p->zErrMsg = 0; 50084 p->zErrMsg = 0; 49371 }else if( p->rc ){ 50085 }else if( p->rc ){ 49372 sqlite3Error(db, p->rc, 0); 50086 sqlite3Error(db, p->rc, 0); 49373 }else{ 50087 }else{ 49374 sqlite3Error(db, SQLITE_OK, 0); 50088 sqlite3Error(db, SQLITE_OK, 0); 49375 } 50089 } > 50090 if( p->runOnlyOnce ) p->expired = 1; 49376 }else if( p->rc && p->expired ){ 50091 }else if( p->rc && p->expired ){ 49377 /* The expired flag was set on the VDBE before the first call 50092 /* The expired flag was set on the VDBE before the first call 49378 ** to sqlite3_step(). For consistency (since sqlite3_step() was 50093 ** to sqlite3_step(). For consistency (since sqlite3_step() was 49379 ** called), set the database error in this case as well. 50094 ** called), set the database error in this case as well. 49380 */ 50095 */ 49381 sqlite3Error(db, p->rc, 0); 50096 sqlite3Error(db, p->rc, 0); 49382 sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT); 50097 sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT); ................................................................................................................................................................................ 49470 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N); 50185 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N); 49471 vdbeFreeOpArray(db, p->aOp, p->nOp); 50186 vdbeFreeOpArray(db, p->aOp, p->nOp); 49472 sqlite3DbFree(db, p->aLabel); 50187 sqlite3DbFree(db, p->aLabel); 49473 sqlite3DbFree(db, p->aColName); 50188 sqlite3DbFree(db, p->aColName); 49474 sqlite3DbFree(db, p->zSql); 50189 sqlite3DbFree(db, p->zSql); 49475 p->magic = VDBE_MAGIC_DEAD; 50190 p->magic = VDBE_MAGIC_DEAD; 49476 sqlite3DbFree(db, p->pFree); 50191 sqlite3DbFree(db, p->pFree); > 50192 p->db = 0; 49477 sqlite3DbFree(db, p); 50193 sqlite3DbFree(db, p); 49478 } 50194 } 49479 50195 49480 /* 50196 /* 49481 ** Make sure the cursor p is ready to read or write the row to which it 50197 ** Make sure the cursor p is ready to read or write the row to which it 49482 ** was last positioned. Return an error code if an OOM fault or I/O error 50198 ** was last positioned. Return an error code if an OOM fault or I/O error 49483 ** prevents us from positioning the cursor to its correct position. 50199 ** prevents us from positioning the cursor to its correct position. ................................................................................................................................................................................ 50150 assert( sqlite3BtreeCursorIsValid(pCur) ); 50866 assert( sqlite3BtreeCursorIsValid(pCur) ); 50151 rc = sqlite3BtreeKeySize(pCur, &nCellKey); 50867 rc = sqlite3BtreeKeySize(pCur, &nCellKey); 50152 assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */ 50868 assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */ 50153 /* nCellKey will always be between 0 and 0xffffffff because of the say 50869 /* nCellKey will always be between 0 and 0xffffffff because of the say 50154 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */ 50870 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */ 50155 if( nCellKey<=0 || nCellKey>0x7fffffff ){ 50871 if( nCellKey<=0 || nCellKey>0x7fffffff ){ 50156 *res = 0; 50872 *res = 0; 50157 return SQLITE_CORRUPT; | 50873 return SQLITE_CORRUPT_BKPT; 50158 } 50874 } 50159 memset(&m, 0, sizeof(m)); 50875 memset(&m, 0, sizeof(m)); 50160 rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m); 50876 rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m); 50161 if( rc ){ 50877 if( rc ){ 50162 return rc; 50878 return rc; 50163 } 50879 } 50164 assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID ); 50880 assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID ); ................................................................................................................................................................................ 50276 ** added or changed. 50992 ** added or changed. 50277 */ 50993 */ 50278 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){ 50994 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){ 50279 Vdbe *p = (Vdbe*)pStmt; 50995 Vdbe *p = (Vdbe*)pStmt; 50280 return p==0 || p->expired; 50996 return p==0 || p->expired; 50281 } 50997 } 50282 #endif 50998 #endif > 50999 > 51000 /* > 51001 ** Check on a Vdbe to make sure it has not been finalized. Log > 51002 ** an error and return true if it has been finalized (or is otherwise > 51003 ** invalid). Return false if it is ok. > 51004 */ > 51005 static int vdbeSafety(Vdbe *p){ > 51006 if( p->db==0 ){ > 51007 sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement"); > 51008 return 1; > 51009 }else{ > 51010 return 0; > 51011 } > 51012 } > 51013 static int vdbeSafetyNotNull(Vdbe *p){ > 51014 if( p==0 ){ > 51015 sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement"); > 51016 return 1; > 51017 }else{ > 51018 return vdbeSafety(p); > 51019 } > 51020 } 50283 51021 50284 /* 51022 /* 50285 ** The following routine destroys a virtual machine that is created by 51023 ** The following routine destroys a virtual machine that is created by 50286 ** the sqlite3_compile() routine. The integer returned is an SQLITE_ 51024 ** the sqlite3_compile() routine. The integer returned is an SQLITE_ 50287 ** success/failure code that describes the result of executing the virtual 51025 ** success/failure code that describes the result of executing the virtual 50288 ** machine. 51026 ** machine. 50289 ** 51027 ** ................................................................................................................................................................................ 50294 int rc; 51032 int rc; 50295 if( pStmt==0 ){ 51033 if( pStmt==0 ){ 50296 rc = SQLITE_OK; 51034 rc = SQLITE_OK; 50297 }else{ 51035 }else{ 50298 Vdbe *v = (Vdbe*)pStmt; 51036 Vdbe *v = (Vdbe*)pStmt; 50299 sqlite3 *db = v->db; 51037 sqlite3 *db = v->db; 50300 #if SQLITE_THREADSAFE 51038 #if SQLITE_THREADSAFE > 51039 sqlite3_mutex *mutex; > 51040 #endif > 51041 if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT; > 51042 #if SQLITE_THREADSAFE 50301 sqlite3_mutex *mutex = v->db->mutex; | 51043 mutex = v->db->mutex; 50302 #endif 51044 #endif 50303 sqlite3_mutex_enter(mutex); 51045 sqlite3_mutex_enter(mutex); 50304 rc = sqlite3VdbeFinalize(v); 51046 rc = sqlite3VdbeFinalize(v); 50305 rc = sqlite3ApiExit(db, rc); 51047 rc = sqlite3ApiExit(db, rc); 50306 sqlite3_mutex_leave(mutex); 51048 sqlite3_mutex_leave(mutex); 50307 } 51049 } 50308 return rc; 51050 return rc; ................................................................................................................................................................................ 50541 */ 51283 */ 50542 static int sqlite3Step(Vdbe *p){ 51284 static int sqlite3Step(Vdbe *p){ 50543 sqlite3 *db; 51285 sqlite3 *db; 50544 int rc; 51286 int rc; 50545 51287 50546 assert(p); 51288 assert(p); 50547 if( p->magic!=VDBE_MAGIC_RUN ){ 51289 if( p->magic!=VDBE_MAGIC_RUN ){ > 51290 sqlite3_log(SQLITE_MISUSE, > 51291 "attempt to step a halted statement: [%s]", p->zSql); 50548 return SQLITE_MISUSE; | 51292 return SQLITE_MISUSE_BKPT; 50549 } 51293 } 50550 51294 50551 /* Assert that malloc() has not failed */ | 51295 /* Check that malloc() has not failed. If it has, return early. */ 50552 db = p->db; 51296 db = p->db; 50553 if( db->mallocFailed ){ 51297 if( db->mallocFailed ){ > 51298 p->rc = SQLITE_NOMEM; 50554 return SQLITE_NOMEM; 51299 return SQLITE_NOMEM; 50555 } 51300 } 50556 51301 50557 if( p->pc<=0 && p->expired ){ 51302 if( p->pc<=0 && p->expired ){ 50558 if( ALWAYS(p->rc==SQLITE_OK || p->rc==SQLITE_SCHEMA) ){ < 50559 p->rc = SQLITE_SCHEMA; | 51303 p->rc = SQLITE_SCHEMA; 50560 } < 50561 rc = SQLITE_ERROR; 51304 rc = SQLITE_ERROR; 50562 goto end_of_step; 51305 goto end_of_step; 50563 } 51306 } 50564 if( sqlite3SafetyOn(db) ){ < 50565 p->rc = SQLITE_MISUSE; < 50566 return SQLITE_MISUSE; < 50567 } < 50568 if( p->pc<0 ){ 51307 if( p->pc<0 ){ 50569 /* If there are no other statements currently running, then 51308 /* If there are no other statements currently running, then 50570 ** reset the interrupt flag. This prevents a call to sqlite3_interrupt 51309 ** reset the interrupt flag. This prevents a call to sqlite3_interrupt 50571 ** from interrupting a statement that has not yet started. 51310 ** from interrupting a statement that has not yet started. 50572 */ 51311 */ 50573 if( db->activeVdbeCnt==0 ){ 51312 if( db->activeVdbeCnt==0 ){ 50574 db->u1.isInterrupted = 0; 51313 db->u1.isInterrupted = 0; ................................................................................................................................................................................ 50593 rc = sqlite3VdbeList(p); 51332 rc = sqlite3VdbeList(p); 50594 }else 51333 }else 50595 #endif /* SQLITE_OMIT_EXPLAIN */ 51334 #endif /* SQLITE_OMIT_EXPLAIN */ 50596 { 51335 { 50597 rc = sqlite3VdbeExec(p); 51336 rc = sqlite3VdbeExec(p); 50598 } 51337 } 50599 51338 50600 if( sqlite3SafetyOff(db) ){ < 50601 rc = SQLITE_MISUSE; < 50602 } < 50603 < 50604 #ifndef SQLITE_OMIT_TRACE 51339 #ifndef SQLITE_OMIT_TRACE 50605 /* Invoke the profile callback if there is one 51340 /* Invoke the profile callback if there is one 50606 */ 51341 */ 50607 if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){ 51342 if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){ 50608 double rNow; 51343 double rNow; 50609 u64 elapseTime; 51344 u64 elapseTime; 50610 51345 ................................................................................................................................................................................ 50643 51378 50644 /* 51379 /* 50645 ** This is the top-level implementation of sqlite3_step(). Call 51380 ** This is the top-level implementation of sqlite3_step(). Call 50646 ** sqlite3Step() to do most of the work. If a schema error occurs, 51381 ** sqlite3Step() to do most of the work. If a schema error occurs, 50647 ** call sqlite3Reprepare() and try again. 51382 ** call sqlite3Reprepare() and try again. 50648 */ 51383 */ 50649 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){ 51384 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){ 50650 int rc = SQLITE_MISUSE; | 51385 int rc = SQLITE_OK; /* Result from sqlite3Step() */ 50651 if( pStmt ){ | 51386 int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */ 50652 int cnt = 0; < 50653 Vdbe *v = (Vdbe*)pStmt; | 51387 Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */ > 51388 int cnt = 0; /* Counter to prevent infinite loop of reprepares */ > 51389 sqlite3 *db; /* The database connection */ > 51390 > 51391 if( vdbeSafetyNotNull(v) ){ > 51392 return SQLITE_MISUSE_BKPT; > 51393 } 50654 sqlite3 *db = v->db; | 51394 db = v->db; 50655 sqlite3_mutex_enter(db->mutex); | 51395 sqlite3_mutex_enter(db->mutex); 50656 while( (rc = sqlite3Step(v))==SQLITE_SCHEMA | 51396 while( (rc = sqlite3Step(v))==SQLITE_SCHEMA 50657 && cnt++ < 5 | 51397 && cnt++ < 5 50658 && (rc = sqlite3Reprepare(v))==SQLITE_OK ){ | 51398 && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){ 50659 sqlite3_reset(pStmt); | 51399 sqlite3_reset(pStmt); 50660 v->expired = 0; | 51400 v->expired = 0; 50661 } | 51401 } 50662 if( rc==SQLITE_SCHEMA && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){ | 51402 if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){ 50663 /* This case occurs after failing to recompile an sql statement. | 51403 /* This case occurs after failing to recompile an sql statement. 50664 ** The error message from the SQL compiler has already been loaded | 51404 ** The error message from the SQL compiler has already been loaded 50665 ** into the database handle. This block copies the error message | 51405 ** into the database handle. This block copies the error message 50666 ** from the database handle into the statement and sets the statement | 51406 ** from the database handle into the statement and sets the statement 50667 ** program counter to 0 to ensure that when the statement is | 51407 ** program counter to 0 to ensure that when the statement is 50668 ** finalized or reset the parser error message is available via | 51408 ** finalized or reset the parser error message is available via 50669 ** sqlite3_errmsg() and sqlite3_errcode(). | 51409 ** sqlite3_errmsg() and sqlite3_errcode(). 50670 */ | 51410 */ 50671 const char *zErr = (const char *)sqlite3_value_text(db->pErr); | 51411 const char *zErr = (const char *)sqlite3_value_text(db->pErr); 50672 sqlite3DbFree(db, v->zErrMsg); | 51412 sqlite3DbFree(db, v->zErrMsg); 50673 if( !db->mallocFailed ){ | 51413 if( !db->mallocFailed ){ 50674 v->zErrMsg = sqlite3DbStrDup(db, zErr); | 51414 v->zErrMsg = sqlite3DbStrDup(db, zErr); > 51415 v->rc = rc2; 50675 } else { | 51416 } else { 50676 v->zErrMsg = 0; | 51417 v->zErrMsg = 0; 50677 v->rc = SQLITE_NOMEM; | 51418 v->rc = rc = SQLITE_NOMEM; 50678 } | 51419 } 50679 } | 51420 } 50680 rc = sqlite3ApiExit(db, rc); | 51421 rc = sqlite3ApiExit(db, rc); 50681 sqlite3_mutex_leave(db->mutex); | 51422 sqlite3_mutex_leave(db->mutex); 50682 } < 50683 return rc; 51423 return rc; 50684 } 51424 } 50685 51425 50686 /* 51426 /* 50687 ** Extract the user data from a sqlite3_context structure and return a 51427 ** Extract the user data from a sqlite3_context structure and return a 50688 ** pointer to it. 51428 ** pointer to it. 50689 */ 51429 */ ................................................................................................................................................................................ 51145 ** the mutex is released if any kind of error occurs. 51885 ** the mutex is released if any kind of error occurs. 51146 ** 51886 ** 51147 ** The error code stored in database p->db is overwritten with the return 51887 ** The error code stored in database p->db is overwritten with the return 51148 ** value in any case. 51888 ** value in any case. 51149 */ 51889 */ 51150 static int vdbeUnbind(Vdbe *p, int i){ 51890 static int vdbeUnbind(Vdbe *p, int i){ 51151 Mem *pVar; 51891 Mem *pVar; > 51892 if( vdbeSafetyNotNull(p) ){ 51152 if( p==0 ) return SQLITE_MISUSE; | 51893 return SQLITE_MISUSE_BKPT; > 51894 } 51153 sqlite3_mutex_enter(p->db->mutex); 51895 sqlite3_mutex_enter(p->db->mutex); 51154 if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){ 51896 if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){ 51155 sqlite3Error(p->db, SQLITE_MISUSE, 0); 51897 sqlite3Error(p->db, SQLITE_MISUSE, 0); 51156 sqlite3_mutex_leave(p->db->mutex); 51898 sqlite3_mutex_leave(p->db->mutex); > 51899 sqlite3_log(SQLITE_MISUSE, > 51900 "bind on a busy prepared statement: [%s]", p->zSql); 51157 return SQLITE_MISUSE; | 51901 return SQLITE_MISUSE_BKPT; 51158 } 51902 } 51159 if( i<1 || i>p->nVar ){ 51903 if( i<1 || i>p->nVar ){ 51160 sqlite3Error(p->db, SQLITE_RANGE, 0); 51904 sqlite3Error(p->db, SQLITE_RANGE, 0); 51161 sqlite3_mutex_leave(p->db->mutex); 51905 sqlite3_mutex_leave(p->db->mutex); 51162 return SQLITE_RANGE; 51906 return SQLITE_RANGE; 51163 } 51907 } 51164 i--; 51908 i--; ................................................................................................................................................................................ 51855 ** do so without loss of information. In other words, if the string 52599 ** do so without loss of information. In other words, if the string 51856 ** looks like a number, convert it into a number. If it does not 52600 ** looks like a number, convert it into a number. If it does not 51857 ** look like a number, leave it alone. 52601 ** look like a number, leave it alone. 51858 */ 52602 */ 51859 static void applyNumericAffinity(Mem *pRec){ 52603 static void applyNumericAffinity(Mem *pRec){ 51860 if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){ 52604 if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){ 51861 int realnum; 52605 int realnum; > 52606 u8 enc = pRec->enc; 51862 sqlite3VdbeMemNulTerminate(pRec); 52607 sqlite3VdbeMemNulTerminate(pRec); 51863 if( (pRec->flags&MEM_Str) < 51864 && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){ | 52608 if( (pRec->flags&MEM_Str) && sqlite3IsNumber(pRec->z, &realnum, enc) ){ 51865 i64 value; 52609 i64 value; 51866 sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8); | 52610 char *zUtf8 = pRec->z; > 52611 #ifndef SQLITE_OMIT_UTF16 > 52612 if( enc!=SQLITE_UTF8 ){ > 52613 assert( pRec->db ); > 52614 zUtf8 = sqlite3Utf16to8(pRec->db, pRec->z, pRec->n, enc); > 52615 if( !zUtf8 ) return; > 52616 } > 52617 #endif 51867 if( !realnum && sqlite3Atoi64(pRec->z, &value) ){ | 52618 if( !realnum && sqlite3Atoi64(zUtf8, &value) ){ 51868 pRec->u.i = value; 52619 pRec->u.i = value; 51869 MemSetTypeFlag(pRec, MEM_Int); 52620 MemSetTypeFlag(pRec, MEM_Int); 51870 }else{ 52621 }else{ 51871 sqlite3VdbeMemRealify(pRec); | 52622 sqlite3AtoF(zUtf8, &pRec->r); > 52623 MemSetTypeFlag(pRec, MEM_Real); 51872 } 52624 } > 52625 #ifndef SQLITE_OMIT_UTF16 > 52626 if( enc!=SQLITE_UTF8 ){ > 52627 sqlite3DbFree(pRec->db, zUtf8); > 52628 } > 52629 #endif 51873 } 52630 } 51874 } 52631 } 51875 } 52632 } 51876 52633 51877 /* 52634 /* 51878 ** Processing is determine by the affinity parameter: 52635 ** Processing is determine by the affinity parameter: 51879 ** 52636 ** ................................................................................................................................................................................ 52243 ** 53000 ** 52244 ** After this routine has finished, sqlite3VdbeFinalize() should be 53001 ** After this routine has finished, sqlite3VdbeFinalize() should be 52245 ** used to clean up the mess that was left behind. 53002 ** used to clean up the mess that was left behind. 52246 */ 53003 */ 52247 SQLITE_PRIVATE int sqlite3VdbeExec( 53004 SQLITE_PRIVATE int sqlite3VdbeExec( 52248 Vdbe *p /* The VDBE */ 53005 Vdbe *p /* The VDBE */ 52249 ){ 53006 ){ 52250 int pc; /* The program counter */ | 53007 int pc=0; /* The program counter */ 52251 Op *aOp = p->aOp; /* Copy of p->aOp */ 53008 Op *aOp = p->aOp; /* Copy of p->aOp */ 52252 Op *pOp; /* Current operation */ 53009 Op *pOp; /* Current operation */ 52253 int rc = SQLITE_OK; /* Value to return */ 53010 int rc = SQLITE_OK; /* Value to return */ 52254 sqlite3 *db = p->db; /* The database */ 53011 sqlite3 *db = p->db; /* The database */ 52255 u8 resetSchemaOnFault = 0; /* Reset schema after an error if true */ 53012 u8 resetSchemaOnFault = 0; /* Reset schema after an error if true */ 52256 u8 encoding = ENC(db); /* The database encoding */ 53013 u8 encoding = ENC(db); /* The database encoding */ 52257 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK 53014 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK ................................................................................................................................................................................ 52317 struct OP_ShiftRight_stack_vars { 53074 struct OP_ShiftRight_stack_vars { 52318 i64 a; 53075 i64 a; 52319 i64 b; 53076 i64 b; 52320 } ah; 53077 } ah; 52321 struct OP_Ge_stack_vars { 53078 struct OP_Ge_stack_vars { 52322 int res; /* Result of the comparison of pIn1 against pIn3 */ 53079 int res; /* Result of the comparison of pIn1 against pIn3 */ 52323 char affinity; /* Affinity to use for comparison */ 53080 char affinity; /* Affinity to use for comparison */ > 53081 u16 flags1; /* Copy of initial value of pIn1->flags */ > 53082 u16 flags3; /* Copy of initial value of pIn3->flags */ 52324 } ai; 53083 } ai; 52325 struct OP_Compare_stack_vars { 53084 struct OP_Compare_stack_vars { 52326 int n; 53085 int n; 52327 int i; 53086 int i; 52328 int p1; 53087 int p1; 52329 int p2; 53088 int p2; 52330 const KeyInfo *pKeyInfo; 53089 const KeyInfo *pKeyInfo; ................................................................................................................................................................................ 52354 int i; /* Loop counter */ 53113 int i; /* Loop counter */ 52355 char *zData; /* Part of the record being decoded */ 53114 char *zData; /* Part of the record being decoded */ 52356 Mem *pDest; /* Where to write the extracted value */ 53115 Mem *pDest; /* Where to write the extracted value */ 52357 Mem sMem; /* For storing the record being decoded */ 53116 Mem sMem; /* For storing the record being decoded */ 52358 u8 *zIdx; /* Index into header */ 53117 u8 *zIdx; /* Index into header */ 52359 u8 *zEndHdr; /* Pointer to first byte after the header */ 53118 u8 *zEndHdr; /* Pointer to first byte after the header */ 52360 u32 offset; /* Offset into the data */ 53119 u32 offset; /* Offset into the data */ 52361 u64 offset64; /* 64-bit offset. 64 bits needed to catch overflow */ | 53120 u32 szField; /* Number of bytes in the content of a field */ 52362 int szHdr; /* Size of the header size field at start of record */ 53121 int szHdr; /* Size of the header size field at start of record */ 52363 int avail; /* Number of bytes of available data */ 53122 int avail; /* Number of bytes of available data */ 52364 Mem *pReg; /* PseudoTable input register */ 53123 Mem *pReg; /* PseudoTable input register */ 52365 } am; 53124 } am; 52366 struct OP_Affinity_stack_vars { 53125 struct OP_Affinity_stack_vars { 52367 const char *zAffinity; /* The affinity to be applied */ 53126 const char *zAffinity; /* The affinity to be applied */ 52368 char cAff; /* A single character of affinity */ 53127 char cAff; /* A single character of affinity */ ................................................................................................................................................................................ 52666 char *zTrace; 53425 char *zTrace; 52667 } cm; 53426 } cm; 52668 } u; 53427 } u; 52669 /* End automatically generated code 53428 /* End automatically generated code 52670 ********************************************************************/ 53429 ********************************************************************/ 52671 53430 52672 assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */ 53431 assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */ 52673 assert( db->magic==SQLITE_MAGIC_BUSY ); < 52674 sqlite3VdbeMutexArrayEnter(p); 53432 sqlite3VdbeMutexArrayEnter(p); 52675 if( p->rc==SQLITE_NOMEM ){ 53433 if( p->rc==SQLITE_NOMEM ){ 52676 /* This happens if a malloc() inside a call to sqlite3_column_text() or 53434 /* This happens if a malloc() inside a call to sqlite3_column_text() or 52677 ** sqlite3_column_text16() failed. */ 53435 ** sqlite3_column_text16() failed. */ 52678 goto no_mem; 53436 goto no_mem; 52679 } 53437 } 52680 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY ); 53438 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY ); ................................................................................................................................................................................ 52751 ** sqlite3VdbeExec() or since last time the progress callback was called). 53509 ** sqlite3VdbeExec() or since last time the progress callback was called). 52752 ** If the progress callback returns non-zero, exit the virtual machine with 53510 ** If the progress callback returns non-zero, exit the virtual machine with 52753 ** a return code SQLITE_ABORT. 53511 ** a return code SQLITE_ABORT. 52754 */ 53512 */ 52755 if( checkProgress ){ 53513 if( checkProgress ){ 52756 if( db->nProgressOps==nProgressOps ){ 53514 if( db->nProgressOps==nProgressOps ){ 52757 int prc; 53515 int prc; 52758 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; < 52759 prc =db->xProgress(db->pProgressArg); | 53516 prc = db->xProgress(db->pProgressArg); 52760 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse; < 52761 if( prc!=0 ){ 53517 if( prc!=0 ){ 52762 rc = SQLITE_INTERRUPT; 53518 rc = SQLITE_INTERRUPT; 52763 goto vdbe_error_halt; 53519 goto vdbe_error_halt; 52764 } 53520 } 52765 nProgressOps = 0; 53521 nProgressOps = 0; 52766 } 53522 } 52767 nProgressOps++; 53523 nProgressOps++; ................................................................................................................................................................................ 52955 break; 53711 break; 52956 } 53712 } 52957 53713 52958 p->rc = pOp->p1; 53714 p->rc = pOp->p1; 52959 p->errorAction = (u8)pOp->p2; 53715 p->errorAction = (u8)pOp->p2; 52960 p->pc = pc; 53716 p->pc = pc; 52961 if( pOp->p4.z ){ 53717 if( pOp->p4.z ){ > 53718 assert( p->rc!=SQLITE_OK ); 52962 sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z); 53719 sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z); > 53720 testcase( sqlite3GlobalConfig.xLog!=0 ); > 53721 sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z); > 53722 }else if( p->rc ){ > 53723 testcase( sqlite3GlobalConfig.xLog!=0 ); > 53724 sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql); 52963 } 53725 } 52964 rc = sqlite3VdbeHalt(p); 53726 rc = sqlite3VdbeHalt(p); 52965 assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR ); 53727 assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR ); 52966 if( rc==SQLITE_BUSY ){ 53728 if( rc==SQLITE_BUSY ){ 52967 p->rc = rc = SQLITE_BUSY; 53729 p->rc = rc = SQLITE_BUSY; 52968 }else{ 53730 }else{ 52969 assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT ); 53731 assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT ); ................................................................................................................................................................................ 52989 */ 53751 */ 52990 case OP_Int64: { /* out2-prerelease */ 53752 case OP_Int64: { /* out2-prerelease */ 52991 assert( pOp->p4.pI64!=0 ); 53753 assert( pOp->p4.pI64!=0 ); 52992 pOut->u.i = *pOp->p4.pI64; 53754 pOut->u.i = *pOp->p4.pI64; 52993 break; 53755 break; 52994 } 53756 } 52995 53757 > 53758 #ifndef SQLITE_OMIT_FLOATING_POINT 52996 /* Opcode: Real * P2 * P4 * 53759 /* Opcode: Real * P2 * P4 * 52997 ** 53760 ** 52998 ** P4 is a pointer to a 64-bit floating point value. 53761 ** P4 is a pointer to a 64-bit floating point value. 52999 ** Write that value into register P2. 53762 ** Write that value into register P2. 53000 */ 53763 */ 53001 case OP_Real: { /* same as TK_FLOAT, out2-prerelease */ 53764 case OP_Real: { /* same as TK_FLOAT, out2-prerelease */ 53002 pOut->flags = MEM_Real; 53765 pOut->flags = MEM_Real; 53003 assert( !sqlite3IsNaN(*pOp->p4.pReal) ); 53766 assert( !sqlite3IsNaN(*pOp->p4.pReal) ); 53004 pOut->r = *pOp->p4.pReal; 53767 pOut->r = *pOp->p4.pReal; 53005 break; 53768 break; 53006 } 53769 } > 53770 #endif 53007 53771 53008 /* Opcode: String8 * P2 * P4 * 53772 /* Opcode: String8 * P2 * P4 * 53009 ** 53773 ** 53010 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 53774 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 53011 ** into an OP_String before it is executed for the first time. 53775 ** into an OP_String before it is executed for the first time. 53012 */ 53776 */ 53013 case OP_String8: { /* same as TK_STRING, out2-prerelease */ 53777 case OP_String8: { /* same as TK_STRING, out2-prerelease */ ................................................................................................................................................................................ 53410 u.af.iB = (i64)u.af.rB; 54174 u.af.iB = (i64)u.af.rB; 53411 if( u.af.iA==0 ) goto arithmetic_result_is_null; 54175 if( u.af.iA==0 ) goto arithmetic_result_is_null; 53412 if( u.af.iA==-1 ) u.af.iA = 1; 54176 if( u.af.iA==-1 ) u.af.iA = 1; 53413 u.af.rB = (double)(u.af.iB % u.af.iA); 54177 u.af.rB = (double)(u.af.iB % u.af.iA); 53414 break; 54178 break; 53415 } 54179 } 53416 } 54180 } > 54181 #ifdef SQLITE_OMIT_FLOATING_POINT > 54182 pOut->u.i = u.af.rB; > 54183 MemSetTypeFlag(pOut, MEM_Int); > 54184 #else 53417 if( sqlite3IsNaN(u.af.rB) ){ 54185 if( sqlite3IsNaN(u.af.rB) ){ 53418 goto arithmetic_result_is_null; 54186 goto arithmetic_result_is_null; 53419 } 54187 } 53420 pOut->r = u.af.rB; 54188 pOut->r = u.af.rB; 53421 MemSetTypeFlag(pOut, MEM_Real); 54189 MemSetTypeFlag(pOut, MEM_Real); 53422 if( (u.af.flags & MEM_Real)==0 ){ 54190 if( (u.af.flags & MEM_Real)==0 ){ 53423 sqlite3VdbeIntegerAffinity(pOut); 54191 sqlite3VdbeIntegerAffinity(pOut); 53424 } 54192 } > 54193 #endif 53425 } 54194 } 53426 break; 54195 break; 53427 54196 53428 arithmetic_result_is_null: 54197 arithmetic_result_is_null: 53429 sqlite3VdbeMemSetNull(pOut); 54198 sqlite3VdbeMemSetNull(pOut); 53430 break; 54199 break; 53431 } 54200 } ................................................................................................................................................................................ 53510 u.ag.ctx.isError = 0; 54279 u.ag.ctx.isError = 0; 53511 if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){ 54280 if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){ 53512 assert( pOp>aOp ); 54281 assert( pOp>aOp ); 53513 assert( pOp[-1].p4type==P4_COLLSEQ ); 54282 assert( pOp[-1].p4type==P4_COLLSEQ ); 53514 assert( pOp[-1].opcode==OP_CollSeq ); 54283 assert( pOp[-1].opcode==OP_CollSeq ); 53515 u.ag.ctx.pColl = pOp[-1].p4.pColl; 54284 u.ag.ctx.pColl = pOp[-1].p4.pColl; 53516 } 54285 } 53517 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; < 53518 (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal); 54286 (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal); 53519 if( sqlite3SafetyOn(db) ){ < 53520 sqlite3VdbeMemRelease(&u.ag.ctx.s); < 53521 goto abort_due_to_misuse; < 53522 } < 53523 if( db->mallocFailed ){ 54287 if( db->mallocFailed ){ 53524 /* Even though a malloc() has failed, the implementation of the 54288 /* Even though a malloc() has failed, the implementation of the 53525 ** user function may have called an sqlite3_result_XXX() function 54289 ** user function may have called an sqlite3_result_XXX() function 53526 ** to return a value. The following call releases any resources 54290 ** to return a value. The following call releases any resources 53527 ** associated with such a value. 54291 ** associated with such a value. 53528 ** < 53529 ** Note: Maybe MemRelease() should be called if sqlite3SafetyOn() < 53530 ** fails also (the if(...) statement above). But if people are < 53531 ** misusing sqlite, they have bigger problems than a leaked value. < 53532 */ 54292 */ 53533 sqlite3VdbeMemRelease(&u.ag.ctx.s); 54293 sqlite3VdbeMemRelease(&u.ag.ctx.s); 53534 goto no_mem; 54294 goto no_mem; 53535 } 54295 } 53536 54296 53537 /* If any auxiliary data functions have been called by this user function, 54297 /* If any auxiliary data functions have been called by this user function, 53538 ** immediately call the destructor for any non-static values. 54298 ** immediately call the destructor for any non-static values. ................................................................................................................................................................................ 53649 } 54409 } 53650 }else{ 54410 }else{ 53651 MemSetTypeFlag(pIn1, MEM_Int); 54411 MemSetTypeFlag(pIn1, MEM_Int); 53652 } 54412 } 53653 break; 54413 break; 53654 } 54414 } 53655 54415 > 54416 #ifndef SQLITE_OMIT_FLOATING_POINT 53656 /* Opcode: RealAffinity P1 * * * * 54417 /* Opcode: RealAffinity P1 * * * * 53657 ** 54418 ** 53658 ** If register P1 holds an integer convert it to a real value. 54419 ** If register P1 holds an integer convert it to a real value. 53659 ** 54420 ** 53660 ** This opcode is used when extracting information from a column that 54421 ** This opcode is used when extracting information from a column that 53661 ** has REAL affinity. Such column values may still be stored as 54422 ** has REAL affinity. Such column values may still be stored as 53662 ** integers, for space efficiency, but after extraction we want them 54423 ** integers, for space efficiency, but after extraction we want them ................................................................................................................................................................................ 53665 case OP_RealAffinity: { /* in1 */ 54426 case OP_RealAffinity: { /* in1 */ 53666 pIn1 = &aMem[pOp->p1]; 54427 pIn1 = &aMem[pOp->p1]; 53667 if( pIn1->flags & MEM_Int ){ 54428 if( pIn1->flags & MEM_Int ){ 53668 sqlite3VdbeMemRealify(pIn1); 54429 sqlite3VdbeMemRealify(pIn1); 53669 } 54430 } 53670 break; 54431 break; 53671 } 54432 } > 54433 #endif 53672 54434 53673 #ifndef SQLITE_OMIT_CAST 54435 #ifndef SQLITE_OMIT_CAST 53674 /* Opcode: ToText P1 * * * * 54436 /* Opcode: ToText P1 * * * * 53675 ** 54437 ** 53676 ** Force the value in register P1 to be text. 54438 ** Force the value in register P1 to be text. 53677 ** If the value is numeric, convert it to a string using the 54439 ** If the value is numeric, convert it to a string using the 53678 ** equivalent of printf(). Blob values are unchanged and 54440 ** equivalent of printf(). Blob values are unchanged and ................................................................................................................................................................................ 53748 pIn1 = &aMem[pOp->p1]; 54510 pIn1 = &aMem[pOp->p1]; 53749 if( (pIn1->flags & MEM_Null)==0 ){ 54511 if( (pIn1->flags & MEM_Null)==0 ){ 53750 sqlite3VdbeMemIntegerify(pIn1); 54512 sqlite3VdbeMemIntegerify(pIn1); 53751 } 54513 } 53752 break; 54514 break; 53753 } 54515 } 53754 54516 53755 #ifndef SQLITE_OMIT_CAST | 54517 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) 53756 /* Opcode: ToReal P1 * * * * 54518 /* Opcode: ToReal P1 * * * * 53757 ** 54519 ** 53758 ** Force the value in register P1 to be a floating point number. 54520 ** Force the value in register P1 to be a floating point number. 53759 ** If The value is currently an integer, convert it. 54521 ** If The value is currently an integer, convert it. 53760 ** If the value is text or blob, try to convert it to an integer using the 54522 ** If the value is text or blob, try to convert it to an integer using the 53761 ** equivalent of atoi() and store 0.0 if no such conversion is possible. 54523 ** equivalent of atoi() and store 0.0 if no such conversion is possible. 53762 ** 54524 ** ................................................................................................................................................................................ 53765 case OP_ToReal: { /* same as TK_TO_REAL, in1 */ 54527 case OP_ToReal: { /* same as TK_TO_REAL, in1 */ 53766 pIn1 = &aMem[pOp->p1]; 54528 pIn1 = &aMem[pOp->p1]; 53767 if( (pIn1->flags & MEM_Null)==0 ){ 54529 if( (pIn1->flags & MEM_Null)==0 ){ 53768 sqlite3VdbeMemRealify(pIn1); 54530 sqlite3VdbeMemRealify(pIn1); 53769 } 54531 } 53770 break; 54532 break; 53771 } 54533 } 53772 #endif /* SQLITE_OMIT_CAST */ | 54534 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */ 53773 54535 53774 /* Opcode: Lt P1 P2 P3 P4 P5 54536 /* Opcode: Lt P1 P2 P3 P4 P5 53775 ** 54537 ** 53776 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then 54538 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then 53777 ** jump to address P2. 54539 ** jump to address P2. 53778 ** 54540 ** 53779 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or 54541 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or ................................................................................................................................................................................ 53848 case OP_Lt: /* same as TK_LT, jump, in1, in3 */ 54610 case OP_Lt: /* same as TK_LT, jump, in1, in3 */ 53849 case OP_Le: /* same as TK_LE, jump, in1, in3 */ 54611 case OP_Le: /* same as TK_LE, jump, in1, in3 */ 53850 case OP_Gt: /* same as TK_GT, jump, in1, in3 */ 54612 case OP_Gt: /* same as TK_GT, jump, in1, in3 */ 53851 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */ 54613 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */ 53852 #if 0 /* local variables moved into u.ai */ 54614 #if 0 /* local variables moved into u.ai */ 53853 int res; /* Result of the comparison of pIn1 against pIn3 */ 54615 int res; /* Result of the comparison of pIn1 against pIn3 */ 53854 char affinity; /* Affinity to use for comparison */ 54616 char affinity; /* Affinity to use for comparison */ > 54617 u16 flags1; /* Copy of initial value of pIn1->flags */ > 54618 u16 flags3; /* Copy of initial value of pIn3->flags */ 53855 #endif /* local variables moved into u.ai */ 54619 #endif /* local variables moved into u.ai */ 53856 54620 53857 pIn1 = &aMem[pOp->p1]; 54621 pIn1 = &aMem[pOp->p1]; 53858 pIn3 = &aMem[pOp->p3]; 54622 pIn3 = &aMem[pOp->p3]; > 54623 u.ai.flags1 = pIn1->flags; > 54624 u.ai.flags3 = pIn3->flags; 53859 if( (pIn1->flags | pIn3->flags)&MEM_Null ){ 54625 if( (pIn1->flags | pIn3->flags)&MEM_Null ){ 53860 /* One or both operands are NULL */ 54626 /* One or both operands are NULL */ 53861 if( pOp->p5 & SQLITE_NULLEQ ){ 54627 if( pOp->p5 & SQLITE_NULLEQ ){ 53862 /* If SQLITE_NULLEQ is set (which will only happen if the operator is 54628 /* If SQLITE_NULLEQ is set (which will only happen if the operator is 53863 ** OP_Eq or OP_Ne) then take the jump or not depending on whether 54629 ** OP_Eq or OP_Ne) then take the jump or not depending on whether 53864 ** or not both operands are null. 54630 ** or not both operands are null. 53865 */ 54631 */ ................................................................................................................................................................................ 53906 pOut = &aMem[pOp->p2]; 54672 pOut = &aMem[pOp->p2]; 53907 MemSetTypeFlag(pOut, MEM_Int); 54673 MemSetTypeFlag(pOut, MEM_Int); 53908 pOut->u.i = u.ai.res; 54674 pOut->u.i = u.ai.res; 53909 REGISTER_TRACE(pOp->p2, pOut); 54675 REGISTER_TRACE(pOp->p2, pOut); 53910 }else if( u.ai.res ){ 54676 }else if( u.ai.res ){ 53911 pc = pOp->p2-1; 54677 pc = pOp->p2-1; 53912 } 54678 } > 54679 > 54680 /* Undo any changes made by applyAffinity() to the input registers. */ > 54681 pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ai.flags1&MEM_TypeMask); > 54682 pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ai.flags3&MEM_TypeMask); 53913 break; 54683 break; 53914 } 54684 } 53915 54685 53916 /* Opcode: Permutation * * * P4 * 54686 /* Opcode: Permutation * * * P4 * 53917 ** 54687 ** 53918 ** Set the permutation used by the OP_Compare operator to be the array 54688 ** Set the permutation used by the OP_Compare operator to be the array 53919 ** of integers in P4. 54689 ** of integers in P4. ................................................................................................................................................................................ 54187 int i; /* Loop counter */ 54957 int i; /* Loop counter */ 54188 char *zData; /* Part of the record being decoded */ 54958 char *zData; /* Part of the record being decoded */ 54189 Mem *pDest; /* Where to write the extracted value */ 54959 Mem *pDest; /* Where to write the extracted value */ 54190 Mem sMem; /* For storing the record being decoded */ 54960 Mem sMem; /* For storing the record being decoded */ 54191 u8 *zIdx; /* Index into header */ 54961 u8 *zIdx; /* Index into header */ 54192 u8 *zEndHdr; /* Pointer to first byte after the header */ 54962 u8 *zEndHdr; /* Pointer to first byte after the header */ 54193 u32 offset; /* Offset into the data */ 54963 u32 offset; /* Offset into the data */ 54194 u64 offset64; /* 64-bit offset. 64 bits needed to catch overflow */ | 54964 u32 szField; /* Number of bytes in the content of a field */ 54195 int szHdr; /* Size of the header size field at start of record */ 54965 int szHdr; /* Size of the header size field at start of record */ 54196 int avail; /* Number of bytes of available data */ 54966 int avail; /* Number of bytes of available data */ 54197 Mem *pReg; /* PseudoTable input register */ 54967 Mem *pReg; /* PseudoTable input register */ 54198 #endif /* local variables moved into u.am */ 54968 #endif /* local variables moved into u.am */ 54199 54969 54200 54970 54201 u.am.p1 = pOp->p1; 54971 u.am.p1 = pOp->p1; ................................................................................................................................................................................ 54363 u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr]; 55133 u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr]; 54364 55134 54365 /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[] 55135 /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[] 54366 ** arrays. u.am.aType[u.am.i] will contain the type integer for the u.am.i- 55136 ** arrays. u.am.aType[u.am.i] will contain the type integer for the u.am.i- 54367 ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beg 55137 ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beg 54368 ** of the record to the start of the data for the u.am.i-th column 55138 ** of the record to the start of the data for the u.am.i-th column 54369 */ 55139 */ 54370 u.am.offset64 = u.am.offset; < 54371 for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){ 55140 for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){ 54372 if( u.am.zIdx<u.am.zEndHdr ){ 55141 if( u.am.zIdx<u.am.zEndHdr ){ 54373 u.am.aOffset[u.am.i] = (u32)u.am.offset64; | 55142 u.am.aOffset[u.am.i] = u.am.offset; 54374 u.am.zIdx += getVarint32(u.am.zIdx, u.am.aType[u.am.i]); 55143 u.am.zIdx += getVarint32(u.am.zIdx, u.am.aType[u.am.i]); 54375 u.am.offset64 += sqlite3VdbeSerialTypeLen(u.am.aType[u.am.i]); | 55144 u.am.szField = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.i]); > 55145 u.am.offset += u.am.szField; > 55146 if( u.am.offset<u.am.szField ){ /* True if u.am.offset overflows */ > 55147 u.am.zIdx = &u.am.zEndHdr[1]; /* Forces SQLITE_CORRUPT return below * > 55148 break; > 55149 } 54376 }else{ 55150 }else{ 54377 /* If u.am.i is less that u.am.nField, then there are less fields in thi 55151 /* If u.am.i is less that u.am.nField, then there are less fields in thi 54378 ** record than SetNumColumns indicated there are columns in the 55152 ** record than SetNumColumns indicated there are columns in the 54379 ** table. Set the u.am.offset for any extra columns not present in 55153 ** table. Set the u.am.offset for any extra columns not present in 54380 ** the record to 0. This tells code below to store a NULL 55154 ** the record to 0. This tells code below to store a NULL 54381 ** instead of deserializing a value from the record. 55155 ** instead of deserializing a value from the record. 54382 */ 55156 */ ................................................................................................................................................................................ 54388 55162 54389 /* If we have read more header data than was contained in the header, 55163 /* If we have read more header data than was contained in the header, 54390 ** or if the end of the last field appears to be past the end of the 55164 ** or if the end of the last field appears to be past the end of the 54391 ** record, or if the end of the last field appears to be before the end 55165 ** record, or if the end of the last field appears to be before the end 54392 ** of the record (when all fields present), then we must be dealing 55166 ** of the record (when all fields present), then we must be dealing 54393 ** with a corrupt database. 55167 ** with a corrupt database. 54394 */ 55168 */ 54395 if( (u.am.zIdx > u.am.zEndHdr)|| (u.am.offset64 > u.am.payloadSize) | 55169 if( (u.am.zIdx > u.am.zEndHdr) || (u.am.offset > u.am.payloadSize) 54396 || (u.am.zIdx==u.am.zEndHdr && u.am.offset64!=(u64)u.am.payloadSize) ){ | 55170 || (u.am.zIdx==u.am.zEndHdr && u.am.offset!=u.am.payloadSize) ){ 54397 rc = SQLITE_CORRUPT_BKPT; 55171 rc = SQLITE_CORRUPT_BKPT; 54398 goto op_column_out; 55172 goto op_column_out; 54399 } 55173 } 54400 } 55174 } 54401 55175 54402 /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then 55176 /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then 54403 ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero, 55177 ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero, ................................................................................................................................................................................ 55257 /* Opcode: OpenPseudo P1 P2 P3 * * 56031 /* Opcode: OpenPseudo P1 P2 P3 * * 55258 ** 56032 ** 55259 ** Open a new cursor that points to a fake table that contains a single 56033 ** Open a new cursor that points to a fake table that contains a single 55260 ** row of data. The content of that one row in the content of memory 56034 ** row of data. The content of that one row in the content of memory 55261 ** register P2. In other words, cursor P1 becomes an alias for the 56035 ** register P2. In other words, cursor P1 becomes an alias for the 55262 ** MEM_Blob content contained in register P2. 56036 ** MEM_Blob content contained in register P2. 55263 ** 56037 ** 55264 ** A pseudo-table created by this opcode is used to hold the a single | 56038 ** A pseudo-table created by this opcode is used to hold a single 55265 ** row output from the sorter so that the row can be decomposed into 56039 ** row output from the sorter so that the row can be decomposed into 55266 ** individual columns using the OP_Column opcode. The OP_Column opcode 56040 ** individual columns using the OP_Column opcode. The OP_Column opcode 55267 ** is the only cursor opcode that works with a pseudo-table. 56041 ** is the only cursor opcode that works with a pseudo-table. 55268 ** 56042 ** 55269 ** P3 is the number of fields in the records that will be stored by 56043 ** P3 is the number of fields in the records that will be stored by 55270 ** the pseudo-table. 56044 ** the pseudo-table. 55271 */ 56045 */ ................................................................................................................................................................................ 56209 }else if( u.bi.pC->deferredMoveto ){ 56983 }else if( u.bi.pC->deferredMoveto ){ 56210 u.bi.v = u.bi.pC->movetoTarget; 56984 u.bi.v = u.bi.pC->movetoTarget; 56211 #ifndef SQLITE_OMIT_VIRTUALTABLE 56985 #ifndef SQLITE_OMIT_VIRTUALTABLE 56212 }else if( u.bi.pC->pVtabCursor ){ 56986 }else if( u.bi.pC->pVtabCursor ){ 56213 u.bi.pVtab = u.bi.pC->pVtabCursor->pVtab; 56987 u.bi.pVtab = u.bi.pC->pVtabCursor->pVtab; 56214 u.bi.pModule = u.bi.pVtab->pModule; 56988 u.bi.pModule = u.bi.pVtab->pModule; 56215 assert( u.bi.pModule->xRowid ); 56989 assert( u.bi.pModule->xRowid ); 56216 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; < 56217 rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v); 56990 rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v); 56218 sqlite3DbFree(db, p->zErrMsg); 56991 sqlite3DbFree(db, p->zErrMsg); 56219 p->zErrMsg = u.bi.pVtab->zErrMsg; 56992 p->zErrMsg = u.bi.pVtab->zErrMsg; 56220 u.bi.pVtab->zErrMsg = 0; 56993 u.bi.pVtab->zErrMsg = 0; 56221 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse; < 56222 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 56994 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 56223 }else{ 56995 }else{ 56224 assert( u.bi.pC->pCursor!=0 ); 56996 assert( u.bi.pC->pCursor!=0 ); 56225 rc = sqlite3VdbeCursorMoveto(u.bi.pC); 56997 rc = sqlite3VdbeCursorMoveto(u.bi.pC); 56226 if( rc ) goto abort_due_to_error; 56998 if( rc ) goto abort_due_to_error; 56227 if( u.bi.pC->rowidIsValid ){ 56999 if( u.bi.pC->rowidIsValid ){ 56228 u.bi.v = u.bi.pC->lastRowid; 57000 u.bi.v = u.bi.pC->lastRowid; ................................................................................................................................................................................ 56769 sqlite3BtreeEnterAll(db); 57541 sqlite3BtreeEnterAll(db); 56770 if( pOp->p2 || DbHasProperty(db, u.bu.iDb, DB_SchemaLoaded) ){ 57542 if( pOp->p2 || DbHasProperty(db, u.bu.iDb, DB_SchemaLoaded) ){ 56771 u.bu.zMaster = SCHEMA_TABLE(u.bu.iDb); 57543 u.bu.zMaster = SCHEMA_TABLE(u.bu.iDb); 56772 u.bu.initData.db = db; 57544 u.bu.initData.db = db; 56773 u.bu.initData.iDb = pOp->p1; 57545 u.bu.initData.iDb = pOp->p1; 56774 u.bu.initData.pzErrMsg = &p->zErrMsg; 57546 u.bu.initData.pzErrMsg = &p->zErrMsg; 56775 u.bu.zSql = sqlite3MPrintf(db, 57547 u.bu.zSql = sqlite3MPrintf(db, 56776 "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s", | 57548 "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid", 56777 db->aDb[u.bu.iDb].zName, u.bu.zMaster, pOp->p4.z); 57549 db->aDb[u.bu.iDb].zName, u.bu.zMaster, pOp->p4.z); 56778 if( u.bu.zSql==0 ){ 57550 if( u.bu.zSql==0 ){ 56779 rc = SQLITE_NOMEM; 57551 rc = SQLITE_NOMEM; 56780 }else{ 57552 }else{ 56781 (void)sqlite3SafetyOff(db); < 56782 assert( db->init.busy==0 ); 57553 assert( db->init.busy==0 ); 56783 db->init.busy = 1; 57554 db->init.busy = 1; 56784 u.bu.initData.rc = SQLITE_OK; 57555 u.bu.initData.rc = SQLITE_OK; 56785 assert( !db->mallocFailed ); 57556 assert( !db->mallocFailed ); 56786 rc = sqlite3_exec(db, u.bu.zSql, sqlite3InitCallback, &u.bu.initData, 0); 57557 rc = sqlite3_exec(db, u.bu.zSql, sqlite3InitCallback, &u.bu.initData, 0); 56787 if( rc==SQLITE_OK ) rc = u.bu.initData.rc; 57558 if( rc==SQLITE_OK ) rc = u.bu.initData.rc; 56788 sqlite3DbFree(db, u.bu.zSql); 57559 sqlite3DbFree(db, u.bu.zSql); 56789 db->init.busy = 0; 57560 db->init.busy = 0; 56790 (void)sqlite3SafetyOn(db); < 56791 } 57561 } 56792 } 57562 } 56793 sqlite3BtreeLeaveAll(db); 57563 sqlite3BtreeLeaveAll(db); 56794 if( rc==SQLITE_NOMEM ){ 57564 if( rc==SQLITE_NOMEM ){ 56795 goto no_mem; 57565 goto no_mem; 56796 } 57566 } 56797 break; 57567 break; ................................................................................................................................................................................ 57369 /* Opcode: Vacuum * * * * * 58139 /* Opcode: Vacuum * * * * * 57370 ** 58140 ** 57371 ** Vacuum the entire database. This opcode will cause other virtual 58141 ** Vacuum the entire database. This opcode will cause other virtual 57372 ** machines to be created and run. It may not be called from within 58142 ** machines to be created and run. It may not be called from within 57373 ** a transaction. 58143 ** a transaction. 57374 */ 58144 */ 57375 case OP_Vacuum: { 58145 case OP_Vacuum: { 57376 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; < 57377 rc = sqlite3RunVacuum(&p->zErrMsg, db); 58146 rc = sqlite3RunVacuum(&p->zErrMsg, db); 57378 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse; < 57379 break; 58147 break; 57380 } 58148 } 57381 #endif 58149 #endif 57382 58150 57383 #if !defined(SQLITE_OMIT_AUTOVACUUM) 58151 #if !defined(SQLITE_OMIT_AUTOVACUUM) 57384 /* Opcode: IncrVacuum P1 P2 * * * 58152 /* Opcode: IncrVacuum P1 P2 * * * 57385 ** 58153 ** ................................................................................................................................................................................ 57521 #endif /* local variables moved into u.cf */ 58289 #endif /* local variables moved into u.cf */ 57522 58290 57523 u.cf.pCur = 0; 58291 u.cf.pCur = 0; 57524 u.cf.pVtabCursor = 0; 58292 u.cf.pVtabCursor = 0; 57525 u.cf.pVtab = pOp->p4.pVtab->pVtab; 58293 u.cf.pVtab = pOp->p4.pVtab->pVtab; 57526 u.cf.pModule = (sqlite3_module *)u.cf.pVtab->pModule; 58294 u.cf.pModule = (sqlite3_module *)u.cf.pVtab->pModule; 57527 assert(u.cf.pVtab && u.cf.pModule); 58295 assert(u.cf.pVtab && u.cf.pModule); 57528 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; < 57529 rc = u.cf.pModule->xOpen(u.cf.pVtab, &u.cf.pVtabCursor); 58296 rc = u.cf.pModule->xOpen(u.cf.pVtab, &u.cf.pVtabCursor); 57530 sqlite3DbFree(db, p->zErrMsg); 58297 sqlite3DbFree(db, p->zErrMsg); 57531 p->zErrMsg = u.cf.pVtab->zErrMsg; 58298 p->zErrMsg = u.cf.pVtab->zErrMsg; 57532 u.cf.pVtab->zErrMsg = 0; 58299 u.cf.pVtab->zErrMsg = 0; 57533 if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse; < 57534 if( SQLITE_OK==rc ){ 58300 if( SQLITE_OK==rc ){ 57535 /* Initialize sqlite3_vtab_cursor base class */ 58301 /* Initialize sqlite3_vtab_cursor base class */ 57536 u.cf.pVtabCursor->pVtab = u.cf.pVtab; 58302 u.cf.pVtabCursor->pVtab = u.cf.pVtab; 57537 58303 57538 /* Initialise vdbe cursor object */ 58304 /* Initialise vdbe cursor object */ 57539 u.cf.pCur = allocateCursor(p, pOp->p1, 0, -1, 0); 58305 u.cf.pCur = allocateCursor(p, pOp->p1, 0, -1, 0); 57540 if( u.cf.pCur ){ 58306 if( u.cf.pCur ){ ................................................................................................................................................................................ 57602 u.cg.res = 0; 58368 u.cg.res = 0; 57603 u.cg.apArg = p->apArg; 58369 u.cg.apArg = p->apArg; 57604 for(u.cg.i = 0; u.cg.i<u.cg.nArg; u.cg.i++){ 58370 for(u.cg.i = 0; u.cg.i<u.cg.nArg; u.cg.i++){ 57605 u.cg.apArg[u.cg.i] = &u.cg.pArgc[u.cg.i+1]; 58371 u.cg.apArg[u.cg.i] = &u.cg.pArgc[u.cg.i+1]; 57606 sqlite3VdbeMemStoreType(u.cg.apArg[u.cg.i]); 58372 sqlite3VdbeMemStoreType(u.cg.apArg[u.cg.i]); 57607 } 58373 } 57608 58374 57609 if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; < 57610 p->inVtabMethod = 1; 58375 p->inVtabMethod = 1; 57611 rc = u.cg.pModule->xFilter(u.cg.pVtabCursor, u.cg.iQuery, pOp->p4.z, u.cg.nA 58376 rc = u.cg.pModule->xFilter(u.cg.pVtabCursor, u.cg.iQuery, pOp->p4.z, u.cg.nA 57612 p->inVtabMethod = 0; 58377 p->inVtabMethod = 0; 57613 sqlite3DbFree(db, p->zErrMsg); 58378 sqlite3DbFree(db, p->zErrMsg); 57614 p->zErrMsg = u.cg.pVtab->zErrMsg; 58379 p->zErrMsg = u.cg.pVtab->zErrMsg; 57615 u.cg.pVtab->zErrMsg = 0; 58380 u.cg.pVtab->zErrMsg = 0; 57616 if( rc==SQLITE_OK ){ 58381 if( rc==SQLITE_OK ){ 57617 u.cg