PageRenderTime 85ms CodeModel.GetById 52ms RepoModel.GetById 0ms app.codeStats 0ms

/usr/src/lib/libsqlite/src/util.c

https://bitbucket.org/a3217055/illumos-2
C | 1138 lines | 994 code | 24 blank | 120 comment | 49 complexity | 6539e8b70c2c5394fee95624ed4c69c6 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, MPL-2.0-no-copyleft-exception, AGPL-3.0, BSD-3-Clause, LGPL-2.0, 0BSD, BSD-2-Clause, BSD-3-Clause-No-Nuclear-License-2014, AGPL-1.0, GPL-2.0
  1. #pragma ident "%Z%%M% %I% %E% SMI"
  2. /*
  3. ** 2001 September 15
  4. **
  5. ** The author disclaims copyright to this source code. In place of
  6. ** a legal notice, here is a blessing:
  7. **
  8. ** May you do good and not evil.
  9. ** May you find forgiveness for yourself and forgive others.
  10. ** May you share freely, never taking more than you give.
  11. **
  12. *************************************************************************
  13. ** Utility functions used throughout sqlite.
  14. **
  15. ** This file contains functions for allocating memory, comparing
  16. ** strings, and stuff like that.
  17. **
  18. ** $Id: util.c,v 1.74.2.1 2004/07/15 13:08:41 drh Exp $
  19. */
  20. #include "sqliteInt.h"
  21. #include <stdarg.h>
  22. #include <ctype.h>
  23. /*
  24. ** If malloc() ever fails, this global variable gets set to 1.
  25. ** This causes the library to abort and never again function.
  26. */
  27. int sqlite_malloc_failed = 0;
  28. /*
  29. ** If MEMORY_DEBUG is defined, then use versions of malloc() and
  30. ** free() that track memory usage and check for buffer overruns.
  31. */
  32. #ifdef MEMORY_DEBUG
  33. /*
  34. ** For keeping track of the number of mallocs and frees. This
  35. ** is used to check for memory leaks.
  36. */
  37. int sqlite_nMalloc; /* Number of sqliteMalloc() calls */
  38. int sqlite_nFree; /* Number of sqliteFree() calls */
  39. int sqlite_iMallocFail; /* Fail sqliteMalloc() after this many calls */
  40. #if MEMORY_DEBUG>1
  41. static int memcnt = 0;
  42. #endif
  43. /*
  44. ** Number of 32-bit guard words
  45. */
  46. #define N_GUARD 1
  47. /*
  48. ** Allocate new memory and set it to zero. Return NULL if
  49. ** no memory is available.
  50. */
  51. void *sqliteMalloc_(int n, int bZero, char *zFile, int line){
  52. void *p;
  53. int *pi;
  54. int i, k;
  55. if( sqlite_iMallocFail>=0 ){
  56. sqlite_iMallocFail--;
  57. if( sqlite_iMallocFail==0 ){
  58. sqlite_malloc_failed++;
  59. #if MEMORY_DEBUG>1
  60. fprintf(stderr,"**** failed to allocate %d bytes at %s:%d\n",
  61. n, zFile,line);
  62. #endif
  63. sqlite_iMallocFail--;
  64. return 0;
  65. }
  66. }
  67. if( n==0 ) return 0;
  68. k = (n+sizeof(int)-1)/sizeof(int);
  69. pi = malloc( (N_GUARD*2+1+k)*sizeof(int));
  70. if( pi==0 ){
  71. sqlite_malloc_failed++;
  72. return 0;
  73. }
  74. sqlite_nMalloc++;
  75. for(i=0; i<N_GUARD; i++) pi[i] = 0xdead1122;
  76. pi[N_GUARD] = n;
  77. for(i=0; i<N_GUARD; i++) pi[k+1+N_GUARD+i] = 0xdead3344;
  78. p = &pi[N_GUARD+1];
  79. memset(p, bZero==0, n);
  80. #if MEMORY_DEBUG>1
  81. fprintf(stderr,"%06d malloc %d bytes at 0x%x from %s:%d\n",
  82. ++memcnt, n, (int)p, zFile,line);
  83. #endif
  84. return p;
  85. }
  86. /*
  87. ** Check to see if the given pointer was obtained from sqliteMalloc()
  88. ** and is able to hold at least N bytes. Raise an exception if this
  89. ** is not the case.
  90. **
  91. ** This routine is used for testing purposes only.
  92. */
  93. void sqliteCheckMemory(void *p, int N){
  94. int *pi = p;
  95. int n, i, k;
  96. pi -= N_GUARD+1;
  97. for(i=0; i<N_GUARD; i++){
  98. assert( pi[i]==0xdead1122 );
  99. }
  100. n = pi[N_GUARD];
  101. assert( N>=0 && N<n );
  102. k = (n+sizeof(int)-1)/sizeof(int);
  103. for(i=0; i<N_GUARD; i++){
  104. assert( pi[k+N_GUARD+1+i]==0xdead3344 );
  105. }
  106. }
  107. /*
  108. ** Free memory previously obtained from sqliteMalloc()
  109. */
  110. void sqliteFree_(void *p, char *zFile, int line){
  111. if( p ){
  112. int *pi, i, k, n;
  113. pi = p;
  114. pi -= N_GUARD+1;
  115. sqlite_nFree++;
  116. for(i=0; i<N_GUARD; i++){
  117. if( pi[i]!=0xdead1122 ){
  118. fprintf(stderr,"Low-end memory corruption at 0x%x\n", (int)p);
  119. return;
  120. }
  121. }
  122. n = pi[N_GUARD];
  123. k = (n+sizeof(int)-1)/sizeof(int);
  124. for(i=0; i<N_GUARD; i++){
  125. if( pi[k+N_GUARD+1+i]!=0xdead3344 ){
  126. fprintf(stderr,"High-end memory corruption at 0x%x\n", (int)p);
  127. return;
  128. }
  129. }
  130. memset(pi, 0xff, (k+N_GUARD*2+1)*sizeof(int));
  131. #if MEMORY_DEBUG>1
  132. fprintf(stderr,"%06d free %d bytes at 0x%x from %s:%d\n",
  133. ++memcnt, n, (int)p, zFile,line);
  134. #endif
  135. free(pi);
  136. }
  137. }
  138. /*
  139. ** Resize a prior allocation. If p==0, then this routine
  140. ** works just like sqliteMalloc(). If n==0, then this routine
  141. ** works just like sqliteFree().
  142. */
  143. void *sqliteRealloc_(void *oldP, int n, char *zFile, int line){
  144. int *oldPi, *pi, i, k, oldN, oldK;
  145. void *p;
  146. if( oldP==0 ){
  147. return sqliteMalloc_(n,1,zFile,line);
  148. }
  149. if( n==0 ){
  150. sqliteFree_(oldP,zFile,line);
  151. return 0;
  152. }
  153. oldPi = oldP;
  154. oldPi -= N_GUARD+1;
  155. if( oldPi[0]!=0xdead1122 ){
  156. fprintf(stderr,"Low-end memory corruption in realloc at 0x%x\n", (int)oldP);
  157. return 0;
  158. }
  159. oldN = oldPi[N_GUARD];
  160. oldK = (oldN+sizeof(int)-1)/sizeof(int);
  161. for(i=0; i<N_GUARD; i++){
  162. if( oldPi[oldK+N_GUARD+1+i]!=0xdead3344 ){
  163. fprintf(stderr,"High-end memory corruption in realloc at 0x%x\n",
  164. (int)oldP);
  165. return 0;
  166. }
  167. }
  168. k = (n + sizeof(int) - 1)/sizeof(int);
  169. pi = malloc( (k+N_GUARD*2+1)*sizeof(int) );
  170. if( pi==0 ){
  171. sqlite_malloc_failed++;
  172. return 0;
  173. }
  174. for(i=0; i<N_GUARD; i++) pi[i] = 0xdead1122;
  175. pi[N_GUARD] = n;
  176. for(i=0; i<N_GUARD; i++) pi[k+N_GUARD+1+i] = 0xdead3344;
  177. p = &pi[N_GUARD+1];
  178. memcpy(p, oldP, n>oldN ? oldN : n);
  179. if( n>oldN ){
  180. memset(&((char*)p)[oldN], 0, n-oldN);
  181. }
  182. memset(oldPi, 0xab, (oldK+N_GUARD+2)*sizeof(int));
  183. free(oldPi);
  184. #if MEMORY_DEBUG>1
  185. fprintf(stderr,"%06d realloc %d to %d bytes at 0x%x to 0x%x at %s:%d\n",
  186. ++memcnt, oldN, n, (int)oldP, (int)p, zFile, line);
  187. #endif
  188. return p;
  189. }
  190. /*
  191. ** Make a duplicate of a string into memory obtained from malloc()
  192. ** Free the original string using sqliteFree().
  193. **
  194. ** This routine is called on all strings that are passed outside of
  195. ** the SQLite library. That way clients can free the string using free()
  196. ** rather than having to call sqliteFree().
  197. */
  198. void sqliteStrRealloc(char **pz){
  199. char *zNew;
  200. if( pz==0 || *pz==0 ) return;
  201. zNew = malloc( strlen(*pz) + 1 );
  202. if( zNew==0 ){
  203. sqlite_malloc_failed++;
  204. sqliteFree(*pz);
  205. *pz = 0;
  206. }
  207. strcpy(zNew, *pz);
  208. sqliteFree(*pz);
  209. *pz = zNew;
  210. }
  211. /*
  212. ** Make a copy of a string in memory obtained from sqliteMalloc()
  213. */
  214. char *sqliteStrDup_(const char *z, char *zFile, int line){
  215. char *zNew;
  216. if( z==0 ) return 0;
  217. zNew = sqliteMalloc_(strlen(z)+1, 0, zFile, line);
  218. if( zNew ) strcpy(zNew, z);
  219. return zNew;
  220. }
  221. char *sqliteStrNDup_(const char *z, int n, char *zFile, int line){
  222. char *zNew;
  223. if( z==0 ) return 0;
  224. zNew = sqliteMalloc_(n+1, 0, zFile, line);
  225. if( zNew ){
  226. memcpy(zNew, z, n);
  227. zNew[n] = 0;
  228. }
  229. return zNew;
  230. }
  231. #endif /* MEMORY_DEBUG */
  232. /*
  233. ** The following versions of malloc() and free() are for use in a
  234. ** normal build.
  235. */
  236. #if !defined(MEMORY_DEBUG)
  237. /*
  238. ** Allocate new memory and set it to zero. Return NULL if
  239. ** no memory is available. See also sqliteMallocRaw().
  240. */
  241. void *sqliteMalloc(int n){
  242. void *p;
  243. if( (p = malloc(n))==0 ){
  244. if( n>0 ) sqlite_malloc_failed++;
  245. }else{
  246. memset(p, 0, n);
  247. }
  248. return p;
  249. }
  250. /*
  251. ** Allocate new memory but do not set it to zero. Return NULL if
  252. ** no memory is available. See also sqliteMalloc().
  253. */
  254. void *sqliteMallocRaw(int n){
  255. void *p;
  256. if( (p = malloc(n))==0 ){
  257. if( n>0 ) sqlite_malloc_failed++;
  258. }
  259. return p;
  260. }
  261. /*
  262. ** Free memory previously obtained from sqliteMalloc()
  263. */
  264. void sqliteFree(void *p){
  265. if( p ){
  266. free(p);
  267. }
  268. }
  269. /*
  270. ** Resize a prior allocation. If p==0, then this routine
  271. ** works just like sqliteMalloc(). If n==0, then this routine
  272. ** works just like sqliteFree().
  273. */
  274. void *sqliteRealloc(void *p, int n){
  275. void *p2;
  276. if( p==0 ){
  277. return sqliteMalloc(n);
  278. }
  279. if( n==0 ){
  280. sqliteFree(p);
  281. return 0;
  282. }
  283. p2 = realloc(p, n);
  284. if( p2==0 ){
  285. sqlite_malloc_failed++;
  286. }
  287. return p2;
  288. }
  289. /*
  290. ** Make a copy of a string in memory obtained from sqliteMalloc()
  291. */
  292. char *sqliteStrDup(const char *z){
  293. char *zNew;
  294. if( z==0 ) return 0;
  295. zNew = sqliteMallocRaw(strlen(z)+1);
  296. if( zNew ) strcpy(zNew, z);
  297. return zNew;
  298. }
  299. char *sqliteStrNDup(const char *z, int n){
  300. char *zNew;
  301. if( z==0 ) return 0;
  302. zNew = sqliteMallocRaw(n+1);
  303. if( zNew ){
  304. memcpy(zNew, z, n);
  305. zNew[n] = 0;
  306. }
  307. return zNew;
  308. }
  309. #endif /* !defined(MEMORY_DEBUG) */
  310. /*
  311. ** Create a string from the 2nd and subsequent arguments (up to the
  312. ** first NULL argument), store the string in memory obtained from
  313. ** sqliteMalloc() and make the pointer indicated by the 1st argument
  314. ** point to that string. The 1st argument must either be NULL or
  315. ** point to memory obtained from sqliteMalloc().
  316. */
  317. void sqliteSetString(char **pz, const char *zFirst, ...){
  318. va_list ap;
  319. int nByte;
  320. const char *z;
  321. char *zResult;
  322. if( pz==0 ) return;
  323. nByte = strlen(zFirst) + 1;
  324. va_start(ap, zFirst);
  325. while( (z = va_arg(ap, const char*))!=0 ){
  326. nByte += strlen(z);
  327. }
  328. va_end(ap);
  329. sqliteFree(*pz);
  330. *pz = zResult = sqliteMallocRaw( nByte );
  331. if( zResult==0 ){
  332. return;
  333. }
  334. strcpy(zResult, zFirst);
  335. zResult += strlen(zResult);
  336. va_start(ap, zFirst);
  337. while( (z = va_arg(ap, const char*))!=0 ){
  338. strcpy(zResult, z);
  339. zResult += strlen(zResult);
  340. }
  341. va_end(ap);
  342. #ifdef MEMORY_DEBUG
  343. #if MEMORY_DEBUG>1
  344. fprintf(stderr,"string at 0x%x is %s\n", (int)*pz, *pz);
  345. #endif
  346. #endif
  347. }
  348. /*
  349. ** Works like sqliteSetString, but each string is now followed by
  350. ** a length integer which specifies how much of the source string
  351. ** to copy (in bytes). -1 means use the whole string. The 1st
  352. ** argument must either be NULL or point to memory obtained from
  353. ** sqliteMalloc().
  354. */
  355. void sqliteSetNString(char **pz, ...){
  356. va_list ap;
  357. int nByte;
  358. const char *z;
  359. char *zResult;
  360. int n;
  361. if( pz==0 ) return;
  362. nByte = 0;
  363. va_start(ap, pz);
  364. while( (z = va_arg(ap, const char*))!=0 ){
  365. n = va_arg(ap, int);
  366. if( n<=0 ) n = strlen(z);
  367. nByte += n;
  368. }
  369. va_end(ap);
  370. sqliteFree(*pz);
  371. *pz = zResult = sqliteMallocRaw( nByte + 1 );
  372. if( zResult==0 ) return;
  373. va_start(ap, pz);
  374. while( (z = va_arg(ap, const char*))!=0 ){
  375. n = va_arg(ap, int);
  376. if( n<=0 ) n = strlen(z);
  377. strncpy(zResult, z, n);
  378. zResult += n;
  379. }
  380. *zResult = 0;
  381. #ifdef MEMORY_DEBUG
  382. #if MEMORY_DEBUG>1
  383. fprintf(stderr,"string at 0x%x is %s\n", (int)*pz, *pz);
  384. #endif
  385. #endif
  386. va_end(ap);
  387. }
  388. /*
  389. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  390. ** The following formatting characters are allowed:
  391. **
  392. ** %s Insert a string
  393. ** %z A string that should be freed after use
  394. ** %d Insert an integer
  395. ** %T Insert a token
  396. ** %S Insert the first element of a SrcList
  397. */
  398. void sqliteErrorMsg(Parse *pParse, const char *zFormat, ...){
  399. va_list ap;
  400. pParse->nErr++;
  401. sqliteFree(pParse->zErrMsg);
  402. va_start(ap, zFormat);
  403. pParse->zErrMsg = sqliteVMPrintf(zFormat, ap);
  404. va_end(ap);
  405. }
  406. /*
  407. ** Convert an SQL-style quoted string into a normal string by removing
  408. ** the quote characters. The conversion is done in-place. If the
  409. ** input does not begin with a quote character, then this routine
  410. ** is a no-op.
  411. **
  412. ** 2002-Feb-14: This routine is extended to remove MS-Access style
  413. ** brackets from around identifers. For example: "[a-b-c]" becomes
  414. ** "a-b-c".
  415. */
  416. void sqliteDequote(char *z){
  417. int quote;
  418. int i, j;
  419. if( z==0 ) return;
  420. quote = z[0];
  421. switch( quote ){
  422. case '\'': break;
  423. case '"': break;
  424. case '[': quote = ']'; break;
  425. default: return;
  426. }
  427. for(i=1, j=0; z[i]; i++){
  428. if( z[i]==quote ){
  429. if( z[i+1]==quote ){
  430. z[j++] = quote;
  431. i++;
  432. }else{
  433. z[j++] = 0;
  434. break;
  435. }
  436. }else{
  437. z[j++] = z[i];
  438. }
  439. }
  440. }
  441. /* An array to map all upper-case characters into their corresponding
  442. ** lower-case character.
  443. */
  444. static unsigned char UpperToLower[] = {
  445. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  446. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  447. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  448. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  449. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  450. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  451. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  452. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  453. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  454. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  455. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  456. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  457. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  458. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  459. 252,253,254,255
  460. };
  461. /*
  462. ** This function computes a hash on the name of a keyword.
  463. ** Case is not significant.
  464. */
  465. int sqliteHashNoCase(const char *z, int n){
  466. int h = 0;
  467. if( n<=0 ) n = strlen(z);
  468. while( n > 0 ){
  469. h = (h<<3) ^ h ^ UpperToLower[(unsigned char)*z++];
  470. n--;
  471. }
  472. return h & 0x7fffffff;
  473. }
  474. /*
  475. ** Some systems have stricmp(). Others have strcasecmp(). Because
  476. ** there is no consistency, we will define our own.
  477. */
  478. int sqliteStrICmp(const char *zLeft, const char *zRight){
  479. register unsigned char *a, *b;
  480. a = (unsigned char *)zLeft;
  481. b = (unsigned char *)zRight;
  482. while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  483. return UpperToLower[*a] - UpperToLower[*b];
  484. }
  485. int sqliteStrNICmp(const char *zLeft, const char *zRight, int N){
  486. register unsigned char *a, *b;
  487. a = (unsigned char *)zLeft;
  488. b = (unsigned char *)zRight;
  489. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  490. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  491. }
  492. /*
  493. ** Return TRUE if z is a pure numeric string. Return FALSE if the
  494. ** string contains any character which is not part of a number.
  495. **
  496. ** Am empty string is considered non-numeric.
  497. */
  498. int sqliteIsNumber(const char *z){
  499. if( *z=='-' || *z=='+' ) z++;
  500. if( !isdigit(*z) ){
  501. return 0;
  502. }
  503. z++;
  504. while( isdigit(*z) ){ z++; }
  505. if( *z=='.' ){
  506. z++;
  507. if( !isdigit(*z) ) return 0;
  508. while( isdigit(*z) ){ z++; }
  509. }
  510. if( *z=='e' || *z=='E' ){
  511. z++;
  512. if( *z=='+' || *z=='-' ) z++;
  513. if( !isdigit(*z) ) return 0;
  514. while( isdigit(*z) ){ z++; }
  515. }
  516. return *z==0;
  517. }
  518. /*
  519. ** The string z[] is an ascii representation of a real number.
  520. ** Convert this string to a double.
  521. **
  522. ** This routine assumes that z[] really is a valid number. If it
  523. ** is not, the result is undefined.
  524. **
  525. ** This routine is used instead of the library atof() function because
  526. ** the library atof() might want to use "," as the decimal point instead
  527. ** of "." depending on how locale is set. But that would cause problems
  528. ** for SQL. So this routine always uses "." regardless of locale.
  529. */
  530. double sqliteAtoF(const char *z, const char **pzEnd){
  531. int sign = 1;
  532. LONGDOUBLE_TYPE v1 = 0.0;
  533. if( *z=='-' ){
  534. sign = -1;
  535. z++;
  536. }else if( *z=='+' ){
  537. z++;
  538. }
  539. while( isdigit(*z) ){
  540. v1 = v1*10.0 + (*z - '0');
  541. z++;
  542. }
  543. if( *z=='.' ){
  544. LONGDOUBLE_TYPE divisor = 1.0;
  545. z++;
  546. while( isdigit(*z) ){
  547. v1 = v1*10.0 + (*z - '0');
  548. divisor *= 10.0;
  549. z++;
  550. }
  551. v1 /= divisor;
  552. }
  553. if( *z=='e' || *z=='E' ){
  554. int esign = 1;
  555. int eval = 0;
  556. LONGDOUBLE_TYPE scale = 1.0;
  557. z++;
  558. if( *z=='-' ){
  559. esign = -1;
  560. z++;
  561. }else if( *z=='+' ){
  562. z++;
  563. }
  564. while( isdigit(*z) ){
  565. eval = eval*10 + *z - '0';
  566. z++;
  567. }
  568. while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
  569. while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
  570. while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
  571. while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }
  572. if( esign<0 ){
  573. v1 /= scale;
  574. }else{
  575. v1 *= scale;
  576. }
  577. }
  578. if( pzEnd ) *pzEnd = z;
  579. return sign<0 ? -v1 : v1;
  580. }
  581. /*
  582. ** The string zNum represents an integer. There might be some other
  583. ** information following the integer too, but that part is ignored.
  584. ** If the integer that the prefix of zNum represents will fit in a
  585. ** 32-bit signed integer, return TRUE. Otherwise return FALSE.
  586. **
  587. ** This routine returns FALSE for the string -2147483648 even that
  588. ** that number will, in theory fit in a 32-bit integer. But positive
  589. ** 2147483648 will not fit in 32 bits. So it seems safer to return
  590. ** false.
  591. */
  592. int sqliteFitsIn32Bits(const char *zNum){
  593. int i, c;
  594. if( *zNum=='-' || *zNum=='+' ) zNum++;
  595. for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
  596. return i<10 || (i==10 && memcmp(zNum,"2147483647",10)<=0);
  597. }
  598. /* This comparison routine is what we use for comparison operations
  599. ** between numeric values in an SQL expression. "Numeric" is a little
  600. ** bit misleading here. What we mean is that the strings have a
  601. ** type of "numeric" from the point of view of SQL. The strings
  602. ** do not necessarily contain numbers. They could contain text.
  603. **
  604. ** If the input strings both look like actual numbers then they
  605. ** compare in numerical order. Numerical strings are always less
  606. ** than non-numeric strings so if one input string looks like a
  607. ** number and the other does not, then the one that looks like
  608. ** a number is the smaller. Non-numeric strings compare in
  609. ** lexigraphical order (the same order as strcmp()).
  610. */
  611. int sqliteCompare(const char *atext, const char *btext){
  612. int result;
  613. int isNumA, isNumB;
  614. if( atext==0 ){
  615. return -1;
  616. }else if( btext==0 ){
  617. return 1;
  618. }
  619. isNumA = sqliteIsNumber(atext);
  620. isNumB = sqliteIsNumber(btext);
  621. if( isNumA ){
  622. if( !isNumB ){
  623. result = -1;
  624. }else{
  625. double rA, rB;
  626. rA = sqliteAtoF(atext, 0);
  627. rB = sqliteAtoF(btext, 0);
  628. if( rA<rB ){
  629. result = -1;
  630. }else if( rA>rB ){
  631. result = +1;
  632. }else{
  633. result = 0;
  634. }
  635. }
  636. }else if( isNumB ){
  637. result = +1;
  638. }else {
  639. result = strcmp(atext, btext);
  640. }
  641. return result;
  642. }
  643. /*
  644. ** This routine is used for sorting. Each key is a list of one or more
  645. ** null-terminated elements. The list is terminated by two nulls in
  646. ** a row. For example, the following text is a key with three elements
  647. **
  648. ** Aone\000Dtwo\000Athree\000\000
  649. **
  650. ** All elements begin with one of the characters "+-AD" and end with "\000"
  651. ** with zero or more text elements in between. Except, NULL elements
  652. ** consist of the special two-character sequence "N\000".
  653. **
  654. ** Both arguments will have the same number of elements. This routine
  655. ** returns negative, zero, or positive if the first argument is less
  656. ** than, equal to, or greater than the first. (Result is a-b).
  657. **
  658. ** Each element begins with one of the characters "+", "-", "A", "D".
  659. ** This character determines the sort order and collating sequence:
  660. **
  661. ** + Sort numerically in ascending order
  662. ** - Sort numerically in descending order
  663. ** A Sort as strings in ascending order
  664. ** D Sort as strings in descending order.
  665. **
  666. ** For the "+" and "-" sorting, pure numeric strings (strings for which the
  667. ** isNum() function above returns TRUE) always compare less than strings
  668. ** that are not pure numerics. Non-numeric strings compare in memcmp()
  669. ** order. This is the same sort order as the sqliteCompare() function
  670. ** above generates.
  671. **
  672. ** The last point is a change from version 2.6.3 to version 2.7.0. In
  673. ** version 2.6.3 and earlier, substrings of digits compare in numerical
  674. ** and case was used only to break a tie.
  675. **
  676. ** Elements that begin with 'A' or 'D' compare in memcmp() order regardless
  677. ** of whether or not they look like a number.
  678. **
  679. ** Note that the sort order imposed by the rules above is the same
  680. ** from the ordering defined by the "<", "<=", ">", and ">=" operators
  681. ** of expressions and for indices. This was not the case for version
  682. ** 2.6.3 and earlier.
  683. */
  684. int sqliteSortCompare(const char *a, const char *b){
  685. int res = 0;
  686. int isNumA, isNumB;
  687. int dir = 0;
  688. while( res==0 && *a && *b ){
  689. if( a[0]=='N' || b[0]=='N' ){
  690. if( a[0]==b[0] ){
  691. a += 2;
  692. b += 2;
  693. continue;
  694. }
  695. if( a[0]=='N' ){
  696. dir = b[0];
  697. res = -1;
  698. }else{
  699. dir = a[0];
  700. res = +1;
  701. }
  702. break;
  703. }
  704. assert( a[0]==b[0] );
  705. if( (dir=a[0])=='A' || a[0]=='D' ){
  706. res = strcmp(&a[1],&b[1]);
  707. if( res ) break;
  708. }else{
  709. isNumA = sqliteIsNumber(&a[1]);
  710. isNumB = sqliteIsNumber(&b[1]);
  711. if( isNumA ){
  712. double rA, rB;
  713. if( !isNumB ){
  714. res = -1;
  715. break;
  716. }
  717. rA = sqliteAtoF(&a[1], 0);
  718. rB = sqliteAtoF(&b[1], 0);
  719. if( rA<rB ){
  720. res = -1;
  721. break;
  722. }
  723. if( rA>rB ){
  724. res = +1;
  725. break;
  726. }
  727. }else if( isNumB ){
  728. res = +1;
  729. break;
  730. }else{
  731. res = strcmp(&a[1],&b[1]);
  732. if( res ) break;
  733. }
  734. }
  735. a += strlen(&a[1]) + 2;
  736. b += strlen(&b[1]) + 2;
  737. }
  738. if( dir=='-' || dir=='D' ) res = -res;
  739. return res;
  740. }
  741. /*
  742. ** Some powers of 64. These constants are needed in the
  743. ** sqliteRealToSortable() routine below.
  744. */
  745. #define _64e3 (64.0 * 64.0 * 64.0)
  746. #define _64e4 (64.0 * 64.0 * 64.0 * 64.0)
  747. #define _64e15 (_64e3 * _64e4 * _64e4 * _64e4)
  748. #define _64e16 (_64e4 * _64e4 * _64e4 * _64e4)
  749. #define _64e63 (_64e15 * _64e16 * _64e16 * _64e16)
  750. #define _64e64 (_64e16 * _64e16 * _64e16 * _64e16)
  751. /*
  752. ** The following procedure converts a double-precision floating point
  753. ** number into a string. The resulting string has the property that
  754. ** two such strings comparied using strcmp() or memcmp() will give the
  755. ** same results as a numeric comparison of the original floating point
  756. ** numbers.
  757. **
  758. ** This routine is used to generate database keys from floating point
  759. ** numbers such that the keys sort in the same order as the original
  760. ** floating point numbers even though the keys are compared using
  761. ** memcmp().
  762. **
  763. ** The calling function should have allocated at least 14 characters
  764. ** of space for the buffer z[].
  765. */
  766. void sqliteRealToSortable(double r, char *z){
  767. int neg;
  768. int exp;
  769. int cnt = 0;
  770. /* This array maps integers between 0 and 63 into base-64 digits.
  771. ** The digits must be chosen such at their ASCII codes are increasing.
  772. ** This means we can not use the traditional base-64 digit set. */
  773. static const char zDigit[] =
  774. "0123456789"
  775. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  776. "abcdefghijklmnopqrstuvwxyz"
  777. "|~";
  778. if( r<0.0 ){
  779. neg = 1;
  780. r = -r;
  781. *z++ = '-';
  782. } else {
  783. neg = 0;
  784. *z++ = '0';
  785. }
  786. exp = 0;
  787. if( r==0.0 ){
  788. exp = -1024;
  789. }else if( r<(0.5/64.0) ){
  790. while( r < 0.5/_64e64 && exp > -961 ){ r *= _64e64; exp -= 64; }
  791. while( r < 0.5/_64e16 && exp > -1009 ){ r *= _64e16; exp -= 16; }
  792. while( r < 0.5/_64e4 && exp > -1021 ){ r *= _64e4; exp -= 4; }
  793. while( r < 0.5/64.0 && exp > -1024 ){ r *= 64.0; exp -= 1; }
  794. }else if( r>=0.5 ){
  795. while( r >= 0.5*_64e63 && exp < 960 ){ r *= 1.0/_64e64; exp += 64; }
  796. while( r >= 0.5*_64e15 && exp < 1008 ){ r *= 1.0/_64e16; exp += 16; }
  797. while( r >= 0.5*_64e3 && exp < 1020 ){ r *= 1.0/_64e4; exp += 4; }
  798. while( r >= 0.5 && exp < 1023 ){ r *= 1.0/64.0; exp += 1; }
  799. }
  800. if( neg ){
  801. exp = -exp;
  802. r = -r;
  803. }
  804. exp += 1024;
  805. r += 0.5;
  806. if( exp<0 ) return;
  807. if( exp>=2048 || r>=1.0 ){
  808. strcpy(z, "~~~~~~~~~~~~");
  809. return;
  810. }
  811. *z++ = zDigit[(exp>>6)&0x3f];
  812. *z++ = zDigit[exp & 0x3f];
  813. while( r>0.0 && cnt<10 ){
  814. int digit;
  815. r *= 64.0;
  816. digit = (int)r;
  817. assert( digit>=0 && digit<64 );
  818. *z++ = zDigit[digit & 0x3f];
  819. r -= digit;
  820. cnt++;
  821. }
  822. *z = 0;
  823. }
  824. #ifdef SQLITE_UTF8
  825. /*
  826. ** X is a pointer to the first byte of a UTF-8 character. Increment
  827. ** X so that it points to the next character. This only works right
  828. ** if X points to a well-formed UTF-8 string.
  829. */
  830. #define sqliteNextChar(X) while( (0xc0&*++(X))==0x80 ){}
  831. #define sqliteCharVal(X) sqlite_utf8_to_int(X)
  832. #else /* !defined(SQLITE_UTF8) */
  833. /*
  834. ** For iso8859 encoding, the next character is just the next byte.
  835. */
  836. #define sqliteNextChar(X) (++(X));
  837. #define sqliteCharVal(X) ((int)*(X))
  838. #endif /* defined(SQLITE_UTF8) */
  839. #ifdef SQLITE_UTF8
  840. /*
  841. ** Convert the UTF-8 character to which z points into a 31-bit
  842. ** UCS character. This only works right if z points to a well-formed
  843. ** UTF-8 string.
  844. */
  845. static int sqlite_utf8_to_int(const unsigned char *z){
  846. int c;
  847. static const int initVal[] = {
  848. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  849. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  850. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  851. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  852. 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
  853. 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
  854. 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  855. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  856. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  857. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  858. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  859. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  860. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 0, 1, 2,
  861. 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  862. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 0,
  863. 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
  864. 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 0, 1, 254,
  865. 255,
  866. };
  867. c = initVal[*(z++)];
  868. while( (0xc0&*z)==0x80 ){
  869. c = (c<<6) | (0x3f&*(z++));
  870. }
  871. return c;
  872. }
  873. #endif
  874. /*
  875. ** Compare two UTF-8 strings for equality where the first string can
  876. ** potentially be a "glob" expression. Return true (1) if they
  877. ** are the same and false (0) if they are different.
  878. **
  879. ** Globbing rules:
  880. **
  881. ** '*' Matches any sequence of zero or more characters.
  882. **
  883. ** '?' Matches exactly one character.
  884. **
  885. ** [...] Matches one character from the enclosed list of
  886. ** characters.
  887. **
  888. ** [^...] Matches one character not in the enclosed list.
  889. **
  890. ** With the [...] and [^...] matching, a ']' character can be included
  891. ** in the list by making it the first character after '[' or '^'. A
  892. ** range of characters can be specified using '-'. Example:
  893. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  894. ** it the last character in the list.
  895. **
  896. ** This routine is usually quick, but can be N**2 in the worst case.
  897. **
  898. ** Hints: to match '*' or '?', put them in "[]". Like this:
  899. **
  900. ** abc[*]xyz Matches "abc*xyz" only
  901. */
  902. int
  903. sqliteGlobCompare(const unsigned char *zPattern, const unsigned char *zString){
  904. register int c;
  905. int invert;
  906. int seen;
  907. int c2;
  908. while( (c = *zPattern)!=0 ){
  909. switch( c ){
  910. case '*':
  911. while( (c=zPattern[1]) == '*' || c == '?' ){
  912. if( c=='?' ){
  913. if( *zString==0 ) return 0;
  914. sqliteNextChar(zString);
  915. }
  916. zPattern++;
  917. }
  918. if( c==0 ) return 1;
  919. if( c=='[' ){
  920. while( *zString && sqliteGlobCompare(&zPattern[1],zString)==0 ){
  921. sqliteNextChar(zString);
  922. }
  923. return *zString!=0;
  924. }else{
  925. while( (c2 = *zString)!=0 ){
  926. while( c2 != 0 && c2 != c ){ c2 = *++zString; }
  927. if( c2==0 ) return 0;
  928. if( sqliteGlobCompare(&zPattern[1],zString) ) return 1;
  929. sqliteNextChar(zString);
  930. }
  931. return 0;
  932. }
  933. case '?': {
  934. if( *zString==0 ) return 0;
  935. sqliteNextChar(zString);
  936. zPattern++;
  937. break;
  938. }
  939. case '[': {
  940. int prior_c = 0;
  941. seen = 0;
  942. invert = 0;
  943. c = sqliteCharVal(zString);
  944. if( c==0 ) return 0;
  945. c2 = *++zPattern;
  946. if( c2=='^' ){ invert = 1; c2 = *++zPattern; }
  947. if( c2==']' ){
  948. if( c==']' ) seen = 1;
  949. c2 = *++zPattern;
  950. }
  951. while( (c2 = sqliteCharVal(zPattern))!=0 && c2!=']' ){
  952. if( c2=='-' && zPattern[1]!=']' && zPattern[1]!=0 && prior_c>0 ){
  953. zPattern++;
  954. c2 = sqliteCharVal(zPattern);
  955. if( c>=prior_c && c<=c2 ) seen = 1;
  956. prior_c = 0;
  957. }else if( c==c2 ){
  958. seen = 1;
  959. prior_c = c2;
  960. }else{
  961. prior_c = c2;
  962. }
  963. sqliteNextChar(zPattern);
  964. }
  965. if( c2==0 || (seen ^ invert)==0 ) return 0;
  966. sqliteNextChar(zString);
  967. zPattern++;
  968. break;
  969. }
  970. default: {
  971. if( c != *zString ) return 0;
  972. zPattern++;
  973. zString++;
  974. break;
  975. }
  976. }
  977. }
  978. return *zString==0;
  979. }
  980. /*
  981. ** Compare two UTF-8 strings for equality using the "LIKE" operator of
  982. ** SQL. The '%' character matches any sequence of 0 or more
  983. ** characters and '_' matches any single character. Case is
  984. ** not significant.
  985. **
  986. ** This routine is just an adaptation of the sqliteGlobCompare()
  987. ** routine above.
  988. */
  989. int
  990. sqliteLikeCompare(const unsigned char *zPattern, const unsigned char *zString){
  991. register int c;
  992. int c2;
  993. while( (c = UpperToLower[*zPattern])!=0 ){
  994. switch( c ){
  995. case '%': {
  996. while( (c=zPattern[1]) == '%' || c == '_' ){
  997. if( c=='_' ){
  998. if( *zString==0 ) return 0;
  999. sqliteNextChar(zString);
  1000. }
  1001. zPattern++;
  1002. }
  1003. if( c==0 ) return 1;
  1004. c = UpperToLower[c];
  1005. while( (c2=UpperToLower[*zString])!=0 ){
  1006. while( c2 != 0 && c2 != c ){ c2 = UpperToLower[*++zString]; }
  1007. if( c2==0 ) return 0;
  1008. if( sqliteLikeCompare(&zPattern[1],zString) ) return 1;
  1009. sqliteNextChar(zString);
  1010. }
  1011. return 0;
  1012. }
  1013. case '_': {
  1014. if( *zString==0 ) return 0;
  1015. sqliteNextChar(zString);
  1016. zPattern++;
  1017. break;
  1018. }
  1019. default: {
  1020. if( c != UpperToLower[*zString] ) return 0;
  1021. zPattern++;
  1022. zString++;
  1023. break;
  1024. }
  1025. }
  1026. }
  1027. return *zString==0;
  1028. }
  1029. /*
  1030. ** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
  1031. ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
  1032. ** when this routine is called.
  1033. **
  1034. ** This routine is a attempt to detect if two threads use the
  1035. ** same sqlite* pointer at the same time. There is a race
  1036. ** condition so it is possible that the error is not detected.
  1037. ** But usually the problem will be seen. The result will be an
  1038. ** error which can be used to debug the application that is
  1039. ** using SQLite incorrectly.
  1040. **
  1041. ** Ticket #202: If db->magic is not a valid open value, take care not
  1042. ** to modify the db structure at all. It could be that db is a stale
  1043. ** pointer. In other words, it could be that there has been a prior
  1044. ** call to sqlite_close(db) and db has been deallocated. And we do
  1045. ** not want to write into deallocated memory.
  1046. */
  1047. int sqliteSafetyOn(sqlite *db){
  1048. if( db->magic==SQLITE_MAGIC_OPEN ){
  1049. db->magic = SQLITE_MAGIC_BUSY;
  1050. return 0;
  1051. }else if( db->magic==SQLITE_MAGIC_BUSY || db->magic==SQLITE_MAGIC_ERROR
  1052. || db->want_to_close ){
  1053. db->magic = SQLITE_MAGIC_ERROR;
  1054. db->flags |= SQLITE_Interrupt;
  1055. }
  1056. return 1;
  1057. }
  1058. /*
  1059. ** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
  1060. ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
  1061. ** when this routine is called.
  1062. */
  1063. int sqliteSafetyOff(sqlite *db){
  1064. if( db->magic==SQLITE_MAGIC_BUSY ){
  1065. db->magic = SQLITE_MAGIC_OPEN;
  1066. return 0;
  1067. }else if( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ERROR
  1068. || db->want_to_close ){
  1069. db->magic = SQLITE_MAGIC_ERROR;
  1070. db->flags |= SQLITE_Interrupt;
  1071. }
  1072. return 1;
  1073. }
  1074. /*
  1075. ** Check to make sure we are not currently executing an sqlite_exec().
  1076. ** If we are currently in an sqlite_exec(), return true and set
  1077. ** sqlite.magic to SQLITE_MAGIC_ERROR. This will cause a complete
  1078. ** shutdown of the database.
  1079. **
  1080. ** This routine is used to try to detect when API routines are called
  1081. ** at the wrong time or in the wrong sequence.
  1082. */
  1083. int sqliteSafetyCheck(sqlite *db){
  1084. if( db->pVdbe!=0 ){
  1085. db->magic = SQLITE_MAGIC_ERROR;
  1086. return 1;
  1087. }
  1088. return 0;
  1089. }