64bit fixes.
[AROS-Contrib.git] / sqlite3 / util.c
blob9db0ecaffafbbd2d905bf1926b7905a6c772bffa
1 /*
2 * 2005 July 4, Markku Sukanen
3 * - modifying the code for AROS.
5 * 2001 September 15
7 * The author disclaims copyright to this source code. In place of a legal
8 * notice, here is a blessing:
10 * May you do good and not evil.
11 * May you find forgiveness for yourself and forgive others.
12 * May you share freely, never taking more than you give.
13 * */
14 /**
15 * @file util.c
16 * @brief Utility functions used throughout sqlite.
18 * This file contains functions for allocating memory, comparing strings, and
19 * stuff like that.
20 * */
21 /* $Id$ */
22 #include "sqliteInt.h"
23 #include <stdarg.h>
24 #include <ctype.h>
25 #include <exec/memory.h>
26 #include <proto/exec.h>
28 #if SQLITE_MEMDEBUG>2 && defined(__GLIBC__)
29 #include <execinfo.h>
30 void print_stack_trace()
32 void *bt[30];
33 int i;
34 int n = backtrace(bt, 30);
36 fprintf(stderr, "STACK: ");
37 for( i=0; i<n; i++ )
38 fprintf(stderr, "%p ", bt[i]);
39 fprintf(stderr, "\n");
41 #else
42 #define print_stack_trace()
43 #endif
46 * If malloc() ever fails, this global variable gets set to 1. This causes the
47 * library to abort and never again function.
48 * */
49 int sqlite3_malloc_failed = 0;
52 * If SQLITE_MEMDEBUG is defined, then use versions of malloc() and free() that
53 * track memory usage and check for buffer overruns.
54 * */
55 #ifdef SQLITE_MEMDEBUG
58 * For keeping track of the number of mallocs and frees. This is used to check
59 * for memory leaks. The iMallocFail and iMallocReset values are used to
60 * simulate malloc() failures during testing in order to verify that the
61 * library correctly handles an out-of-memory condition.
62 * */
63 int sqlite3_nMalloc; /* Number of sqliteMalloc() calls */
64 int sqlite3_nFree; /* Number of sqliteFree() calls */
65 int sqlite3_iMallocFail; /* Fail sqliteMalloc() after this many calls */
66 int sqlite3_iMallocReset = -1; /* When iMallocFail reaches 0, set to this */
67 #if SQLITE_MEMDEBUG>1
68 static int memcnt = 0;
69 #endif
72 * Number of 32-bit guard words. This should probably be a multiple of 2 since
73 * on 64-bit machines we want the value returned by sqliteMalloc() to be 8-byte
74 * aligned.
75 * */
76 #define N_GUARD 2
79 * Allocate new memory and set it to zero. Return NULL if no memory is
80 * available.
81 * */
82 void *sqlite3Malloc_(int n, int bZero, char *zFile, int line)
84 void *p;
85 int *pi;
86 int i, k;
87 if( sqlite3_iMallocFail>=0 )
89 sqlite3_iMallocFail--;
90 if( sqlite3_iMallocFail==0 )
92 sqlite3_malloc_failed++;
93 #if SQLITE_MEMDEBUG>1
94 fprintf( stderr, "**** failed to allocate %d bytes at %s:%d\n",
95 n, zFile,line);
96 #endif
97 sqlite3_iMallocFail = sqlite3_iMallocReset;
98 return 0;
101 if( n==0 ) return 0;
102 k = (n+sizeof(int)-1)/sizeof(int);
103 pi = malloc( (N_GUARD*2+1+k)*sizeof(int));
104 if( pi==0 )
106 if( n>0 ) sqlite3_malloc_failed++;
107 return 0;
109 sqlite3_nMalloc++;
110 for( i=0; i<N_GUARD; i++ ) pi[i] = 0xdead1122;
111 pi[N_GUARD] = n;
112 for( i=0; i<N_GUARD; i++ ) pi[k+1+N_GUARD+i] = 0xdead3344;
113 p = &pi[N_GUARD+1];
114 memset(p, bZero==0, n);
115 #if SQLITE_MEMDEBUG>1
116 print_stack_trace();
117 fprintf(stderr, "%06d malloc %d bytes at 0x%x from %s:%d\n",
118 ++memcnt, n, (int)p, zFile,line);
119 #endif
120 return p;
125 * This version of malloc is always a real function, never a macro
126 * */
127 void *sqlite3MallocX(int n)
129 return sqlite3Malloc_(n, 0, __FILE__, __LINE__);
134 * Check to see if the given pointer was obtained from sqliteMalloc() and is
135 * able to hold at least N bytes. Raise an exception if this is not the case.
137 * This routine is used for testing purposes only.
138 * */
139 void sqlite3CheckMemory(void *p, int N)
141 int *pi = p;
142 int n, i, k;
144 pi -= N_GUARD+1;
145 for( i=0; i<N_GUARD; i++ )
146 assert( pi[i]==0xdead1122 );
148 n = pi[N_GUARD];
149 assert( N>=0 && N<n );
150 k = (n+sizeof(int)-1)/sizeof(int);
151 for( i=0; i<N_GUARD; i++ )
152 assert( pi[k+N_GUARD+1+i]==0xdead3344 );
157 * Free memory previously obtained from sqliteMalloc()
158 * */
159 void sqlite3Free_(void *p, char *zFile, int line)
161 if( p )
163 int *pi, i, k, n;
164 pi = p;
165 pi -= N_GUARD+1;
166 sqlite3_nFree++;
167 for( i=0; i<N_GUARD; i++ )
169 if( pi[i] != 0xDEAD1122 )
171 fprintf(stderr,"Low-end memory corruption at 0x%x\n", (int)p);
172 return;
175 n = pi[N_GUARD];
176 k = (n+sizeof(int)-1)/sizeof(int);
177 for( i=0; i<N_GUARD; i++ )
179 if( pi[k+N_GUARD+1+i] != 0xDEAD3344 )
181 fprintf(stderr,"High-end memory corruption at 0x%x\n", (int)p);
182 return;
185 memset(pi, 0xff, (k+N_GUARD*2+1)*sizeof(int));
186 #if SQLITE_MEMDEBUG>1
187 fprintf(stderr, "%06d free %d bytes at 0x%x from %s:%d\n",
188 ++memcnt, n, (int)p, zFile,line);
189 #endif
190 free( pi );
196 * Resize a prior allocation. If p==0, then this routine works just like
197 * sqliteMalloc(). If n==0, then this routine works just like sqliteFree().
198 * */
199 void *sqlite3Realloc_(void *oldP, int n, char *zFile, int line)
201 int *oldPi, *pi, i, k, oldN, oldK;
202 void *p;
204 if( !oldP )
205 return sqlite3Malloc_(n,1,zFile,line);
206 if( !n )
208 sqlite3Free_(oldP,zFile,line);
209 return 0;
211 oldPi = oldP;
212 oldPi -= N_GUARD+1;
213 if( oldPi[0] != 0xDEAD1122 )
215 fprintf(stderr,
216 "Low-end memory corruption in realloc at 0x%x\n", (int)oldP);
217 return 0;
219 oldN = oldPi[N_GUARD];
220 oldK = (oldN+sizeof(int)-1)/sizeof(int);
221 for( i=0; i<N_GUARD; i++ )
223 if( oldPi[oldK+N_GUARD+1+i] != 0xDEAD3344 )
225 fprintf(stderr,"High-end memory corruption in realloc at 0x%x\n",
226 (int)oldP);
227 return 0;
230 k = (n + sizeof(int) - 1)/sizeof(int);
231 pi = malloc( (k+N_GUARD*2+1)*sizeof(int) );
232 if( !pi )
234 if( n>0 ) sqlite3_malloc_failed++;
235 return 0;
237 for( i=0; i<N_GUARD; i++ ) pi[i] = 0xDEAD1122;
238 pi[N_GUARD] = n;
239 for( i=0; i<N_GUARD; i++ ) pi[k+N_GUARD+1+i] = 0xDEAD3344;
240 p = &pi[N_GUARD+1];
241 memcpy( p, oldP, (n > oldN) ? oldN : n );
242 if( n>oldN )
243 memset( &((char*)p)[oldN], 0x55, n-oldN );
244 memset( oldPi, 0xAB, (oldK+N_GUARD+2)*sizeof(int));
245 free( oldPi );
246 #if SQLITE_MEMDEBUG>1
247 print_stack_trace();
248 fprintf(stderr,"%06d realloc %d to %d bytes at 0x%x to 0x%x at %s:%d\n",
249 ++memcnt, oldN, n, (int)oldP, (int)p, zFile, line);
250 #endif
251 return p;
256 * Make a copy of a string in memory obtained from sqliteMalloc()
257 * */
258 char *sqlite3StrDup_(const char *z, char *zFile, int line)
260 char *zNew;
261 if( z==0 ) return 0;
262 zNew = sqlite3Malloc_(strlen(z)+1, 0, zFile, line);
263 if( zNew ) strcpy(zNew, z);
264 return zNew;
266 char *sqlite3StrNDup_(const char *z, int n, char *zFile, int line)
268 char *zNew;
269 if( z==0 ) return 0;
270 zNew = sqlite3Malloc_(n+1, 0, zFile, line);
271 if( zNew )
273 memcpy(zNew, z, n);
274 zNew[n] = 0;
276 return zNew;
281 * A version of sqliteFree that is always a function, not a macro.
282 * */
283 void sqlite3FreeX(void *p)
285 sqliteFree(p);
287 #endif /* SQLITE_MEMDEBUG */
291 * The following versions of malloc() and free() are for use in a normal build.
292 * */
293 #if !defined(SQLITE_MEMDEBUG)
296 * Allocate new memory and set it to zero. Return NULL if no memory is
297 * available. See also sqliteMallocRaw().
298 * */
299 void *sqlite3Malloc(int n)
301 void *p;
302 if( ! (p = malloc(n)))
304 if( n > 0 )
305 sqlite3_malloc_failed++;
306 }else
307 memset(p, 0, n);
308 return p;
313 * Allocate new memory but do not set it to zero. Return NULL if no memory is
314 * available. See also sqliteMalloc().
315 * */
316 void *sqlite3MallocRaw(int n)
318 void *p;
319 if( ! (p = malloc(n)))
320 if( n > 0 )
321 sqlite3_malloc_failed++;
322 return p;
327 * Free memory previously obtained from sqliteMalloc()
328 * */
329 void sqlite3FreeX(void *p)
331 if( p ) free(p);
336 * Resize a prior allocation. If p==0, then this routine works just like
337 * sqliteMalloc(). If n==0, then this routine works just like sqliteFree().
338 * */
339 void *sqlite3Realloc(void *p, int n)
341 void *p2;
343 if( !p ) return sqliteMalloc(n);
344 if( !n )
346 sqliteFree( p );
347 return 0;
349 p2 = realloc(p, n);
350 if( !p2 && n>0 )
351 sqlite3_malloc_failed++;
352 return p2;
357 * Make a copy of a string in memory obtained from sqliteMalloc()
358 * */
359 char *sqlite3StrDup(const char *z)
361 char *zNew;
362 if( !z ) return NULL;
363 zNew = sqliteMallocRaw(strlen(z)+1);
364 if( zNew ) strcpy(zNew, z);
365 return zNew;
367 char *sqlite3StrNDup(const char *z, int n)
369 char *zNew;
370 if( !z ) return NULL;
371 zNew = sqliteMallocRaw(n+1);
372 if( zNew )
374 memcpy(zNew, z, n);
375 zNew[n] = '\0';
377 return zNew;
379 #endif /* !defined(SQLITE_MEMDEBUG) */
383 * Create a string from the 2nd and subsequent arguments (up to the first NULL
384 * argument), store the string in memory obtained from sqliteMalloc() and make
385 * the pointer indicated by the 1st argument point to that string. The 1st
386 * argument must either be NULL or point to memory obtained from
387 * sqliteMalloc().
388 * */
389 void sqlite3SetString(STRPTR *pz, ...)
391 va_list ap;
392 int nByte;
393 const char *z;
394 char *zResult;
396 if( !pz ) return;
397 nByte = 1;
398 va_start(ap, pz);
399 while( (z = va_arg(ap, const char*))!=0 )
400 nByte += strlen(z);
401 va_end(ap);
402 sqliteFree(*pz);
403 *pz = zResult = sqliteMallocRaw( nByte );
404 if( !zResult )
405 return;
407 *zResult = '\0';
408 va_start(ap, pz);
409 while( (z = va_arg(ap, const char*)))
411 strcpy(zResult, z);
412 zResult += strlen(zResult);
414 va_end(ap);
415 #ifdef SQLITE_DEBUG
416 #if SQLITE_DEBUG>1
417 fprintf(stderr,"string at 0x%x is %s\n", (int)*pz, *pz);
418 #endif
419 #endif
424 * Set the most recent error code and error string for the sqlite handle "db".
425 * The error code is set to "err_code".
427 * If it is not NULL, string zFormat specifies the format of the error string
428 * in the style of the printf functions: The following format characters are
429 * allowed:
430 * %s Insert a string
431 * %z A string that should be freed after use
432 * %d Insert an integer
433 * %T Insert a token
434 * %S Insert the first element of a SrcList
436 * zFormat and any string tokens that follow it are assumed to be encoded in
437 * UTF-8.
439 * To clear the most recent error for sqlite handle "db", sqlite3Error should
440 * be called with err_code set to SQLITE_OK and zFormat set to NULL.
441 * */
442 void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...)
444 if( db && (db->pErr || (db->pErr = sqlite3ValueNew())))
446 db->errCode = err_code;
447 if( zFormat )
449 char *z;
450 va_list ap;
451 va_start( ap, zFormat );
452 z = sqlite3VMPrintf( zFormat, ap );
453 va_end( ap );
454 sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, sqlite3FreeX);
455 }else
456 sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
462 * Add an error message to pParse->zErrMsg and increment pParse->nErr.
463 * The following formatting characters are allowed:
464 * %s Insert a string
465 * %z A string that should be freed after use
466 * %d Insert an integer
467 * %T Insert a token
468 * %S Insert the first element of a SrcList
470 * This function should be used to report any error that occurs whilst
471 * compiling an SQL statement (i.e. within sqlite3_prepare()). The last thing
472 * the sqlite3_prepare() function does is copy the error stored by this
473 * function into the database handle using sqlite3Error(). Function
474 * sqlite3Error() should be used during statement execution (sqlite3_step()
475 * etc.).
476 * */
477 void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...)
479 va_list ap;
480 pParse->nErr++;
481 sqliteFree( pParse->zErrMsg );
482 va_start( ap, zFormat );
483 pParse->zErrMsg = sqlite3VMPrintf( zFormat, ap );
484 va_end( ap );
489 * Convert an SQL-style quoted string into a normal string by removing the
490 * quote characters. The conversion is done in-place. If the input does not
491 * begin with a quote character, then this routine is a no-op.
493 * 2002-Feb-14: This routine is extended to remove MS-Access style brackets
494 * from around identifers. For example: "[a-b-c]" becomes "a-b-c".
495 * */
496 void sqlite3Dequote(char *z)
498 int quote;
499 int i, j;
501 if( !z ) return;
503 switch( (quote = z[0]))
505 case '\'': break;
506 case '"': break;
507 case '[': quote = ']'; break;
508 default: return;
511 for( i=1, j=0; z[i]; i++ )
513 if( z[i]==quote )
515 if( z[i+1]==quote )
517 z[j++] = quote;
518 i++;
519 }else {
520 z[j++] = 0;
521 break;
523 }else
524 z[j++] = z[i];
530 * An array to map all upper-case characters into their corresponding
531 * lower-case character.
532 * */
533 const unsigned char sqlite3UpperToLower[] = {
534 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
535 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
536 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
537 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
538 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
539 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
540 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
541 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
542 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
543 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
544 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
545 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
546 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
547 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
548 252,253,254,255
550 #define UpperToLower sqlite3UpperToLower
553 * Some systems have stricmp(). Others have strcasecmp(). Because there is
554 * no consistency, we will define our own.
555 * */
556 int sqlite3StrICmp(const char *zLeft, const char *zRight)
558 register unsigned char *a, *b;
559 a = (unsigned char *)zLeft;
560 b = (unsigned char *)zRight;
561 while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
562 return UpperToLower[*a] - UpperToLower[*b];
564 int sqlite3StrNICmp(const char *zLeft, const char *zRight, int N)
566 register unsigned char *a, *b;
567 a = (unsigned char *)zLeft;
568 b = (unsigned char *)zRight;
569 while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
570 return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
575 * Return TRUE if z is a pure numeric string. Return FALSE if the string
576 * contains any character which is not part of a number. If the string is
577 * numeric and contains the '.' character, set *realnum to TRUE (otherwise
578 * FALSE).
580 * An empty string is considered non-numeric.
581 * */
582 int sqlite3IsNumber(const char *z, int *realnum, u8 enc)
584 int incr = (enc==SQLITE_UTF8?1:2);
585 if( enc==SQLITE_UTF16BE ) z++;
586 if( *z=='-' || *z=='+' ) z += incr;
587 if( !isdigit(*(u8*)z) ) return 0;
588 z += incr;
589 if( realnum ) *realnum = 0;
590 while( isdigit(*(u8*)z) ){ z += incr; }
591 if( *z=='.' )
593 z += incr;
594 if( !isdigit(*(u8*)z) ) return 0;
595 while( isdigit(*(u8*)z) ){ z += incr; }
596 if( realnum ) *realnum = 1;
598 if( *z=='e' || *z=='E' )
600 z += incr;
601 if( *z=='+' || *z=='-' ) z += incr;
602 if( !isdigit(*(u8*)z) ) return 0;
603 while( isdigit(*(u8*)z) ){ z += incr; }
604 if( realnum ) *realnum = 1;
606 return *z==0;
611 * The string z[] is an ascii representation of a real number. Convert this
612 * string to a double.
614 * This routine assumes that z[] really is a valid number. If it is not, the
615 * result is undefined.
617 * This routine is used instead of the library atof() function because the
618 * library atof() might want to use "," as the decimal point instead of "."
619 * depending on how locale is set. But that would cause problems for SQL.
620 * So this routine always uses "." regardless of locale.
621 * */
622 double sqlite3AtoF(const char *z, const char **pzEnd)
624 int sign = 1;
625 LONGDOUBLE_TYPE v1 = 0.0;
626 if( *z=='-' )
628 sign = -1;
629 z++;
630 }else if( *z=='+' )
631 z++;
633 while( isdigit(*(u8*)z) )
635 v1 = v1*10.0 + (*z - '0');
636 z++;
638 if( *z=='.' )
640 LONGDOUBLE_TYPE divisor = 1.0;
641 z++;
642 while( isdigit(*(u8*)z) )
644 v1 = v1*10.0 + (*z - '0');
645 divisor *= 10.0;
646 z++;
648 v1 /= divisor;
650 if( *z=='e' || *z=='E' )
652 int esign = 1;
653 int eval = 0;
654 LONGDOUBLE_TYPE scale = 1.0;
655 z++;
656 if( *z=='-' )
658 esign = -1;
659 z++;
660 }else if( *z=='+' )
661 z++;
662 while( isdigit(*(u8*)z) )
664 eval = eval*10 + *z - '0';
665 z++;
667 while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
668 while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
669 while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
670 while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }
671 if( esign<0 )
672 v1 /= scale;
673 else v1 *= scale;
675 if( pzEnd ) *pzEnd = z;
676 return sign<0 ? -v1 : v1;
681 * Return TRUE if zNum is a 64-bit signed integer and write the value of the
682 * integer into *pNum. If zNum is not an integer or is an integer that is too
683 * large to be expressed with 64 bits, then return false. If n>0 and the
684 * integer is string is not exactly n bytes long, return false.
686 * When this routine was originally written it dealt with only 32-bit numbers.
687 * At that time, it was much faster than the atoi() library routine in RedHat
688 * 7.2.
689 * */
690 BOOL sqlite3atoi64(const char *zNum, i64 *pNum)
692 i64 v = 0;
693 int neg;
694 int i, c;
695 if( *zNum=='-' )
697 neg = 1;
698 zNum++;
700 else if( *zNum=='+' )
702 neg = 0;
703 zNum++;
704 }else
705 neg = 0;
707 for( i=0; (c=zNum[i])>='0' && c<='9'; i++ )
708 v = v*10 + c - '0';
710 *pNum = neg ? -v : v;
711 return c==0 && i>0 &&
712 (i<19 || (i==19 && memcmp(zNum,"9223372036854775807",19)<=0));
717 * The string zNum represents an integer. There might be some other information
718 * following the integer too, but that part is ignored. If the integer that the
719 * prefix of zNum represents will fit in a 32-bit signed integer, return TRUE.
720 * Otherwise return FALSE.
722 * This routine returns FALSE for the string -2147483648 even that that number
723 * will in fact fit in a 32-bit integer. But positive 2147483648 will not fit
724 * in 32 bits. So it seems safer to return false.
725 * */
726 static BOOL sqlite3FitsIn32Bits(const char *zNum)
728 int i, c;
729 if( *zNum=='-' || *zNum=='+' ) zNum++;
730 for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
731 return i<10 || (i==10 && memcmp(zNum,"2147483647",10)<=0);
736 * If zNum represents an integer that will fit in 32-bits, then set *pValue to
737 * that integer and return true. Otherwise return false.
738 * */
739 BOOL sqlite3GetInt32(const char *zNum, int *pValue)
741 if( sqlite3FitsIn32Bits(zNum) )
743 *pValue = atoi(zNum);
744 return TRUE;
746 return FALSE;
751 * The string zNum represents an integer. There might be some other information
752 * following the integer too, but that part is ignored. If the integer that the
753 * prefix of zNum represents will fit in a 64-bit signed integer, return TRUE.
754 * Otherwise return FALSE.
756 * This routine returns FALSE for the string -9223372036854775808 even that
757 * that number will, in theory fit in a 64-bit integer. Positive
758 * 9223373036854775808 will not fit in 64 bits. So it seems safer to return
759 * false.
760 * */
761 BOOL sqlite3FitsIn64Bits(const char *zNum)
763 int i, c;
764 if( *zNum=='-' || *zNum=='+' ) zNum++;
765 for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
766 return i<19 || (i==19 && memcmp(zNum,"9223372036854775807",19)<=0);
771 * Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY. Return
772 * an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN when this routine
773 * is called.
775 * This routine is a attempt to detect if two threads use the same sqlite*
776 * pointer at the same time. There is a race condition so it is possible that
777 * the error is not detected. But usually the problem will be seen. The result
778 * will be an error which can be used to debug the application that is using
779 * SQLite incorrectly.
781 * Ticket #202: If db->magic is not a valid open value, take care not to
782 * modify the db structure at all. It could be that db is a stale pointer. In
783 * other words, it could be that there has been a prior call to
784 * sqlite3_close(db) and db has been deallocated. And we do not want to write
785 * into deallocated memory.
786 * */
787 BOOL sqlite3SafetyOn(sqlite3 *db)
789 if( db->magic==SQLITE_MAGIC_OPEN )
791 db->magic = SQLITE_MAGIC_BUSY;
792 return FALSE;
794 else if( db->magic==SQLITE_MAGIC_BUSY || db->magic==SQLITE_MAGIC_ERROR )
796 db->magic = SQLITE_MAGIC_ERROR;
797 db->flags |= SQLITE_Interrupt;
799 return TRUE;
804 * Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN. Return an
805 * error (non-zero) if the magic was not SQLITE_MAGIC_BUSY when this routine is
806 * called.
807 * */
808 BOOL sqlite3SafetyOff(sqlite3 *db)
810 if( db->magic==SQLITE_MAGIC_BUSY )
812 db->magic = SQLITE_MAGIC_OPEN;
813 return FALSE;
815 else if( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ERROR )
817 db->magic = SQLITE_MAGIC_ERROR;
818 db->flags |= SQLITE_Interrupt;
820 return TRUE;
825 * Check to make sure we have a valid db pointer. This test is not foolproof
826 * but it does provide some measure of protection against misuse of the
827 * interface such as passing in db pointers that are NULL or which have been
828 * previously closed. If this routine returns TRUE it means that the db pointer
829 * is invalid and should not be dereferenced for any reason. The calling
830 * function should invoke SQLITE_MISUSE immediately.
831 * */
832 BOOL sqlite3SafetyCheck(sqlite3 *db)
834 int magic;
835 if( !db ) return TRUE;
836 magic = db->magic;
837 if( magic != SQLITE_MAGIC_CLOSED
838 && magic != SQLITE_MAGIC_OPEN
839 && magic != SQLITE_MAGIC_BUSY ) return TRUE;
840 return FALSE;
845 * The variable-length integer encoding is as follows:
847 * KEY:
848 * A = 0xxxxxxx 7 bits of data and one flag bit
849 * B = 1xxxxxxx 7 bits of data and one flag bit
850 * C = xxxxxxxx 8 bits of data
852 * 7 bits - A
853 * 14 bits - BA
854 * 21 bits - BBA
855 * 28 bits - BBBA
856 * 35 bits - BBBBA
857 * 42 bits - BBBBBA
858 * 49 bits - BBBBBBA
859 * 56 bits - BBBBBBBA
860 * 64 bits - BBBBBBBBC
861 * */
864 * Write a 64-bit variable-length integer to memory starting at p[0]. The
865 * length of data write will be between 1 and 9 bytes. The number of bytes
866 * written is returned.
868 * A variable-length integer consists of the lower 7 bits of each byte for all
869 * bytes that have the 8th bit set and one byte with the 8th bit clear.
870 * Except, if we get to the 9th byte, it stores the full 8 bits and is the last
871 * byte.
872 * */
873 int sqlite3PutVarint(unsigned char *p, u64 v)
875 int i, j, n;
876 u8 buf[10];
877 if( v & (((u64)0xff000000)<<32))
879 p[8] = v;
880 v >>= 8;
881 for( i=7; i>=0; i-- )
883 p[i] = (v & 0x7f) | 0x80;
884 v >>= 7;
886 return 9;
889 n = 0;
890 do {
891 buf[n++] = (v & 0x7f) | 0x80;
892 v >>= 7;
893 }while( v );
894 buf[0] &= 0x7f;
895 assert( n<=9 );
896 for( i=0, j=n-1; j>=0; j--, i++ )
897 p[i] = buf[j];
899 return n;
904 * Read a 64-bit variable-length integer from memory starting at p[0]. Return
905 * the number of bytes read. The value is stored in *v.
906 * */
907 int sqlite3GetVarint(const unsigned char *p, u64 *v)
909 u32 x;
910 u64 x64;
911 int n;
912 unsigned char c;
913 if( ! ((c = p[0]) & 0x80))
915 *v = c;
916 return 1;
918 x = c & 0x7f;
919 if( ! ((c = p[1]) & 0x80))
921 *v = (x<<7) | c;
922 return 2;
924 x = (x<<7) | (c&0x7f);
925 if( ! ((c = p[2]) & 0x80))
927 *v = (x<<7) | c;
928 return 3;
930 x = (x<<7) | (c&0x7f);
931 if( ! ((c = p[3]) & 0x80))
933 *v = (x<<7) | c;
934 return 4;
936 x64 = (x<<7) | (c&0x7f);
937 n = 4;
938 do {
939 c = p[n++];
940 if( n==9 )
942 x64 = (x64<<8) | c;
943 break;
945 x64 = (x64<<7) | (c&0x7f);
946 }while( c & 0x80 );
947 *v = x64;
948 return n;
953 * Read a 32-bit variable-length integer from memory starting at p[0]. Return
954 * the number of bytes read. The value is stored in *v.
955 * */
956 int sqlite3GetVarint32(const unsigned char *p, u32 *v)
958 u32 x;
959 int n;
960 unsigned char c;
961 if( ((signed char*)p)[0]>=0 )
963 *v = p[0];
964 return 1;
966 x = p[0] & 0x7f;
967 if( ((signed char*)p)[1]>=0 )
969 *v = (x<<7) | p[1];
970 return 2;
972 x = (x<<7) | (p[1] & 0x7f);
973 n = 2;
974 do {
975 x = (x<<7) | ((c = p[n++])&0x7f);
976 }while( (c & 0x80) && n<9 );
977 *v = x;
978 return n;
983 * Return the number of bytes that will be needed to store the given 64-bit
984 * integer.
985 * */
986 int sqlite3VarintLen(u64 v)
988 int i = 0;
989 do {
990 i++;
991 v >>= 7;
992 }while( v && i<9 );
993 return i;
997 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC) \
998 || defined(SQLITE_TEST)
1000 * Translate a single byte of Hex into an integer.
1001 * */
1002 static int hexToInt(int h)
1004 if( h>='0' && h<='9' )
1005 return h - '0';
1006 else if( h>='a' && h<='f' )
1007 return h - 'a' + 10;
1008 else {
1009 assert( h>='A' && h<='F' );
1010 return h - 'A' + 10;
1013 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC || SQLITE_TEST */
1016 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
1018 * Convert a BLOB literal of the form "x'hhhhhh'" into its binary value.
1019 * Return a pointer to its binary value. Space to hold the binary value has
1020 * been obtained from malloc and must be freed by the calling routine.
1021 * */
1022 void *sqlite3HexToBlob(const char *z)
1024 char *zBlob;
1025 int i;
1026 int n = strlen(z);
1028 if( n%2 ) return 0;
1030 zBlob = (char *)sqliteMalloc(n/2);
1031 for(i=0; i<n; i+=2)
1032 zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
1034 return zBlob;
1036 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
1039 #if defined(SQLITE_TEST)
1041 * Convert text generated by the "%p" conversion format back into a pointer.
1042 * */
1043 void *sqlite3TextToPtr(const char *z)
1045 void *p;
1046 u64 v;
1047 u32 v2;
1048 if( z[0]=='0' && z[1]=='x' )
1049 z += 2;
1050 v = 0;
1051 while( *z )
1053 v = (v<<4) + hexToInt(*z);
1054 z++;
1056 if( sizeof(p)==sizeof(v) )
1057 p = *(void**)&v;
1058 else {
1059 assert( sizeof(p)==sizeof(v2) );
1060 v2 = (u32)v;
1061 p = *(void**)&v2;
1063 return p;
1065 #endif