blob: 813ef6e62ca4e9ab8f3a8b645a985c81f6e9fd21 [file] [log] [blame]
drhc81c11f2009-11-10 01:30:52 +00001/*
2** 2001 September 15
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11*************************************************************************
12** Utility functions used throughout sqlite.
13**
14** This file contains functions for allocating memory, comparing
15** strings, and stuff like that.
16**
17*/
18#include "sqliteInt.h"
19#include <stdarg.h>
20#ifdef SQLITE_HAVE_ISNAN
21# include <math.h>
22#endif
23
24/*
25** Routine needed to support the testcase() macro.
26*/
27#ifdef SQLITE_COVERAGE_TEST
28void sqlite3Coverage(int x){
29 static int dummy = 0;
30 dummy += x;
31}
32#endif
33
drh85c8f292010-01-13 17:39:53 +000034#ifndef SQLITE_OMIT_FLOATING_POINT
drhc81c11f2009-11-10 01:30:52 +000035/*
36** Return true if the floating point value is Not a Number (NaN).
37**
38** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
39** Otherwise, we have our own implementation that works on most systems.
40*/
41int sqlite3IsNaN(double x){
42 int rc; /* The value return */
43#if !defined(SQLITE_HAVE_ISNAN)
44 /*
45 ** Systems that support the isnan() library function should probably
46 ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
47 ** found that many systems do not have a working isnan() function so
48 ** this implementation is provided as an alternative.
49 **
50 ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
51 ** On the other hand, the use of -ffast-math comes with the following
52 ** warning:
53 **
54 ** This option [-ffast-math] should never be turned on by any
55 ** -O option since it can result in incorrect output for programs
56 ** which depend on an exact implementation of IEEE or ISO
57 ** rules/specifications for math functions.
58 **
59 ** Under MSVC, this NaN test may fail if compiled with a floating-
60 ** point precision mode other than /fp:precise. From the MSDN
61 ** documentation:
62 **
63 ** The compiler [with /fp:precise] will properly handle comparisons
64 ** involving NaN. For example, x != x evaluates to true if x is NaN
65 ** ...
66 */
67#ifdef __FAST_MATH__
68# error SQLite will not work correctly with the -ffast-math option of GCC.
69#endif
70 volatile double y = x;
71 volatile double z = y;
72 rc = (y!=z);
73#else /* if defined(SQLITE_HAVE_ISNAN) */
74 rc = isnan(x);
75#endif /* SQLITE_HAVE_ISNAN */
76 testcase( rc );
77 return rc;
78}
drh85c8f292010-01-13 17:39:53 +000079#endif /* SQLITE_OMIT_FLOATING_POINT */
drhc81c11f2009-11-10 01:30:52 +000080
81/*
82** Compute a string length that is limited to what can be stored in
83** lower 30 bits of a 32-bit signed integer.
84**
85** The value returned will never be negative. Nor will it ever be greater
86** than the actual length of the string. For very long strings (greater
87** than 1GiB) the value returned might be less than the true string length.
88*/
89int sqlite3Strlen30(const char *z){
90 const char *z2 = z;
91 if( z==0 ) return 0;
92 while( *z2 ){ z2++; }
93 return 0x3fffffff & (int)(z2 - z);
94}
95
96/*
97** Set the most recent error code and error string for the sqlite
98** handle "db". The error code is set to "err_code".
99**
100** If it is not NULL, string zFormat specifies the format of the
101** error string in the style of the printf functions: The following
102** format characters are allowed:
103**
104** %s Insert a string
105** %z A string that should be freed after use
106** %d Insert an integer
107** %T Insert a token
108** %S Insert the first element of a SrcList
109**
110** zFormat and any string tokens that follow it are assumed to be
111** encoded in UTF-8.
112**
113** To clear the most recent error for sqlite handle "db", sqlite3Error
114** should be called with err_code set to SQLITE_OK and zFormat set
115** to NULL.
116*/
117void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
118 if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
119 db->errCode = err_code;
120 if( zFormat ){
121 char *z;
122 va_list ap;
123 va_start(ap, zFormat);
124 z = sqlite3VMPrintf(db, zFormat, ap);
125 va_end(ap);
126 sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
127 }else{
128 sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
129 }
130 }
131}
132
133/*
134** Add an error message to pParse->zErrMsg and increment pParse->nErr.
135** The following formatting characters are allowed:
136**
137** %s Insert a string
138** %z A string that should be freed after use
139** %d Insert an integer
140** %T Insert a token
141** %S Insert the first element of a SrcList
142**
143** This function should be used to report any error that occurs whilst
144** compiling an SQL statement (i.e. within sqlite3_prepare()). The
145** last thing the sqlite3_prepare() function does is copy the error
146** stored by this function into the database handle using sqlite3Error().
147** Function sqlite3Error() should be used during statement execution
148** (sqlite3_step() etc.).
149*/
150void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
drha7564662010-02-22 19:32:31 +0000151 char *zMsg;
drhc81c11f2009-11-10 01:30:52 +0000152 va_list ap;
153 sqlite3 *db = pParse->db;
drhc81c11f2009-11-10 01:30:52 +0000154 va_start(ap, zFormat);
drha7564662010-02-22 19:32:31 +0000155 zMsg = sqlite3VMPrintf(db, zFormat, ap);
drhc81c11f2009-11-10 01:30:52 +0000156 va_end(ap);
drha7564662010-02-22 19:32:31 +0000157 if( db->suppressErr ){
158 sqlite3DbFree(db, zMsg);
159 }else{
160 pParse->nErr++;
161 sqlite3DbFree(db, pParse->zErrMsg);
162 pParse->zErrMsg = zMsg;
163 pParse->rc = SQLITE_ERROR;
164 sqlite3_log(SQLITE_ERROR, pParse->zErrMsg);
165 }
drhc81c11f2009-11-10 01:30:52 +0000166}
167
168/*
169** Convert an SQL-style quoted string into a normal string by removing
170** the quote characters. The conversion is done in-place. If the
171** input does not begin with a quote character, then this routine
172** is a no-op.
173**
174** The input string must be zero-terminated. A new zero-terminator
175** is added to the dequoted string.
176**
177** The return value is -1 if no dequoting occurs or the length of the
178** dequoted string, exclusive of the zero terminator, if dequoting does
179** occur.
180**
181** 2002-Feb-14: This routine is extended to remove MS-Access style
182** brackets from around identifers. For example: "[a-b-c]" becomes
183** "a-b-c".
184*/
185int sqlite3Dequote(char *z){
186 char quote;
187 int i, j;
188 if( z==0 ) return -1;
189 quote = z[0];
190 switch( quote ){
191 case '\'': break;
192 case '"': break;
193 case '`': break; /* For MySQL compatibility */
194 case '[': quote = ']'; break; /* For MS SqlServer compatibility */
195 default: return -1;
196 }
197 for(i=1, j=0; ALWAYS(z[i]); i++){
198 if( z[i]==quote ){
199 if( z[i+1]==quote ){
200 z[j++] = quote;
201 i++;
202 }else{
203 break;
204 }
205 }else{
206 z[j++] = z[i];
207 }
208 }
209 z[j] = 0;
210 return j;
211}
212
213/* Convenient short-hand */
214#define UpperToLower sqlite3UpperToLower
215
216/*
217** Some systems have stricmp(). Others have strcasecmp(). Because
218** there is no consistency, we will define our own.
219*/
220int sqlite3StrICmp(const char *zLeft, const char *zRight){
221 register unsigned char *a, *b;
222 a = (unsigned char *)zLeft;
223 b = (unsigned char *)zRight;
224 while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
225 return UpperToLower[*a] - UpperToLower[*b];
226}
227int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
228 register unsigned char *a, *b;
229 a = (unsigned char *)zLeft;
230 b = (unsigned char *)zRight;
231 while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
232 return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
233}
234
235/*
236** Return TRUE if z is a pure numeric string. Return FALSE and leave
237** *realnum unchanged if the string contains any character which is not
238** part of a number.
239**
240** If the string is pure numeric, set *realnum to TRUE if the string
241** contains the '.' character or an "E+000" style exponentiation suffix.
242** Otherwise set *realnum to FALSE. Note that just becaue *realnum is
243** false does not mean that the number can be successfully converted into
244** an integer - it might be too big.
245**
246** An empty string is considered non-numeric.
247*/
248int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
249 int incr = (enc==SQLITE_UTF8?1:2);
250 if( enc==SQLITE_UTF16BE ) z++;
251 if( *z=='-' || *z=='+' ) z += incr;
252 if( !sqlite3Isdigit(*z) ){
253 return 0;
254 }
255 z += incr;
256 *realnum = 0;
257 while( sqlite3Isdigit(*z) ){ z += incr; }
drh44dbca82010-01-13 04:22:20 +0000258#ifndef SQLITE_OMIT_FLOATING_POINT
drhc81c11f2009-11-10 01:30:52 +0000259 if( *z=='.' ){
260 z += incr;
261 if( !sqlite3Isdigit(*z) ) return 0;
262 while( sqlite3Isdigit(*z) ){ z += incr; }
263 *realnum = 1;
264 }
265 if( *z=='e' || *z=='E' ){
266 z += incr;
267 if( *z=='+' || *z=='-' ) z += incr;
268 if( !sqlite3Isdigit(*z) ) return 0;
269 while( sqlite3Isdigit(*z) ){ z += incr; }
270 *realnum = 1;
271 }
drh44dbca82010-01-13 04:22:20 +0000272#endif
drhc81c11f2009-11-10 01:30:52 +0000273 return *z==0;
274}
275
276/*
277** The string z[] is an ASCII representation of a real number.
278** Convert this string to a double.
279**
280** This routine assumes that z[] really is a valid number. If it
281** is not, the result is undefined.
282**
283** This routine is used instead of the library atof() function because
284** the library atof() might want to use "," as the decimal point instead
285** of "." depending on how locale is set. But that would cause problems
286** for SQL. So this routine always uses "." regardless of locale.
287*/
288int sqlite3AtoF(const char *z, double *pResult){
289#ifndef SQLITE_OMIT_FLOATING_POINT
290 const char *zBegin = z;
291 /* sign * significand * (10 ^ (esign * exponent)) */
292 int sign = 1; /* sign of significand */
293 i64 s = 0; /* significand */
294 int d = 0; /* adjust exponent for shifting decimal point */
295 int esign = 1; /* sign of exponent */
296 int e = 0; /* exponent */
297 double result;
298 int nDigits = 0;
299
300 /* skip leading spaces */
301 while( sqlite3Isspace(*z) ) z++;
302 /* get sign of significand */
303 if( *z=='-' ){
304 sign = -1;
305 z++;
306 }else if( *z=='+' ){
307 z++;
308 }
309 /* skip leading zeroes */
310 while( z[0]=='0' ) z++, nDigits++;
311
312 /* copy max significant digits to significand */
313 while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
314 s = s*10 + (*z - '0');
315 z++, nDigits++;
316 }
317 /* skip non-significant significand digits
318 ** (increase exponent by d to shift decimal left) */
319 while( sqlite3Isdigit(*z) ) z++, nDigits++, d++;
320
321 /* if decimal point is present */
322 if( *z=='.' ){
323 z++;
324 /* copy digits from after decimal to significand
325 ** (decrease exponent by d to shift decimal right) */
326 while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
327 s = s*10 + (*z - '0');
328 z++, nDigits++, d--;
329 }
330 /* skip non-significant digits */
331 while( sqlite3Isdigit(*z) ) z++, nDigits++;
332 }
333
334 /* if exponent is present */
335 if( *z=='e' || *z=='E' ){
336 z++;
337 /* get sign of exponent */
338 if( *z=='-' ){
339 esign = -1;
340 z++;
341 }else if( *z=='+' ){
342 z++;
343 }
344 /* copy digits to exponent */
345 while( sqlite3Isdigit(*z) ){
346 e = e*10 + (*z - '0');
347 z++;
348 }
349 }
350
351 /* adjust exponent by d, and update sign */
352 e = (e*esign) + d;
353 if( e<0 ) {
354 esign = -1;
355 e *= -1;
356 } else {
357 esign = 1;
358 }
359
360 /* if 0 significand */
361 if( !s ) {
362 /* In the IEEE 754 standard, zero is signed.
363 ** Add the sign if we've seen at least one digit */
364 result = (sign<0 && nDigits) ? -(double)0 : (double)0;
365 } else {
366 /* attempt to reduce exponent */
367 if( esign>0 ){
368 while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
369 }else{
370 while( !(s%10) && e>0 ) e--,s/=10;
371 }
372
373 /* adjust the sign of significand */
374 s = sign<0 ? -s : s;
375
376 /* if exponent, scale significand as appropriate
377 ** and store in result. */
378 if( e ){
379 double scale = 1.0;
380 /* attempt to handle extremely small/large numbers better */
381 if( e>307 && e<342 ){
382 while( e%308 ) { scale *= 1.0e+1; e -= 1; }
383 if( esign<0 ){
384 result = s / scale;
385 result /= 1.0e+308;
386 }else{
387 result = s * scale;
388 result *= 1.0e+308;
389 }
390 }else{
391 /* 1.0e+22 is the largest power of 10 than can be
392 ** represented exactly. */
393 while( e%22 ) { scale *= 1.0e+1; e -= 1; }
394 while( e>0 ) { scale *= 1.0e+22; e -= 22; }
395 if( esign<0 ){
396 result = s / scale;
397 }else{
398 result = s * scale;
399 }
400 }
401 } else {
402 result = (double)s;
403 }
404 }
405
406 /* store the result */
407 *pResult = result;
408
409 /* return number of characters used */
410 return (int)(z - zBegin);
411#else
412 return sqlite3Atoi64(z, pResult);
413#endif /* SQLITE_OMIT_FLOATING_POINT */
414}
415
416/*
417** Compare the 19-character string zNum against the text representation
418** value 2^63: 9223372036854775808. Return negative, zero, or positive
419** if zNum is less than, equal to, or greater than the string.
420**
421** Unlike memcmp() this routine is guaranteed to return the difference
422** in the values of the last digit if the only difference is in the
423** last digit. So, for example,
424**
425** compare2pow63("9223372036854775800")
426**
427** will return -8.
428*/
429static int compare2pow63(const char *zNum){
430 int c;
431 c = memcmp(zNum,"922337203685477580",18)*10;
432 if( c==0 ){
433 c = zNum[18] - '8';
drh44dbca82010-01-13 04:22:20 +0000434 testcase( c==(-1) );
435 testcase( c==0 );
436 testcase( c==(+1) );
drhc81c11f2009-11-10 01:30:52 +0000437 }
438 return c;
439}
440
441
442/*
443** Return TRUE if zNum is a 64-bit signed integer and write
444** the value of the integer into *pNum. If zNum is not an integer
445** or is an integer that is too large to be expressed with 64 bits,
446** then return false.
447**
448** When this routine was originally written it dealt with only
449** 32-bit numbers. At that time, it was much faster than the
450** atoi() library routine in RedHat 7.2.
451*/
452int sqlite3Atoi64(const char *zNum, i64 *pNum){
453 i64 v = 0;
454 int neg;
455 int i, c;
456 const char *zStart;
457 while( sqlite3Isspace(*zNum) ) zNum++;
458 if( *zNum=='-' ){
459 neg = 1;
460 zNum++;
461 }else if( *zNum=='+' ){
462 neg = 0;
463 zNum++;
464 }else{
465 neg = 0;
466 }
467 zStart = zNum;
468 while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
469 for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
470 v = v*10 + c - '0';
471 }
472 *pNum = neg ? -v : v;
drh44dbca82010-01-13 04:22:20 +0000473 testcase( i==18 );
474 testcase( i==19 );
475 testcase( i==20 );
drhc81c11f2009-11-10 01:30:52 +0000476 if( c!=0 || (i==0 && zStart==zNum) || i>19 ){
477 /* zNum is empty or contains non-numeric text or is longer
478 ** than 19 digits (thus guaranting that it is too large) */
479 return 0;
480 }else if( i<19 ){
481 /* Less than 19 digits, so we know that it fits in 64 bits */
482 return 1;
483 }else{
484 /* 19-digit numbers must be no larger than 9223372036854775807 if positive
485 ** or 9223372036854775808 if negative. Note that 9223372036854665808
486 ** is 2^63. */
487 return compare2pow63(zNum)<neg;
488 }
489}
490
491/*
492** The string zNum represents an unsigned integer. The zNum string
493** consists of one or more digit characters and is terminated by
494** a zero character. Any stray characters in zNum result in undefined
495** behavior.
496**
497** If the unsigned integer that zNum represents will fit in a
498** 64-bit signed integer, return TRUE. Otherwise return FALSE.
499**
500** If the negFlag parameter is true, that means that zNum really represents
501** a negative number. (The leading "-" is omitted from zNum.) This
502** parameter is needed to determine a boundary case. A string
503** of "9223373036854775808" returns false if negFlag is false or true
504** if negFlag is true.
505**
506** Leading zeros are ignored.
507*/
508int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
509 int i;
510 int neg = 0;
511
512 assert( zNum[0]>='0' && zNum[0]<='9' ); /* zNum is an unsigned number */
513
514 if( negFlag ) neg = 1-neg;
515 while( *zNum=='0' ){
516 zNum++; /* Skip leading zeros. Ticket #2454 */
517 }
518 for(i=0; zNum[i]; i++){ assert( zNum[i]>='0' && zNum[i]<='9' ); }
drh44dbca82010-01-13 04:22:20 +0000519 testcase( i==18 );
520 testcase( i==19 );
521 testcase( i==20 );
drhc81c11f2009-11-10 01:30:52 +0000522 if( i<19 ){
523 /* Guaranteed to fit if less than 19 digits */
524 return 1;
525 }else if( i>19 ){
526 /* Guaranteed to be too big if greater than 19 digits */
527 return 0;
528 }else{
529 /* Compare against 2^63. */
530 return compare2pow63(zNum)<neg;
531 }
532}
533
534/*
535** If zNum represents an integer that will fit in 32-bits, then set
536** *pValue to that integer and return true. Otherwise return false.
537**
538** Any non-numeric characters that following zNum are ignored.
539** This is different from sqlite3Atoi64() which requires the
540** input number to be zero-terminated.
541*/
542int sqlite3GetInt32(const char *zNum, int *pValue){
543 sqlite_int64 v = 0;
544 int i, c;
545 int neg = 0;
546 if( zNum[0]=='-' ){
547 neg = 1;
548 zNum++;
549 }else if( zNum[0]=='+' ){
550 zNum++;
551 }
552 while( zNum[0]=='0' ) zNum++;
553 for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
554 v = v*10 + c;
555 }
556
557 /* The longest decimal representation of a 32 bit integer is 10 digits:
558 **
559 ** 1234567890
560 ** 2^31 -> 2147483648
561 */
drh44dbca82010-01-13 04:22:20 +0000562 testcase( i==10 );
drhc81c11f2009-11-10 01:30:52 +0000563 if( i>10 ){
564 return 0;
565 }
drh44dbca82010-01-13 04:22:20 +0000566 testcase( v-neg==2147483647 );
drhc81c11f2009-11-10 01:30:52 +0000567 if( v-neg>2147483647 ){
568 return 0;
569 }
570 if( neg ){
571 v = -v;
572 }
573 *pValue = (int)v;
574 return 1;
575}
576
577/*
578** The variable-length integer encoding is as follows:
579**
580** KEY:
581** A = 0xxxxxxx 7 bits of data and one flag bit
582** B = 1xxxxxxx 7 bits of data and one flag bit
583** C = xxxxxxxx 8 bits of data
584**
585** 7 bits - A
586** 14 bits - BA
587** 21 bits - BBA
588** 28 bits - BBBA
589** 35 bits - BBBBA
590** 42 bits - BBBBBA
591** 49 bits - BBBBBBA
592** 56 bits - BBBBBBBA
593** 64 bits - BBBBBBBBC
594*/
595
596/*
597** Write a 64-bit variable-length integer to memory starting at p[0].
598** The length of data write will be between 1 and 9 bytes. The number
599** of bytes written is returned.
600**
601** A variable-length integer consists of the lower 7 bits of each byte
602** for all bytes that have the 8th bit set and one byte with the 8th
603** bit clear. Except, if we get to the 9th byte, it stores the full
604** 8 bits and is the last byte.
605*/
606int sqlite3PutVarint(unsigned char *p, u64 v){
607 int i, j, n;
608 u8 buf[10];
609 if( v & (((u64)0xff000000)<<32) ){
610 p[8] = (u8)v;
611 v >>= 8;
612 for(i=7; i>=0; i--){
613 p[i] = (u8)((v & 0x7f) | 0x80);
614 v >>= 7;
615 }
616 return 9;
617 }
618 n = 0;
619 do{
620 buf[n++] = (u8)((v & 0x7f) | 0x80);
621 v >>= 7;
622 }while( v!=0 );
623 buf[0] &= 0x7f;
624 assert( n<=9 );
625 for(i=0, j=n-1; j>=0; j--, i++){
626 p[i] = buf[j];
627 }
628 return n;
629}
630
631/*
632** This routine is a faster version of sqlite3PutVarint() that only
633** works for 32-bit positive integers and which is optimized for
634** the common case of small integers. A MACRO version, putVarint32,
635** is provided which inlines the single-byte case. All code should use
636** the MACRO version as this function assumes the single-byte case has
637** already been handled.
638*/
639int sqlite3PutVarint32(unsigned char *p, u32 v){
640#ifndef putVarint32
641 if( (v & ~0x7f)==0 ){
642 p[0] = v;
643 return 1;
644 }
645#endif
646 if( (v & ~0x3fff)==0 ){
647 p[0] = (u8)((v>>7) | 0x80);
648 p[1] = (u8)(v & 0x7f);
649 return 2;
650 }
651 return sqlite3PutVarint(p, v);
652}
653
654/*
655** Read a 64-bit variable-length integer from memory starting at p[0].
656** Return the number of bytes read. The value is stored in *v.
657*/
658u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
659 u32 a,b,s;
660
661 a = *p;
662 /* a: p0 (unmasked) */
663 if (!(a&0x80))
664 {
665 *v = a;
666 return 1;
667 }
668
669 p++;
670 b = *p;
671 /* b: p1 (unmasked) */
672 if (!(b&0x80))
673 {
674 a &= 0x7f;
675 a = a<<7;
676 a |= b;
677 *v = a;
678 return 2;
679 }
680
681 p++;
682 a = a<<14;
683 a |= *p;
684 /* a: p0<<14 | p2 (unmasked) */
685 if (!(a&0x80))
686 {
687 a &= (0x7f<<14)|(0x7f);
688 b &= 0x7f;
689 b = b<<7;
690 a |= b;
691 *v = a;
692 return 3;
693 }
694
695 /* CSE1 from below */
696 a &= (0x7f<<14)|(0x7f);
697 p++;
698 b = b<<14;
699 b |= *p;
700 /* b: p1<<14 | p3 (unmasked) */
701 if (!(b&0x80))
702 {
703 b &= (0x7f<<14)|(0x7f);
704 /* moved CSE1 up */
705 /* a &= (0x7f<<14)|(0x7f); */
706 a = a<<7;
707 a |= b;
708 *v = a;
709 return 4;
710 }
711
712 /* a: p0<<14 | p2 (masked) */
713 /* b: p1<<14 | p3 (unmasked) */
714 /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
715 /* moved CSE1 up */
716 /* a &= (0x7f<<14)|(0x7f); */
717 b &= (0x7f<<14)|(0x7f);
718 s = a;
719 /* s: p0<<14 | p2 (masked) */
720
721 p++;
722 a = a<<14;
723 a |= *p;
724 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
725 if (!(a&0x80))
726 {
727 /* we can skip these cause they were (effectively) done above in calc'ing s */
728 /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
729 /* b &= (0x7f<<14)|(0x7f); */
730 b = b<<7;
731 a |= b;
732 s = s>>18;
733 *v = ((u64)s)<<32 | a;
734 return 5;
735 }
736
737 /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
738 s = s<<7;
739 s |= b;
740 /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
741
742 p++;
743 b = b<<14;
744 b |= *p;
745 /* b: p1<<28 | p3<<14 | p5 (unmasked) */
746 if (!(b&0x80))
747 {
748 /* we can skip this cause it was (effectively) done above in calc'ing s */
749 /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
750 a &= (0x7f<<14)|(0x7f);
751 a = a<<7;
752 a |= b;
753 s = s>>18;
754 *v = ((u64)s)<<32 | a;
755 return 6;
756 }
757
758 p++;
759 a = a<<14;
760 a |= *p;
761 /* a: p2<<28 | p4<<14 | p6 (unmasked) */
762 if (!(a&0x80))
763 {
764 a &= (0x1f<<28)|(0x7f<<14)|(0x7f);
765 b &= (0x7f<<14)|(0x7f);
766 b = b<<7;
767 a |= b;
768 s = s>>11;
769 *v = ((u64)s)<<32 | a;
770 return 7;
771 }
772
773 /* CSE2 from below */
774 a &= (0x7f<<14)|(0x7f);
775 p++;
776 b = b<<14;
777 b |= *p;
778 /* b: p3<<28 | p5<<14 | p7 (unmasked) */
779 if (!(b&0x80))
780 {
781 b &= (0x1f<<28)|(0x7f<<14)|(0x7f);
782 /* moved CSE2 up */
783 /* a &= (0x7f<<14)|(0x7f); */
784 a = a<<7;
785 a |= b;
786 s = s>>4;
787 *v = ((u64)s)<<32 | a;
788 return 8;
789 }
790
791 p++;
792 a = a<<15;
793 a |= *p;
794 /* a: p4<<29 | p6<<15 | p8 (unmasked) */
795
796 /* moved CSE2 up */
797 /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
798 b &= (0x7f<<14)|(0x7f);
799 b = b<<8;
800 a |= b;
801
802 s = s<<4;
803 b = p[-4];
804 b &= 0x7f;
805 b = b>>3;
806 s |= b;
807
808 *v = ((u64)s)<<32 | a;
809
810 return 9;
811}
812
813/*
814** Read a 32-bit variable-length integer from memory starting at p[0].
815** Return the number of bytes read. The value is stored in *v.
816**
817** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
818** integer, then set *v to 0xffffffff.
819**
820** A MACRO version, getVarint32, is provided which inlines the
821** single-byte case. All code should use the MACRO version as
822** this function assumes the single-byte case has already been handled.
823*/
824u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
825 u32 a,b;
826
827 /* The 1-byte case. Overwhelmingly the most common. Handled inline
828 ** by the getVarin32() macro */
829 a = *p;
830 /* a: p0 (unmasked) */
831#ifndef getVarint32
832 if (!(a&0x80))
833 {
834 /* Values between 0 and 127 */
835 *v = a;
836 return 1;
837 }
838#endif
839
840 /* The 2-byte case */
841 p++;
842 b = *p;
843 /* b: p1 (unmasked) */
844 if (!(b&0x80))
845 {
846 /* Values between 128 and 16383 */
847 a &= 0x7f;
848 a = a<<7;
849 *v = a | b;
850 return 2;
851 }
852
853 /* The 3-byte case */
854 p++;
855 a = a<<14;
856 a |= *p;
857 /* a: p0<<14 | p2 (unmasked) */
858 if (!(a&0x80))
859 {
860 /* Values between 16384 and 2097151 */
861 a &= (0x7f<<14)|(0x7f);
862 b &= 0x7f;
863 b = b<<7;
864 *v = a | b;
865 return 3;
866 }
867
868 /* A 32-bit varint is used to store size information in btrees.
869 ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
870 ** A 3-byte varint is sufficient, for example, to record the size
871 ** of a 1048569-byte BLOB or string.
872 **
873 ** We only unroll the first 1-, 2-, and 3- byte cases. The very
874 ** rare larger cases can be handled by the slower 64-bit varint
875 ** routine.
876 */
877#if 1
878 {
879 u64 v64;
880 u8 n;
881
882 p -= 2;
883 n = sqlite3GetVarint(p, &v64);
884 assert( n>3 && n<=9 );
885 if( (v64 & SQLITE_MAX_U32)!=v64 ){
886 *v = 0xffffffff;
887 }else{
888 *v = (u32)v64;
889 }
890 return n;
891 }
892
893#else
894 /* For following code (kept for historical record only) shows an
895 ** unrolling for the 3- and 4-byte varint cases. This code is
896 ** slightly faster, but it is also larger and much harder to test.
897 */
898 p++;
899 b = b<<14;
900 b |= *p;
901 /* b: p1<<14 | p3 (unmasked) */
902 if (!(b&0x80))
903 {
904 /* Values between 2097152 and 268435455 */
905 b &= (0x7f<<14)|(0x7f);
906 a &= (0x7f<<14)|(0x7f);
907 a = a<<7;
908 *v = a | b;
909 return 4;
910 }
911
912 p++;
913 a = a<<14;
914 a |= *p;
915 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
916 if (!(a&0x80))
917 {
918 /* Walues between 268435456 and 34359738367 */
919 a &= (0x1f<<28)|(0x7f<<14)|(0x7f);
920 b &= (0x1f<<28)|(0x7f<<14)|(0x7f);
921 b = b<<7;
922 *v = a | b;
923 return 5;
924 }
925
926 /* We can only reach this point when reading a corrupt database
927 ** file. In that case we are not in any hurry. Use the (relatively
928 ** slow) general-purpose sqlite3GetVarint() routine to extract the
929 ** value. */
930 {
931 u64 v64;
932 u8 n;
933
934 p -= 4;
935 n = sqlite3GetVarint(p, &v64);
936 assert( n>5 && n<=9 );
937 *v = (u32)v64;
938 return n;
939 }
940#endif
941}
942
943/*
944** Return the number of bytes that will be needed to store the given
945** 64-bit integer.
946*/
947int sqlite3VarintLen(u64 v){
948 int i = 0;
949 do{
950 i++;
951 v >>= 7;
952 }while( v!=0 && ALWAYS(i<9) );
953 return i;
954}
955
956
957/*
958** Read or write a four-byte big-endian integer value.
959*/
960u32 sqlite3Get4byte(const u8 *p){
961 return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
962}
963void sqlite3Put4byte(unsigned char *p, u32 v){
964 p[0] = (u8)(v>>24);
965 p[1] = (u8)(v>>16);
966 p[2] = (u8)(v>>8);
967 p[3] = (u8)v;
968}
969
970
971
972#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
973/*
974** Translate a single byte of Hex into an integer.
975** This routine only works if h really is a valid hexadecimal
976** character: 0..9a..fA..F
977*/
978static u8 hexToInt(int h){
979 assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
980#ifdef SQLITE_ASCII
981 h += 9*(1&(h>>6));
982#endif
983#ifdef SQLITE_EBCDIC
984 h += 9*(1&~(h>>4));
985#endif
986 return (u8)(h & 0xf);
987}
988#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
989
990#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
991/*
992** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
993** value. Return a pointer to its binary value. Space to hold the
994** binary value has been obtained from malloc and must be freed by
995** the calling routine.
996*/
997void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
998 char *zBlob;
999 int i;
1000
1001 zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
1002 n--;
1003 if( zBlob ){
1004 for(i=0; i<n; i+=2){
1005 zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
1006 }
1007 zBlob[i/2] = 0;
1008 }
1009 return zBlob;
1010}
1011#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
1012
1013
1014/*
drhc81c11f2009-11-10 01:30:52 +00001015** Check to make sure we have a valid db pointer. This test is not
1016** foolproof but it does provide some measure of protection against
1017** misuse of the interface such as passing in db pointers that are
1018** NULL or which have been previously closed. If this routine returns
1019** 1 it means that the db pointer is valid and 0 if it should not be
1020** dereferenced for any reason. The calling function should invoke
1021** SQLITE_MISUSE immediately.
1022**
1023** sqlite3SafetyCheckOk() requires that the db pointer be valid for
1024** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
1025** open properly and is not fit for general use but which can be
1026** used as an argument to sqlite3_errmsg() or sqlite3_close().
1027*/
1028int sqlite3SafetyCheckOk(sqlite3 *db){
1029 u32 magic;
1030 if( db==0 ) return 0;
1031 magic = db->magic;
drh9978c972010-02-23 17:36:32 +00001032 if( magic!=SQLITE_MAGIC_OPEN ){
drhc81c11f2009-11-10 01:30:52 +00001033 return 0;
1034 }else{
1035 return 1;
1036 }
1037}
1038int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
1039 u32 magic;
1040 magic = db->magic;
1041 if( magic!=SQLITE_MAGIC_SICK &&
1042 magic!=SQLITE_MAGIC_OPEN &&
1043 magic!=SQLITE_MAGIC_BUSY ) return 0;
1044 return 1;
1045}