Back to index

lightning-sunbird  0.9+nobinonly
util.c
Go to the documentation of this file.
00001 /*
00002 ** 2001 September 15
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 *************************************************************************
00012 ** Utility functions used throughout sqlite.
00013 **
00014 ** This file contains functions for allocating memory, comparing
00015 ** strings, and stuff like that.
00016 **
00017 ** $Id: util.c,v 1.189 2006/04/08 19:14:53 drh Exp $
00018 */
00019 #include "sqliteInt.h"
00020 #include "os.h"
00021 #include <stdarg.h>
00022 #include <ctype.h>
00023 
00024 /*
00025 ** MALLOC WRAPPER ARCHITECTURE
00026 **
00027 ** The sqlite code accesses dynamic memory allocation/deallocation by invoking
00028 ** the following six APIs (which may be implemented as macros).
00029 **
00030 **     sqlite3Malloc()
00031 **     sqlite3MallocRaw()
00032 **     sqlite3Realloc()
00033 **     sqlite3ReallocOrFree()
00034 **     sqlite3Free()
00035 **     sqlite3AllocSize()
00036 **
00037 ** The function sqlite3FreeX performs the same task as sqlite3Free and is
00038 ** guaranteed to be a real function. The same holds for sqlite3MallocX
00039 **
00040 ** The above APIs are implemented in terms of the functions provided in the
00041 ** operating-system interface. The OS interface is never accessed directly
00042 ** by code outside of this file.
00043 **
00044 **     sqlite3OsMalloc()
00045 **     sqlite3OsRealloc()
00046 **     sqlite3OsFree()
00047 **     sqlite3OsAllocationSize()
00048 **
00049 ** Functions sqlite3MallocRaw() and sqlite3Realloc() may invoke 
00050 ** sqlite3_release_memory() if a call to sqlite3OsMalloc() or
00051 ** sqlite3OsRealloc() fails (or if the soft-heap-limit for the thread is
00052 ** exceeded). Function sqlite3Malloc() usually invokes
00053 ** sqlite3MallocRaw().
00054 **
00055 ** MALLOC TEST WRAPPER ARCHITECTURE
00056 **
00057 ** The test wrapper provides extra test facilities to ensure the library 
00058 ** does not leak memory and handles the failure of the underlying OS level
00059 ** allocation system correctly. It is only present if the library is 
00060 ** compiled with the SQLITE_MEMDEBUG macro set.
00061 **
00062 **     * Guardposts to detect overwrites.
00063 **     * Ability to cause a specific Malloc() or Realloc() to fail.
00064 **     * Audit outstanding memory allocations (i.e check for leaks).
00065 */
00066 
00067 #define MAX(x,y) ((x)>(y)?(x):(y))
00068 
00069 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) && !defined(SQLITE_OMIT_DISKIO)
00070 /*
00071 ** Set the soft heap-size limit for the current thread. Passing a negative
00072 ** value indicates no limit.
00073 */
00074 void sqlite3_soft_heap_limit(int n){
00075   ThreadData *pTd = sqlite3ThreadData();
00076   if( pTd ){
00077     pTd->nSoftHeapLimit = n;
00078   }
00079   sqlite3ReleaseThreadData();
00080 }
00081 
00082 /*
00083 ** Release memory held by SQLite instances created by the current thread.
00084 */
00085 int sqlite3_release_memory(int n){
00086   return sqlite3pager_release_memory(n);
00087 }
00088 #else
00089 /* If SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined, then define a version
00090 ** of sqlite3_release_memory() to be used by other code in this file.
00091 ** This is done for no better reason than to reduce the number of 
00092 ** pre-processor #ifndef statements.
00093 */
00094 #define sqlite3_release_memory(x) 0    /* 0 == no memory freed */
00095 #endif
00096 
00097 #ifdef SQLITE_MEMDEBUG
00098 /*--------------------------------------------------------------------------
00099 ** Begin code for memory allocation system test layer.
00100 **
00101 ** Memory debugging is turned on by defining the SQLITE_MEMDEBUG macro.
00102 **
00103 ** SQLITE_MEMDEBUG==1    -> Fence-posting only (thread safe) 
00104 ** SQLITE_MEMDEBUG==2    -> Fence-posting + linked list of allocations (not ts)
00105 ** SQLITE_MEMDEBUG==3    -> Above + backtraces (not thread safe, req. glibc)
00106 */
00107 
00108 /* Figure out whether or not to store backtrace() information for each malloc.
00109 ** The backtrace() function is only used if SQLITE_MEMDEBUG is set to 2 or 
00110 ** greater and glibc is in use. If we don't want to use backtrace(), then just
00111 ** define it as an empty macro and set the amount of space reserved to 0.
00112 */
00113 #if defined(__GLIBC__) && SQLITE_MEMDEBUG>2
00114   extern int backtrace(void **, int);
00115   #define TESTALLOC_STACKSIZE 128
00116   #define TESTALLOC_STACKFRAMES ((TESTALLOC_STACKSIZE-8)/sizeof(void*))
00117 #else
00118   #define backtrace(x, y)
00119   #define TESTALLOC_STACKSIZE 0
00120   #define TESTALLOC_STACKFRAMES 0
00121 #endif
00122 
00123 /*
00124 ** Number of 32-bit guard words.  This should probably be a multiple of
00125 ** 2 since on 64-bit machines we want the value returned by sqliteMalloc()
00126 ** to be 8-byte aligned.
00127 */
00128 #ifndef TESTALLOC_NGUARD
00129 # define TESTALLOC_NGUARD 2
00130 #endif
00131 
00132 /*
00133 ** Size reserved for storing file-name along with each malloc()ed blob.
00134 */
00135 #define TESTALLOC_FILESIZE 64
00136 
00137 /*
00138 ** Size reserved for storing the user string. Each time a Malloc() or Realloc()
00139 ** call succeeds, up to TESTALLOC_USERSIZE bytes of the string pointed to by
00140 ** sqlite3_malloc_id are stored along with the other test system metadata.
00141 */
00142 #define TESTALLOC_USERSIZE 64
00143 const char *sqlite3_malloc_id = 0;
00144 
00145 /*
00146 ** Blocks used by the test layer have the following format:
00147 **
00148 **        <sizeof(void *) pNext pointer>
00149 **        <sizeof(void *) pPrev pointer>
00150 **        <TESTALLOC_NGUARD 32-bit guard words>
00151 **            <The application level allocation>
00152 **        <TESTALLOC_NGUARD 32-bit guard words>
00153 **        <32-bit line number>
00154 **        <TESTALLOC_FILESIZE bytes containing null-terminated file name>
00155 **        <TESTALLOC_STACKSIZE bytes of backtrace() output>
00156 */ 
00157 
00158 #define TESTALLOC_OFFSET_GUARD1(p)    (sizeof(void *) * 2)
00159 #define TESTALLOC_OFFSET_DATA(p) ( \
00160   TESTALLOC_OFFSET_GUARD1(p) + sizeof(u32) * TESTALLOC_NGUARD \
00161 )
00162 #define TESTALLOC_OFFSET_GUARD2(p) ( \
00163   TESTALLOC_OFFSET_DATA(p) + sqlite3OsAllocationSize(p) - TESTALLOC_OVERHEAD \
00164 )
00165 #define TESTALLOC_OFFSET_LINENUMBER(p) ( \
00166   TESTALLOC_OFFSET_GUARD2(p) + sizeof(u32) * TESTALLOC_NGUARD \
00167 )
00168 #define TESTALLOC_OFFSET_FILENAME(p) ( \
00169   TESTALLOC_OFFSET_LINENUMBER(p) + sizeof(u32) \
00170 )
00171 #define TESTALLOC_OFFSET_USER(p) ( \
00172   TESTALLOC_OFFSET_FILENAME(p) + TESTALLOC_FILESIZE \
00173 )
00174 #define TESTALLOC_OFFSET_STACK(p) ( \
00175   TESTALLOC_OFFSET_USER(p) + TESTALLOC_USERSIZE + 8 - \
00176   (TESTALLOC_OFFSET_USER(p) % 8) \
00177 )
00178 
00179 #define TESTALLOC_OVERHEAD ( \
00180   sizeof(void *)*2 +                   /* pPrev and pNext pointers */   \
00181   TESTALLOC_NGUARD*sizeof(u32)*2 +              /* Guard words */       \
00182   sizeof(u32) + TESTALLOC_FILESIZE +   /* File and line number */       \
00183   TESTALLOC_USERSIZE +                 /* User string */                \
00184   TESTALLOC_STACKSIZE                  /* backtrace() stack */          \
00185 )
00186 
00187 
00188 /*
00189 ** For keeping track of the number of mallocs and frees.   This
00190 ** is used to check for memory leaks.  The iMallocFail and iMallocReset
00191 ** values are used to simulate malloc() failures during testing in 
00192 ** order to verify that the library correctly handles an out-of-memory
00193 ** condition.
00194 */
00195 int sqlite3_nMalloc;         /* Number of sqliteMalloc() calls */
00196 int sqlite3_nFree;           /* Number of sqliteFree() calls */
00197 int sqlite3_memUsed;         /* TODO Total memory obtained from malloc */
00198 int sqlite3_memMax;          /* TODO Mem usage high-water mark */
00199 int sqlite3_iMallocFail;     /* Fail sqliteMalloc() after this many calls */
00200 int sqlite3_iMallocReset = -1; /* When iMallocFail reaches 0, set to this */
00201 
00202 void *sqlite3_pFirst = 0;         /* Pointer to linked list of allocations */
00203 int sqlite3_nMaxAlloc = 0;        /* High water mark of ThreadData.nAlloc */
00204 int sqlite3_mallocDisallowed = 0; /* assert() in sqlite3Malloc() if set */
00205 int sqlite3_isFail = 0;           /* True if all malloc calls should fail */
00206 const char *sqlite3_zFile = 0;    /* Filename to associate debug info with */
00207 int sqlite3_iLine = 0;            /* Line number for debug info */
00208 
00209 /*
00210 ** Check for a simulated memory allocation failure.  Return true if
00211 ** the failure should be simulated.  Return false to proceed as normal.
00212 */
00213 int sqlite3TestMallocFail(){
00214   if( sqlite3_isFail ){
00215     return 1;
00216   }
00217   if( sqlite3_iMallocFail>=0 ){
00218     sqlite3_iMallocFail--;
00219     if( sqlite3_iMallocFail==0 ){
00220       sqlite3_iMallocFail = sqlite3_iMallocReset;
00221       sqlite3_isFail = 1;
00222       return 1;
00223     }
00224   }
00225   return 0;
00226 }
00227 
00228 /*
00229 ** The argument is a pointer returned by sqlite3OsMalloc() or xRealloc().
00230 ** assert() that the first and last (TESTALLOC_NGUARD*4) bytes are set to the
00231 ** values set by the applyGuards() function.
00232 */
00233 static void checkGuards(u32 *p)
00234 {
00235   int i;
00236   char *zAlloc = (char *)p;
00237   char *z;
00238 
00239   /* First set of guard words */
00240   z = &zAlloc[TESTALLOC_OFFSET_GUARD1(p)];
00241   for(i=0; i<TESTALLOC_NGUARD; i++){
00242     assert(((u32 *)z)[i]==0xdead1122);
00243   }
00244 
00245   /* Second set of guard words */
00246   z = &zAlloc[TESTALLOC_OFFSET_GUARD2(p)];
00247   for(i=0; i<TESTALLOC_NGUARD; i++){
00248     u32 guard = 0;
00249     memcpy(&guard, &z[i*sizeof(u32)], sizeof(u32));
00250     assert(guard==0xdead3344);
00251   }
00252 }
00253 
00254 /*
00255 ** The argument is a pointer returned by sqlite3OsMalloc() or Realloc(). The
00256 ** first and last (TESTALLOC_NGUARD*4) bytes are set to known values for use as 
00257 ** guard-posts.
00258 */
00259 static void applyGuards(u32 *p)
00260 {
00261   int i;
00262   char *z;
00263   char *zAlloc = (char *)p;
00264 
00265   /* First set of guard words */
00266   z = &zAlloc[TESTALLOC_OFFSET_GUARD1(p)];
00267   for(i=0; i<TESTALLOC_NGUARD; i++){
00268     ((u32 *)z)[i] = 0xdead1122;
00269   }
00270 
00271   /* Second set of guard words */
00272   z = &zAlloc[TESTALLOC_OFFSET_GUARD2(p)];
00273   for(i=0; i<TESTALLOC_NGUARD; i++){
00274     static const int guard = 0xdead3344;
00275     memcpy(&z[i*sizeof(u32)], &guard, sizeof(u32));
00276   }
00277 
00278   /* Line number */
00279   z = &((char *)z)[TESTALLOC_NGUARD*sizeof(u32)];             /* Guard words */
00280   z = &zAlloc[TESTALLOC_OFFSET_LINENUMBER(p)];
00281   memcpy(z, &sqlite3_iLine, sizeof(u32));
00282 
00283   /* File name */
00284   z = &zAlloc[TESTALLOC_OFFSET_FILENAME(p)];
00285   strncpy(z, sqlite3_zFile, TESTALLOC_FILESIZE);
00286   z[TESTALLOC_FILESIZE - 1] = '\0';
00287 
00288   /* User string */
00289   z = &zAlloc[TESTALLOC_OFFSET_USER(p)];
00290   z[0] = 0;
00291   if( sqlite3_malloc_id ){
00292     strncpy(z, sqlite3_malloc_id, TESTALLOC_USERSIZE);
00293     z[TESTALLOC_USERSIZE-1] = 0;
00294   }
00295 
00296   /* backtrace() stack */
00297   z = &zAlloc[TESTALLOC_OFFSET_STACK(p)];
00298   backtrace((void **)z, TESTALLOC_STACKFRAMES);
00299 
00300   /* Sanity check to make sure checkGuards() is working */
00301   checkGuards(p);
00302 }
00303 
00304 /*
00305 ** The argument is a malloc()ed pointer as returned by the test-wrapper.
00306 ** Return a pointer to the Os level allocation.
00307 */
00308 static void *getOsPointer(void *p)
00309 {
00310   char *z = (char *)p;
00311   return (void *)(&z[-1 * TESTALLOC_OFFSET_DATA(p)]);
00312 }
00313 
00314 
00315 #if SQLITE_MEMDEBUG>1
00316 /*
00317 ** The argument points to an Os level allocation. Link it into the threads list
00318 ** of allocations.
00319 */
00320 static void linkAlloc(void *p){
00321   void **pp = (void **)p;
00322   pp[0] = 0;
00323   pp[1] = sqlite3_pFirst;
00324   if( sqlite3_pFirst ){
00325     ((void **)sqlite3_pFirst)[0] = p;
00326   }
00327   sqlite3_pFirst = p;
00328 }
00329 
00330 /*
00331 ** The argument points to an Os level allocation. Unlinke it from the threads
00332 ** list of allocations.
00333 */
00334 static void unlinkAlloc(void *p)
00335 {
00336   void **pp = (void **)p;
00337   if( p==sqlite3_pFirst ){
00338     assert(!pp[0]);
00339     assert(!pp[1] || ((void **)(pp[1]))[0]==p);
00340     sqlite3_pFirst = pp[1];
00341     if( sqlite3_pFirst ){
00342       ((void **)sqlite3_pFirst)[0] = 0;
00343     }
00344   }else{
00345     void **pprev = pp[0];
00346     void **pnext = pp[1];
00347     assert(pprev);
00348     assert(pprev[1]==p);
00349     pprev[1] = (void *)pnext;
00350     if( pnext ){
00351       assert(pnext[0]==p);
00352       pnext[0] = (void *)pprev;
00353     }
00354   }
00355 }
00356 
00357 /*
00358 ** Pointer p is a pointer to an OS level allocation that has just been
00359 ** realloc()ed. Set the list pointers that point to this entry to it's new
00360 ** location.
00361 */
00362 static void relinkAlloc(void *p)
00363 {
00364   void **pp = (void **)p;
00365   if( pp[0] ){
00366     ((void **)(pp[0]))[1] = p;
00367   }else{
00368     sqlite3_pFirst = p;
00369   }
00370   if( pp[1] ){
00371     ((void **)(pp[1]))[0] = p;
00372   }
00373 }
00374 #else
00375 #define linkAlloc(x)
00376 #define relinkAlloc(x)
00377 #define unlinkAlloc(x)
00378 #endif
00379 
00380 /*
00381 ** This function sets the result of the Tcl interpreter passed as an argument
00382 ** to a list containing an entry for each currently outstanding call made to 
00383 ** sqliteMalloc and friends by the current thread. Each list entry is itself a
00384 ** list, consisting of the following (in order):
00385 **
00386 **     * The number of bytes allocated
00387 **     * The __FILE__ macro at the time of the sqliteMalloc() call.
00388 **     * The __LINE__ macro ...
00389 **     * The value of the sqlite3_malloc_id variable ...
00390 **     * The output of backtrace() (if available) ...
00391 **
00392 ** Todo: We could have a version of this function that outputs to stdout, 
00393 ** to debug memory leaks when Tcl is not available.
00394 */
00395 #if defined(TCLSH) && defined(SQLITE_DEBUG) && SQLITE_MEMDEBUG>1
00396 #include <tcl.h>
00397 int sqlite3OutstandingMallocs(Tcl_Interp *interp){
00398   void *p;
00399   Tcl_Obj *pRes = Tcl_NewObj();
00400   Tcl_IncrRefCount(pRes);
00401 
00402 
00403   for(p=sqlite3_pFirst; p; p=((void **)p)[1]){
00404     Tcl_Obj *pEntry = Tcl_NewObj();
00405     Tcl_Obj *pStack = Tcl_NewObj();
00406     char *z;
00407     u32 iLine;
00408     int nBytes = sqlite3OsAllocationSize(p) - TESTALLOC_OVERHEAD;
00409     char *zAlloc = (char *)p;
00410     int i;
00411 
00412     Tcl_ListObjAppendElement(0, pEntry, Tcl_NewIntObj(nBytes));
00413 
00414     z = &zAlloc[TESTALLOC_OFFSET_FILENAME(p)];
00415     Tcl_ListObjAppendElement(0, pEntry, Tcl_NewStringObj(z, -1));
00416 
00417     z = &zAlloc[TESTALLOC_OFFSET_LINENUMBER(p)];
00418     memcpy(&iLine, z, sizeof(u32));
00419     Tcl_ListObjAppendElement(0, pEntry, Tcl_NewIntObj(iLine));
00420 
00421     z = &zAlloc[TESTALLOC_OFFSET_USER(p)];
00422     Tcl_ListObjAppendElement(0, pEntry, Tcl_NewStringObj(z, -1));
00423 
00424     z = &zAlloc[TESTALLOC_OFFSET_STACK(p)];
00425     for(i=0; i<TESTALLOC_STACKFRAMES; i++){
00426       char zHex[128];
00427       sprintf(zHex, "%p", ((void **)z)[i]);
00428       Tcl_ListObjAppendElement(0, pStack, Tcl_NewStringObj(zHex, -1));
00429     }
00430 
00431     Tcl_ListObjAppendElement(0, pEntry, pStack);
00432     Tcl_ListObjAppendElement(0, pRes, pEntry);
00433   }
00434 
00435   Tcl_ResetResult(interp);
00436   Tcl_SetObjResult(interp, pRes);
00437   Tcl_DecrRefCount(pRes);
00438   return TCL_OK;
00439 }
00440 #endif
00441 
00442 /*
00443 ** This is the test layer's wrapper around sqlite3OsMalloc().
00444 */
00445 static void * OSMALLOC(int n){
00446   sqlite3OsEnterMutex();
00447 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
00448   sqlite3_nMaxAlloc = 
00449       MAX(sqlite3_nMaxAlloc, sqlite3ThreadDataReadOnly()->nAlloc);
00450 #endif
00451   assert( !sqlite3_mallocDisallowed );
00452   if( !sqlite3TestMallocFail() ){
00453     u32 *p;
00454     p = (u32 *)sqlite3OsMalloc(n + TESTALLOC_OVERHEAD);
00455     assert(p);
00456     sqlite3_nMalloc++;
00457     applyGuards(p);
00458     linkAlloc(p);
00459     sqlite3OsLeaveMutex();
00460     return (void *)(&p[TESTALLOC_NGUARD + 2*sizeof(void *)/sizeof(u32)]);
00461   }
00462   sqlite3OsLeaveMutex();
00463   return 0;
00464 }
00465 
00466 static int OSSIZEOF(void *p){
00467   if( p ){
00468     u32 *pOs = (u32 *)getOsPointer(p);
00469     return sqlite3OsAllocationSize(pOs) - TESTALLOC_OVERHEAD;
00470   }
00471   return 0;
00472 }
00473 
00474 /*
00475 ** This is the test layer's wrapper around sqlite3OsFree(). The argument is a
00476 ** pointer to the space allocated for the application to use.
00477 */
00478 static void OSFREE(void *pFree){
00479   u32 *p;         /* Pointer to the OS-layer allocation */
00480   sqlite3OsEnterMutex();
00481   p = (u32 *)getOsPointer(pFree);
00482   checkGuards(p);
00483   unlinkAlloc(p);
00484   memset(pFree, 0x55, OSSIZEOF(pFree));
00485   sqlite3OsFree(p);
00486   sqlite3_nFree++;
00487   sqlite3OsLeaveMutex();
00488 }
00489 
00490 /*
00491 ** This is the test layer's wrapper around sqlite3OsRealloc().
00492 */
00493 static void * OSREALLOC(void *pRealloc, int n){
00494 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
00495   sqlite3_nMaxAlloc = 
00496       MAX(sqlite3_nMaxAlloc, sqlite3ThreadDataReadOnly()->nAlloc);
00497 #endif
00498   assert( !sqlite3_mallocDisallowed );
00499   if( !sqlite3TestMallocFail() ){
00500     u32 *p = (u32 *)getOsPointer(pRealloc);
00501     checkGuards(p);
00502     p = sqlite3OsRealloc(p, n + TESTALLOC_OVERHEAD);
00503     applyGuards(p);
00504     relinkAlloc(p);
00505     return (void *)(&p[TESTALLOC_NGUARD + 2*sizeof(void *)/sizeof(u32)]);
00506   }
00507   return 0;
00508 }
00509 
00510 static void OSMALLOC_FAILED(){
00511   sqlite3_isFail = 0;
00512 }
00513 
00514 #else
00515 /* Define macros to call the sqlite3OsXXX interface directly if 
00516 ** the SQLITE_MEMDEBUG macro is not defined.
00517 */
00518 #define OSMALLOC(x)        sqlite3OsMalloc(x)
00519 #define OSREALLOC(x,y)     sqlite3OsRealloc(x,y)
00520 #define OSFREE(x)          sqlite3OsFree(x)
00521 #define OSSIZEOF(x)        sqlite3OsAllocationSize(x)
00522 #define OSMALLOC_FAILED()
00523 
00524 #endif  /* SQLITE_MEMDEBUG */
00525 /*
00526 ** End code for memory allocation system test layer.
00527 **--------------------------------------------------------------------------*/
00528 
00529 /*
00530 ** This routine is called when we are about to allocate n additional bytes
00531 ** of memory.  If the new allocation will put is over the soft allocation
00532 ** limit, then invoke sqlite3_release_memory() to try to release some
00533 ** memory before continuing with the allocation.
00534 **
00535 ** This routine also makes sure that the thread-specific-data (TSD) has
00536 ** be allocated.  If it has not and can not be allocated, then return
00537 ** false.  The updateMemoryUsedCount() routine below will deallocate
00538 ** the TSD if it ought to be.
00539 **
00540 ** If SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined, this routine is
00541 ** a no-op
00542 */ 
00543 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
00544 static int enforceSoftLimit(int n){
00545   ThreadData *pTsd = sqlite3ThreadData();
00546   if( pTsd==0 ){
00547     return 0;
00548   }
00549   assert( pTsd->nAlloc>=0 );
00550   if( n>0 && pTsd->nSoftHeapLimit>0 ){
00551     while( pTsd->nAlloc+n>pTsd->nSoftHeapLimit && sqlite3_release_memory(n) ){}
00552   }
00553   return 1;
00554 }
00555 #else
00556 # define enforceSoftLimit(X)  1
00557 #endif
00558 
00559 /*
00560 ** Update the count of total outstanding memory that is held in
00561 ** thread-specific-data (TSD).  If after this update the TSD is
00562 ** no longer being used, then deallocate it.
00563 **
00564 ** If SQLITE_ENABLE_MEMORY_MANAGEMENT is not defined, this routine is
00565 ** a no-op
00566 */
00567 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
00568 static void updateMemoryUsedCount(int n){
00569   ThreadData *pTsd = sqlite3ThreadData();
00570   if( pTsd ){
00571     pTsd->nAlloc += n;
00572     assert( pTsd->nAlloc>=0 );
00573     if( pTsd->nAlloc==0 && pTsd->nSoftHeapLimit==0 ){
00574       sqlite3ReleaseThreadData();
00575     }
00576   }
00577 }
00578 #else
00579 #define updateMemoryUsedCount(x)  /* no-op */
00580 #endif
00581 
00582 /*
00583 ** Allocate and return N bytes of uninitialised memory by calling
00584 ** sqlite3OsMalloc(). If the Malloc() call fails, attempt to free memory 
00585 ** by calling sqlite3_release_memory().
00586 */
00587 void *sqlite3MallocRaw(int n, int doMemManage){
00588   void *p = 0;
00589   if( n>0 && !sqlite3MallocFailed() && (!doMemManage || enforceSoftLimit(n)) ){
00590     while( (p = OSMALLOC(n))==0 && sqlite3_release_memory(n) ){}
00591     if( !p ){
00592       sqlite3FailedMalloc();
00593       OSMALLOC_FAILED();
00594     }else if( doMemManage ){
00595       updateMemoryUsedCount(OSSIZEOF(p));
00596     }
00597   }
00598   return p;
00599 }
00600 
00601 /*
00602 ** Resize the allocation at p to n bytes by calling sqlite3OsRealloc(). The
00603 ** pointer to the new allocation is returned.  If the Realloc() call fails,
00604 ** attempt to free memory by calling sqlite3_release_memory().
00605 */
00606 void *sqlite3Realloc(void *p, int n){
00607   if( sqlite3MallocFailed() ){
00608     return 0;
00609   }
00610 
00611   if( !p ){
00612     return sqlite3Malloc(n, 1);
00613   }else{
00614     void *np = 0;
00615 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
00616     int origSize = OSSIZEOF(p);
00617 #endif
00618     if( enforceSoftLimit(n - origSize) ){
00619       while( (np = OSREALLOC(p, n))==0 && sqlite3_release_memory(n) ){}
00620       if( !np ){
00621         sqlite3FailedMalloc();
00622         OSMALLOC_FAILED();
00623       }else{
00624         updateMemoryUsedCount(OSSIZEOF(np) - origSize);
00625       }
00626     }
00627     return np;
00628   }
00629 }
00630 
00631 /*
00632 ** Free the memory pointed to by p. p must be either a NULL pointer or a 
00633 ** value returned by a previous call to sqlite3Malloc() or sqlite3Realloc().
00634 */
00635 void sqlite3FreeX(void *p){
00636   if( p ){
00637     updateMemoryUsedCount(0 - OSSIZEOF(p));
00638     OSFREE(p);
00639   }
00640 }
00641 
00642 /*
00643 ** A version of sqliteMalloc() that is always a function, not a macro.
00644 ** Currently, this is used only to alloc to allocate the parser engine.
00645 */
00646 void *sqlite3MallocX(int n){
00647   return sqliteMalloc(n);
00648 }
00649 
00650 /*
00651 ** sqlite3Malloc
00652 ** sqlite3ReallocOrFree
00653 **
00654 ** These two are implemented as wrappers around sqlite3MallocRaw(), 
00655 ** sqlite3Realloc() and sqlite3Free().
00656 */ 
00657 void *sqlite3Malloc(int n, int doMemManage){
00658   void *p = sqlite3MallocRaw(n, doMemManage);
00659   if( p ){
00660     memset(p, 0, n);
00661   }
00662   return p;
00663 }
00664 void sqlite3ReallocOrFree(void **pp, int n){
00665   void *p = sqlite3Realloc(*pp, n);
00666   if( !p ){
00667     sqlite3FreeX(*pp);
00668   }
00669   *pp = p;
00670 }
00671 
00672 /*
00673 ** sqlite3ThreadSafeMalloc() and sqlite3ThreadSafeFree() are used in those
00674 ** rare scenarios where sqlite may allocate memory in one thread and free
00675 ** it in another. They are exactly the same as sqlite3Malloc() and 
00676 ** sqlite3Free() except that:
00677 **
00678 **   * The allocated memory is not included in any calculations with 
00679 **     respect to the soft-heap-limit, and
00680 **
00681 **   * sqlite3ThreadSafeMalloc() must be matched with ThreadSafeFree(),
00682 **     not sqlite3Free(). Calling sqlite3Free() on memory obtained from
00683 **     ThreadSafeMalloc() will cause an error somewhere down the line.
00684 */
00685 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
00686 void *sqlite3ThreadSafeMalloc(int n){
00687   ENTER_MALLOC;
00688   return sqlite3Malloc(n, 0);
00689 }
00690 void sqlite3ThreadSafeFree(void *p){
00691   ENTER_MALLOC;
00692   if( p ){
00693     OSFREE(p);
00694   }
00695 }
00696 #endif
00697 
00698 
00699 /*
00700 ** Return the number of bytes allocated at location p. p must be either 
00701 ** a NULL pointer (in which case 0 is returned) or a pointer returned by 
00702 ** sqlite3Malloc(), sqlite3Realloc() or sqlite3ReallocOrFree().
00703 **
00704 ** The number of bytes allocated does not include any overhead inserted by 
00705 ** any malloc() wrapper functions that may be called. So the value returned
00706 ** is the number of bytes that were available to SQLite using pointer p, 
00707 ** regardless of how much memory was actually allocated.
00708 */
00709 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
00710 int sqlite3AllocSize(void *p){
00711   return OSSIZEOF(p);
00712 }
00713 #endif
00714 
00715 /*
00716 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
00717 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
00718 ** is because when memory debugging is turned on, these two functions are 
00719 ** called via macros that record the current file and line number in the
00720 ** ThreadData structure.
00721 */
00722 char *sqlite3StrDup(const char *z){
00723   char *zNew;
00724   if( z==0 ) return 0;
00725   zNew = sqlite3MallocRaw(strlen(z)+1, 1);
00726   if( zNew ) strcpy(zNew, z);
00727   return zNew;
00728 }
00729 char *sqlite3StrNDup(const char *z, int n){
00730   char *zNew;
00731   if( z==0 ) return 0;
00732   zNew = sqlite3MallocRaw(n+1, 1);
00733   if( zNew ){
00734     memcpy(zNew, z, n);
00735     zNew[n] = 0;
00736   }
00737   return zNew;
00738 }
00739 
00740 /*
00741 ** Create a string from the 2nd and subsequent arguments (up to the
00742 ** first NULL argument), store the string in memory obtained from
00743 ** sqliteMalloc() and make the pointer indicated by the 1st argument
00744 ** point to that string.  The 1st argument must either be NULL or 
00745 ** point to memory obtained from sqliteMalloc().
00746 */
00747 void sqlite3SetString(char **pz, ...){
00748   va_list ap;
00749   int nByte;
00750   const char *z;
00751   char *zResult;
00752 
00753   if( pz==0 ) return;
00754   nByte = 1;
00755   va_start(ap, pz);
00756   while( (z = va_arg(ap, const char*))!=0 ){
00757     nByte += strlen(z);
00758   }
00759   va_end(ap);
00760   sqliteFree(*pz);
00761   *pz = zResult = sqliteMallocRaw( nByte );
00762   if( zResult==0 ){
00763     return;
00764   }
00765   *zResult = 0;
00766   va_start(ap, pz);
00767   while( (z = va_arg(ap, const char*))!=0 ){
00768     strcpy(zResult, z);
00769     zResult += strlen(zResult);
00770   }
00771   va_end(ap);
00772 }
00773 
00774 /*
00775 ** Set the most recent error code and error string for the sqlite
00776 ** handle "db". The error code is set to "err_code".
00777 **
00778 ** If it is not NULL, string zFormat specifies the format of the
00779 ** error string in the style of the printf functions: The following
00780 ** format characters are allowed:
00781 **
00782 **      %s      Insert a string
00783 **      %z      A string that should be freed after use
00784 **      %d      Insert an integer
00785 **      %T      Insert a token
00786 **      %S      Insert the first element of a SrcList
00787 **
00788 ** zFormat and any string tokens that follow it are assumed to be
00789 ** encoded in UTF-8.
00790 **
00791 ** To clear the most recent error for sqlite handle "db", sqlite3Error
00792 ** should be called with err_code set to SQLITE_OK and zFormat set
00793 ** to NULL.
00794 */
00795 void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
00796   if( db && (db->pErr || (db->pErr = sqlite3ValueNew())!=0) ){
00797     db->errCode = err_code;
00798     if( zFormat ){
00799       char *z;
00800       va_list ap;
00801       va_start(ap, zFormat);
00802       z = sqlite3VMPrintf(zFormat, ap);
00803       va_end(ap);
00804       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, sqlite3FreeX);
00805     }else{
00806       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
00807     }
00808   }
00809 }
00810 
00811 /*
00812 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
00813 ** The following formatting characters are allowed:
00814 **
00815 **      %s      Insert a string
00816 **      %z      A string that should be freed after use
00817 **      %d      Insert an integer
00818 **      %T      Insert a token
00819 **      %S      Insert the first element of a SrcList
00820 **
00821 ** This function should be used to report any error that occurs whilst
00822 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
00823 ** last thing the sqlite3_prepare() function does is copy the error
00824 ** stored by this function into the database handle using sqlite3Error().
00825 ** Function sqlite3Error() should be used during statement execution
00826 ** (sqlite3_step() etc.).
00827 */
00828 void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
00829   va_list ap;
00830   pParse->nErr++;
00831   sqliteFree(pParse->zErrMsg);
00832   va_start(ap, zFormat);
00833   pParse->zErrMsg = sqlite3VMPrintf(zFormat, ap);
00834   va_end(ap);
00835 }
00836 
00837 /*
00838 ** Clear the error message in pParse, if any
00839 */
00840 void sqlite3ErrorClear(Parse *pParse){
00841   sqliteFree(pParse->zErrMsg);
00842   pParse->zErrMsg = 0;
00843   pParse->nErr = 0;
00844 }
00845 
00846 /*
00847 ** Convert an SQL-style quoted string into a normal string by removing
00848 ** the quote characters.  The conversion is done in-place.  If the
00849 ** input does not begin with a quote character, then this routine
00850 ** is a no-op.
00851 **
00852 ** 2002-Feb-14: This routine is extended to remove MS-Access style
00853 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
00854 ** "a-b-c".
00855 */
00856 void sqlite3Dequote(char *z){
00857   int quote;
00858   int i, j;
00859   if( z==0 ) return;
00860   quote = z[0];
00861   switch( quote ){
00862     case '\'':  break;
00863     case '"':   break;
00864     case '`':   break;                /* For MySQL compatibility */
00865     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
00866     default:    return;
00867   }
00868   for(i=1, j=0; z[i]; i++){
00869     if( z[i]==quote ){
00870       if( z[i+1]==quote ){
00871         z[j++] = quote;
00872         i++;
00873       }else{
00874         z[j++] = 0;
00875         break;
00876       }
00877     }else{
00878       z[j++] = z[i];
00879     }
00880   }
00881 }
00882 
00883 /* An array to map all upper-case characters into their corresponding
00884 ** lower-case character. 
00885 */
00886 const unsigned char sqlite3UpperToLower[] = {
00887 #ifdef SQLITE_ASCII
00888       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
00889      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
00890      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
00891      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
00892     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
00893     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
00894     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
00895     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
00896     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
00897     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
00898     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
00899     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
00900     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
00901     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
00902     252,253,254,255
00903 #endif
00904 #ifdef SQLITE_EBCDIC
00905       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
00906      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
00907      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
00908      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
00909      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
00910      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
00911      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
00912     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
00913     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
00914     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
00915     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
00916     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
00917     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
00918     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
00919     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
00920     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
00921 #endif
00922 };
00923 #define UpperToLower sqlite3UpperToLower
00924 
00925 /*
00926 ** Some systems have stricmp().  Others have strcasecmp().  Because
00927 ** there is no consistency, we will define our own.
00928 */
00929 int sqlite3StrICmp(const char *zLeft, const char *zRight){
00930   register unsigned char *a, *b;
00931   a = (unsigned char *)zLeft;
00932   b = (unsigned char *)zRight;
00933   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
00934   return UpperToLower[*a] - UpperToLower[*b];
00935 }
00936 int sqlite3StrNICmp(const char *zLeft, const char *zRight, int N){
00937   register unsigned char *a, *b;
00938   a = (unsigned char *)zLeft;
00939   b = (unsigned char *)zRight;
00940   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
00941   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
00942 }
00943 
00944 /*
00945 ** Return TRUE if z is a pure numeric string.  Return FALSE if the
00946 ** string contains any character which is not part of a number. If
00947 ** the string is numeric and contains the '.' character, set *realnum
00948 ** to TRUE (otherwise FALSE).
00949 **
00950 ** An empty string is considered non-numeric.
00951 */
00952 int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
00953   int incr = (enc==SQLITE_UTF8?1:2);
00954   if( enc==SQLITE_UTF16BE ) z++;
00955   if( *z=='-' || *z=='+' ) z += incr;
00956   if( !isdigit(*(u8*)z) ){
00957     return 0;
00958   }
00959   z += incr;
00960   if( realnum ) *realnum = 0;
00961   while( isdigit(*(u8*)z) ){ z += incr; }
00962   if( *z=='.' ){
00963     z += incr;
00964     if( !isdigit(*(u8*)z) ) return 0;
00965     while( isdigit(*(u8*)z) ){ z += incr; }
00966     if( realnum ) *realnum = 1;
00967   }
00968   if( *z=='e' || *z=='E' ){
00969     z += incr;
00970     if( *z=='+' || *z=='-' ) z += incr;
00971     if( !isdigit(*(u8*)z) ) return 0;
00972     while( isdigit(*(u8*)z) ){ z += incr; }
00973     if( realnum ) *realnum = 1;
00974   }
00975   return *z==0;
00976 }
00977 
00978 /*
00979 ** The string z[] is an ascii representation of a real number.
00980 ** Convert this string to a double.
00981 **
00982 ** This routine assumes that z[] really is a valid number.  If it
00983 ** is not, the result is undefined.
00984 **
00985 ** This routine is used instead of the library atof() function because
00986 ** the library atof() might want to use "," as the decimal point instead
00987 ** of "." depending on how locale is set.  But that would cause problems
00988 ** for SQL.  So this routine always uses "." regardless of locale.
00989 */
00990 int sqlite3AtoF(const char *z, double *pResult){
00991 #ifndef SQLITE_OMIT_FLOATING_POINT
00992   int sign = 1;
00993   const char *zBegin = z;
00994   LONGDOUBLE_TYPE v1 = 0.0;
00995   while( isspace(*z) ) z++;
00996   if( *z=='-' ){
00997     sign = -1;
00998     z++;
00999   }else if( *z=='+' ){
01000     z++;
01001   }
01002   while( isdigit(*(u8*)z) ){
01003     v1 = v1*10.0 + (*z - '0');
01004     z++;
01005   }
01006   if( *z=='.' ){
01007     LONGDOUBLE_TYPE divisor = 1.0;
01008     z++;
01009     while( isdigit(*(u8*)z) ){
01010       v1 = v1*10.0 + (*z - '0');
01011       divisor *= 10.0;
01012       z++;
01013     }
01014     v1 /= divisor;
01015   }
01016   if( *z=='e' || *z=='E' ){
01017     int esign = 1;
01018     int eval = 0;
01019     LONGDOUBLE_TYPE scale = 1.0;
01020     z++;
01021     if( *z=='-' ){
01022       esign = -1;
01023       z++;
01024     }else if( *z=='+' ){
01025       z++;
01026     }
01027     while( isdigit(*(u8*)z) ){
01028       eval = eval*10 + *z - '0';
01029       z++;
01030     }
01031     while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
01032     while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
01033     while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
01034     while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }
01035     if( esign<0 ){
01036       v1 /= scale;
01037     }else{
01038       v1 *= scale;
01039     }
01040   }
01041   *pResult = sign<0 ? -v1 : v1;
01042   return z - zBegin;
01043 #else
01044   return sqlite3atoi64(z, pResult);
01045 #endif /* SQLITE_OMIT_FLOATING_POINT */
01046 }
01047 
01048 /*
01049 ** Return TRUE if zNum is a 64-bit signed integer and write
01050 ** the value of the integer into *pNum.  If zNum is not an integer
01051 ** or is an integer that is too large to be expressed with 64 bits,
01052 ** then return false.  If n>0 and the integer is string is not
01053 ** exactly n bytes long, return false.
01054 **
01055 ** When this routine was originally written it dealt with only
01056 ** 32-bit numbers.  At that time, it was much faster than the
01057 ** atoi() library routine in RedHat 7.2.
01058 */
01059 int sqlite3atoi64(const char *zNum, i64 *pNum){
01060   i64 v = 0;
01061   int neg;
01062   int i, c;
01063   while( isspace(*zNum) ) zNum++;
01064   if( *zNum=='-' ){
01065     neg = 1;
01066     zNum++;
01067   }else if( *zNum=='+' ){
01068     neg = 0;
01069     zNum++;
01070   }else{
01071     neg = 0;
01072   }
01073   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
01074     v = v*10 + c - '0';
01075   }
01076   *pNum = neg ? -v : v;
01077   return c==0 && i>0 && 
01078       (i<19 || (i==19 && memcmp(zNum,"9223372036854775807",19)<=0));
01079 }
01080 
01081 /*
01082 ** The string zNum represents an integer.  There might be some other
01083 ** information following the integer too, but that part is ignored.
01084 ** If the integer that the prefix of zNum represents will fit in a
01085 ** 32-bit signed integer, return TRUE.  Otherwise return FALSE.
01086 **
01087 ** This routine returns FALSE for the string -2147483648 even that
01088 ** that number will in fact fit in a 32-bit integer.  But positive
01089 ** 2147483648 will not fit in 32 bits.  So it seems safer to return
01090 ** false.
01091 */
01092 static int sqlite3FitsIn32Bits(const char *zNum){
01093   int i, c;
01094   if( *zNum=='-' || *zNum=='+' ) zNum++;
01095   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
01096   return i<10 || (i==10 && memcmp(zNum,"2147483647",10)<=0);
01097 }
01098 
01099 /*
01100 ** If zNum represents an integer that will fit in 32-bits, then set
01101 ** *pValue to that integer and return true.  Otherwise return false.
01102 */
01103 int sqlite3GetInt32(const char *zNum, int *pValue){
01104   if( sqlite3FitsIn32Bits(zNum) ){
01105     *pValue = atoi(zNum);
01106     return 1;
01107   }
01108   return 0;
01109 }
01110 
01111 /*
01112 ** The string zNum represents an integer.  There might be some other
01113 ** information following the integer too, but that part is ignored.
01114 ** If the integer that the prefix of zNum represents will fit in a
01115 ** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
01116 **
01117 ** This routine returns FALSE for the string -9223372036854775808 even that
01118 ** that number will, in theory fit in a 64-bit integer.  Positive
01119 ** 9223373036854775808 will not fit in 64 bits.  So it seems safer to return
01120 ** false.
01121 */
01122 int sqlite3FitsIn64Bits(const char *zNum){
01123   int i, c;
01124   if( *zNum=='-' || *zNum=='+' ) zNum++;
01125   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
01126   return i<19 || (i==19 && memcmp(zNum,"9223372036854775807",19)<=0);
01127 }
01128 
01129 
01130 /*
01131 ** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
01132 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
01133 ** when this routine is called.
01134 **
01135 ** This routine is a attempt to detect if two threads use the
01136 ** same sqlite* pointer at the same time.  There is a race 
01137 ** condition so it is possible that the error is not detected.
01138 ** But usually the problem will be seen.  The result will be an
01139 ** error which can be used to debug the application that is
01140 ** using SQLite incorrectly.
01141 **
01142 ** Ticket #202:  If db->magic is not a valid open value, take care not
01143 ** to modify the db structure at all.  It could be that db is a stale
01144 ** pointer.  In other words, it could be that there has been a prior
01145 ** call to sqlite3_close(db) and db has been deallocated.  And we do
01146 ** not want to write into deallocated memory.
01147 */
01148 int sqlite3SafetyOn(sqlite3 *db){
01149   if( db->magic==SQLITE_MAGIC_OPEN ){
01150     db->magic = SQLITE_MAGIC_BUSY;
01151     return 0;
01152   }else if( db->magic==SQLITE_MAGIC_BUSY ){
01153     db->magic = SQLITE_MAGIC_ERROR;
01154     db->flags |= SQLITE_Interrupt;
01155   }
01156   return 1;
01157 }
01158 
01159 /*
01160 ** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
01161 ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
01162 ** when this routine is called.
01163 */
01164 int sqlite3SafetyOff(sqlite3 *db){
01165   if( db->magic==SQLITE_MAGIC_BUSY ){
01166     db->magic = SQLITE_MAGIC_OPEN;
01167     return 0;
01168   }else if( db->magic==SQLITE_MAGIC_OPEN ){
01169     db->magic = SQLITE_MAGIC_ERROR;
01170     db->flags |= SQLITE_Interrupt;
01171   }
01172   return 1;
01173 }
01174 
01175 /*
01176 ** Check to make sure we have a valid db pointer.  This test is not
01177 ** foolproof but it does provide some measure of protection against
01178 ** misuse of the interface such as passing in db pointers that are
01179 ** NULL or which have been previously closed.  If this routine returns
01180 ** TRUE it means that the db pointer is invalid and should not be
01181 ** dereferenced for any reason.  The calling function should invoke
01182 ** SQLITE_MISUSE immediately.
01183 */
01184 int sqlite3SafetyCheck(sqlite3 *db){
01185   int magic;
01186   if( db==0 ) return 1;
01187   magic = db->magic;
01188   if( magic!=SQLITE_MAGIC_CLOSED &&
01189          magic!=SQLITE_MAGIC_OPEN &&
01190          magic!=SQLITE_MAGIC_BUSY ) return 1;
01191   return 0;
01192 }
01193 
01194 /*
01195 ** The variable-length integer encoding is as follows:
01196 **
01197 ** KEY:
01198 **         A = 0xxxxxxx    7 bits of data and one flag bit
01199 **         B = 1xxxxxxx    7 bits of data and one flag bit
01200 **         C = xxxxxxxx    8 bits of data
01201 **
01202 **  7 bits - A
01203 ** 14 bits - BA
01204 ** 21 bits - BBA
01205 ** 28 bits - BBBA
01206 ** 35 bits - BBBBA
01207 ** 42 bits - BBBBBA
01208 ** 49 bits - BBBBBBA
01209 ** 56 bits - BBBBBBBA
01210 ** 64 bits - BBBBBBBBC
01211 */
01212 
01213 /*
01214 ** Write a 64-bit variable-length integer to memory starting at p[0].
01215 ** The length of data write will be between 1 and 9 bytes.  The number
01216 ** of bytes written is returned.
01217 **
01218 ** A variable-length integer consists of the lower 7 bits of each byte
01219 ** for all bytes that have the 8th bit set and one byte with the 8th
01220 ** bit clear.  Except, if we get to the 9th byte, it stores the full
01221 ** 8 bits and is the last byte.
01222 */
01223 int sqlite3PutVarint(unsigned char *p, u64 v){
01224   int i, j, n;
01225   u8 buf[10];
01226   if( v & (((u64)0xff000000)<<32) ){
01227     p[8] = v;
01228     v >>= 8;
01229     for(i=7; i>=0; i--){
01230       p[i] = (v & 0x7f) | 0x80;
01231       v >>= 7;
01232     }
01233     return 9;
01234   }    
01235   n = 0;
01236   do{
01237     buf[n++] = (v & 0x7f) | 0x80;
01238     v >>= 7;
01239   }while( v!=0 );
01240   buf[0] &= 0x7f;
01241   assert( n<=9 );
01242   for(i=0, j=n-1; j>=0; j--, i++){
01243     p[i] = buf[j];
01244   }
01245   return n;
01246 }
01247 
01248 /*
01249 ** Read a 64-bit variable-length integer from memory starting at p[0].
01250 ** Return the number of bytes read.  The value is stored in *v.
01251 */
01252 int sqlite3GetVarint(const unsigned char *p, u64 *v){
01253   u32 x;
01254   u64 x64;
01255   int n;
01256   unsigned char c;
01257   if( ((c = p[0]) & 0x80)==0 ){
01258     *v = c;
01259     return 1;
01260   }
01261   x = c & 0x7f;
01262   if( ((c = p[1]) & 0x80)==0 ){
01263     *v = (x<<7) | c;
01264     return 2;
01265   }
01266   x = (x<<7) | (c&0x7f);
01267   if( ((c = p[2]) & 0x80)==0 ){
01268     *v = (x<<7) | c;
01269     return 3;
01270   }
01271   x = (x<<7) | (c&0x7f);
01272   if( ((c = p[3]) & 0x80)==0 ){
01273     *v = (x<<7) | c;
01274     return 4;
01275   }
01276   x64 = (x<<7) | (c&0x7f);
01277   n = 4;
01278   do{
01279     c = p[n++];
01280     if( n==9 ){
01281       x64 = (x64<<8) | c;
01282       break;
01283     }
01284     x64 = (x64<<7) | (c&0x7f);
01285   }while( (c & 0x80)!=0 );
01286   *v = x64;
01287   return n;
01288 }
01289 
01290 /*
01291 ** Read a 32-bit variable-length integer from memory starting at p[0].
01292 ** Return the number of bytes read.  The value is stored in *v.
01293 */
01294 int sqlite3GetVarint32(const unsigned char *p, u32 *v){
01295   u32 x;
01296   int n;
01297   unsigned char c;
01298   if( ((signed char*)p)[0]>=0 ){
01299     *v = p[0];
01300     return 1;
01301   }
01302   x = p[0] & 0x7f;
01303   if( ((signed char*)p)[1]>=0 ){
01304     *v = (x<<7) | p[1];
01305     return 2;
01306   }
01307   x = (x<<7) | (p[1] & 0x7f);
01308   n = 2;
01309   do{
01310     x = (x<<7) | ((c = p[n++])&0x7f);
01311   }while( (c & 0x80)!=0 && n<9 );
01312   *v = x;
01313   return n;
01314 }
01315 
01316 /*
01317 ** Return the number of bytes that will be needed to store the given
01318 ** 64-bit integer.
01319 */
01320 int sqlite3VarintLen(u64 v){
01321   int i = 0;
01322   do{
01323     i++;
01324     v >>= 7;
01325   }while( v!=0 && i<9 );
01326   return i;
01327 }
01328 
01329 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC) \
01330     || defined(SQLITE_TEST)
01331 /*
01332 ** Translate a single byte of Hex into an integer.
01333 */
01334 static int hexToInt(int h){
01335   if( h>='0' && h<='9' ){
01336     return h - '0';
01337   }else if( h>='a' && h<='f' ){
01338     return h - 'a' + 10;
01339   }else{
01340     assert( h>='A' && h<='F' );
01341     return h - 'A' + 10;
01342   }
01343 }
01344 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC || SQLITE_TEST */
01345 
01346 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
01347 /*
01348 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
01349 ** value.  Return a pointer to its binary value.  Space to hold the
01350 ** binary value has been obtained from malloc and must be freed by
01351 ** the calling routine.
01352 */
01353 void *sqlite3HexToBlob(const char *z){
01354   char *zBlob;
01355   int i;
01356   int n = strlen(z);
01357   if( n%2 ) return 0;
01358 
01359   zBlob = (char *)sqliteMalloc(n/2);
01360   for(i=0; i<n; i+=2){
01361     zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
01362   }
01363   return zBlob;
01364 }
01365 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
01366 
01367 #if defined(SQLITE_TEST)
01368 /*
01369 ** Convert text generated by the "%p" conversion format back into
01370 ** a pointer.
01371 */
01372 void *sqlite3TextToPtr(const char *z){
01373   void *p;
01374   u64 v;
01375   u32 v2;
01376   if( z[0]=='0' && z[1]=='x' ){
01377     z += 2;
01378   }
01379   v = 0;
01380   while( *z ){
01381     v = (v<<4) + hexToInt(*z);
01382     z++;
01383   }
01384   if( sizeof(p)==sizeof(v) ){
01385     p = *(void**)&v;
01386   }else{
01387     assert( sizeof(p)==sizeof(v2) );
01388     v2 = (u32)v;
01389     p = *(void**)&v2;
01390   }
01391   return p;
01392 }
01393 #endif
01394 
01395 /*
01396 ** Return a pointer to the ThreadData associated with the calling thread.
01397 */
01398 ThreadData *sqlite3ThreadData(){
01399   ThreadData *p = (ThreadData*)sqlite3OsThreadSpecificData(1);
01400   if( !p ){
01401     sqlite3FailedMalloc();
01402   }
01403   return p;
01404 }
01405 
01406 /*
01407 ** Return a pointer to the ThreadData associated with the calling thread.
01408 ** If no ThreadData has been allocated to this thread yet, return a pointer
01409 ** to a substitute ThreadData structure that is all zeros. 
01410 */
01411 const ThreadData *sqlite3ThreadDataReadOnly(){
01412   static const ThreadData zeroData = {0};  /* Initializer to silence warnings
01413                                            ** from broken compilers */
01414   const ThreadData *pTd = sqlite3OsThreadSpecificData(0);
01415   return pTd ? pTd : &zeroData;
01416 }
01417 
01418 /*
01419 ** Check to see if the ThreadData for this thread is all zero.  If it
01420 ** is, then deallocate it. 
01421 */
01422 void sqlite3ReleaseThreadData(){
01423   sqlite3OsThreadSpecificData(-1);
01424 }
01425 
01426 /*
01427 ** This function must be called before exiting any API function (i.e. 
01428 ** returning control to the user) that has called sqlite3Malloc or
01429 ** sqlite3Realloc.
01430 **
01431 ** The returned value is normally a copy of the second argument to this
01432 ** function. However, if a malloc() failure has occured since the previous
01433 ** invocation SQLITE_NOMEM is returned instead. 
01434 **
01435 ** If the first argument, db, is not NULL and a malloc() error has occured,
01436 ** then the connection error-code (the value returned by sqlite3_errcode())
01437 ** is set to SQLITE_NOMEM.
01438 */
01439 static int mallocHasFailed = 0;
01440 int sqlite3ApiExit(sqlite3* db, int rc){
01441   if( sqlite3MallocFailed() ){
01442     mallocHasFailed = 0;
01443     sqlite3OsLeaveMutex();
01444     sqlite3Error(db, SQLITE_NOMEM, 0);
01445     rc = SQLITE_NOMEM;
01446   }
01447   return rc;
01448 }
01449 
01450 /* 
01451 ** Return true is a malloc has failed in this thread since the last call
01452 ** to sqlite3ApiExit(), or false otherwise.
01453 */
01454 int sqlite3MallocFailed(){
01455   return (mallocHasFailed && sqlite3OsInMutex(1));
01456 }
01457 
01458 /* 
01459 ** Set the "malloc has failed" condition to true for this thread.
01460 */
01461 void sqlite3FailedMalloc(){
01462   sqlite3OsEnterMutex();
01463   assert( mallocHasFailed==0 );
01464   mallocHasFailed = 1;
01465 }
01466 
01467 #ifdef SQLITE_MEMDEBUG
01468 /*
01469 ** This function sets a flag in the thread-specific-data structure that will
01470 ** cause an assert to fail if sqliteMalloc() or sqliteRealloc() is called.
01471 */
01472 void sqlite3MallocDisallow(){
01473   assert( sqlite3_mallocDisallowed>=0 );
01474   sqlite3_mallocDisallowed++;
01475 }
01476 
01477 /*
01478 ** This function clears the flag set in the thread-specific-data structure set
01479 ** by sqlite3MallocDisallow().
01480 */
01481 void sqlite3MallocAllow(){
01482   assert( sqlite3_mallocDisallowed>0 );
01483   sqlite3_mallocDisallowed--;
01484 }
01485 #endif