1 /* 2 ** The "printf" code that follows dates from the 1980's. It is in 3 ** the public domain. 4 ** 5 ************************************************************************** 6 ** 7 ** This file contains code for a set of "printf"-like routines. These 8 ** routines format strings much like the printf() from the standard C 9 ** library, though the implementation here has enhancements to support 10 ** SQLite. 11 */ 12 #include "sqliteInt.h" 13 14 /* 15 ** Conversion types fall into various categories as defined by the 16 ** following enumeration. 17 */ 18 #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */ 19 #define etFLOAT 2 /* Floating point. %f */ 20 #define etEXP 3 /* Exponentional notation. %e and %E */ 21 #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */ 22 #define etSIZE 5 /* Return number of characters processed so far. %n */ 23 #define etSTRING 6 /* Strings. %s */ 24 #define etDYNSTRING 7 /* Dynamically allocated strings. %z */ 25 #define etPERCENT 8 /* Percent symbol. %% */ 26 #define etCHARX 9 /* Characters. %c */ 27 /* The rest are extensions, not normally found in printf() */ 28 #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */ 29 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '', 30 NULL pointers replaced by SQL NULL. %Q */ 31 #define etTOKEN 12 /* a pointer to a Token structure */ 32 #define etSRCLIST 13 /* a pointer to a SrcList */ 33 #define etPOINTER 14 /* The %p conversion */ 34 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */ 35 #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */ 36 37 #define etINVALID 0 /* Any unrecognized conversion type */ 38 39 40 /* 41 ** An "etByte" is an 8-bit unsigned value. 42 */ 43 typedef unsigned char etByte; 44 45 /* 46 ** Each builtin conversion character (ex: the 'd' in "%d") is described 47 ** by an instance of the following structure 48 */ 49 typedef struct et_info { /* Information about each format field */ 50 char fmttype; /* The format field code letter */ 51 etByte base; /* The base for radix conversion */ 52 etByte flags; /* One or more of FLAG_ constants below */ 53 etByte type; /* Conversion paradigm */ 54 etByte charset; /* Offset into aDigits[] of the digits string */ 55 etByte prefix; /* Offset into aPrefix[] of the prefix string */ 56 } et_info; 57 58 /* 59 ** Allowed values for et_info.flags 60 */ 61 #define FLAG_SIGNED 1 /* True if the value to convert is signed */ 62 #define FLAG_INTERN 2 /* True if for internal use only */ 63 #define FLAG_STRING 4 /* Allow infinity precision */ 64 65 66 /* 67 ** The following table is searched linearly, so it is good to put the 68 ** most frequently used conversion types first. 69 */ 70 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef"; 71 static const char aPrefix[] = "-x0\000X0"; 72 static const et_info fmtinfo[] = { 73 { 'd', 10, 1, etRADIX, 0, 0 }, 74 { 's', 0, 4, etSTRING, 0, 0 }, 75 { 'g', 0, 1, etGENERIC, 30, 0 }, 76 { 'z', 0, 4, etDYNSTRING, 0, 0 }, 77 { 'q', 0, 4, etSQLESCAPE, 0, 0 }, 78 { 'Q', 0, 4, etSQLESCAPE2, 0, 0 }, 79 { 'w', 0, 4, etSQLESCAPE3, 0, 0 }, 80 { 'c', 0, 0, etCHARX, 0, 0 }, 81 { 'o', 8, 0, etRADIX, 0, 2 }, 82 { 'u', 10, 0, etRADIX, 0, 0 }, 83 { 'x', 16, 0, etRADIX, 16, 1 }, 84 { 'X', 16, 0, etRADIX, 0, 4 }, 85 #ifndef SQLITE_OMIT_FLOATING_POINT 86 { 'f', 0, 1, etFLOAT, 0, 0 }, 87 { 'e', 0, 1, etEXP, 30, 0 }, 88 { 'E', 0, 1, etEXP, 14, 0 }, 89 { 'G', 0, 1, etGENERIC, 14, 0 }, 90 #endif 91 { 'i', 10, 1, etRADIX, 0, 0 }, 92 { 'n', 0, 0, etSIZE, 0, 0 }, 93 { '%', 0, 0, etPERCENT, 0, 0 }, 94 { 'p', 16, 0, etPOINTER, 0, 1 }, 95 96 /* All the rest have the FLAG_INTERN bit set and are thus for internal 97 ** use only */ 98 { 'T', 0, 2, etTOKEN, 0, 0 }, 99 { 'S', 0, 2, etSRCLIST, 0, 0 }, 100 { 'r', 10, 3, etORDINAL, 0, 0 }, 101 }; 102 103 /* 104 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point 105 ** conversions will work. 106 */ 107 #ifndef SQLITE_OMIT_FLOATING_POINT 108 /* 109 ** "*val" is a double such that 0.1 <= *val < 10.0 110 ** Return the ascii code for the leading digit of *val, then 111 ** multiply "*val" by 10.0 to renormalize. 112 ** 113 ** Example: 114 ** input: *val = 3.14159 115 ** output: *val = 1.4159 function return = '3' 116 ** 117 ** The counter *cnt is incremented each time. After counter exceeds 118 ** 16 (the number of significant digits in a 64-bit float) '0' is 119 ** always returned. 120 */ 121 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){ 122 int digit; 123 LONGDOUBLE_TYPE d; 124 if( (*cnt)<=0 ) return '0'; 125 (*cnt)--; 126 digit = (int)*val; 127 d = digit; 128 digit += '0'; 129 *val = (*val - d)*10.0; 130 return (char)digit; 131 } 132 #endif /* SQLITE_OMIT_FLOATING_POINT */ 133 134 /* 135 ** Set the StrAccum object to an error mode. 136 */ 137 static void setStrAccumError(StrAccum *p, u8 eError){ 138 assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG ); 139 p->accError = eError; 140 p->nAlloc = 0; 141 } 142 143 /* 144 ** Extra argument values from a PrintfArguments object 145 */ 146 static sqlite3_int64 getIntArg(PrintfArguments *p){ 147 if( p->nArg<=p->nUsed ) return 0; 148 return sqlite3_value_int64(p->apArg[p->nUsed++]); 149 } 150 static double getDoubleArg(PrintfArguments *p){ 151 if( p->nArg<=p->nUsed ) return 0.0; 152 return sqlite3_value_double(p->apArg[p->nUsed++]); 153 } 154 static char *getTextArg(PrintfArguments *p){ 155 if( p->nArg<=p->nUsed ) return 0; 156 return (char*)sqlite3_value_text(p->apArg[p->nUsed++]); 157 } 158 159 160 /* 161 ** On machines with a small stack size, you can redefine the 162 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired. 163 */ 164 #ifndef SQLITE_PRINT_BUF_SIZE 165 # define SQLITE_PRINT_BUF_SIZE 70 166 #endif 167 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */ 168 169 /* 170 ** Render a string given by "fmt" into the StrAccum object. 171 */ 172 void sqlite3VXPrintf( 173 StrAccum *pAccum, /* Accumulate results here */ 174 u32 bFlags, /* SQLITE_PRINTF_* flags */ 175 const char *fmt, /* Format string */ 176 va_list ap /* arguments */ 177 ){ 178 int c; /* Next character in the format string */ 179 char *bufpt; /* Pointer to the conversion buffer */ 180 int precision; /* Precision of the current field */ 181 int length; /* Length of the field */ 182 int idx; /* A general purpose loop counter */ 183 int width; /* Width of the current field */ 184 etByte flag_leftjustify; /* True if "-" flag is present */ 185 etByte flag_plussign; /* True if "+" flag is present */ 186 etByte flag_blanksign; /* True if " " flag is present */ 187 etByte flag_alternateform; /* True if "#" flag is present */ 188 etByte flag_altform2; /* True if "!" flag is present */ 189 etByte flag_zeropad; /* True if field width constant starts with zero */ 190 etByte flag_long; /* True if "l" flag is present */ 191 etByte flag_longlong; /* True if the "ll" flag is present */ 192 etByte done; /* Loop termination flag */ 193 etByte xtype = 0; /* Conversion paradigm */ 194 u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */ 195 u8 useIntern; /* Ok to use internal conversions (ex: %T) */ 196 char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */ 197 sqlite_uint64 longvalue; /* Value for integer types */ 198 LONGDOUBLE_TYPE realvalue; /* Value for real types */ 199 const et_info *infop; /* Pointer to the appropriate info structure */ 200 char *zOut; /* Rendering buffer */ 201 int nOut; /* Size of the rendering buffer */ 202 char *zExtra = 0; /* Malloced memory used by some conversion */ 203 #ifndef SQLITE_OMIT_FLOATING_POINT 204 int exp, e2; /* exponent of real numbers */ 205 int nsd; /* Number of significant digits returned */ 206 double rounder; /* Used for rounding floating point values */ 207 etByte flag_dp; /* True if decimal point should be shown */ 208 etByte flag_rtz; /* True if trailing zeros should be removed */ 209 #endif 210 PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */ 211 char buf[etBUFSIZE]; /* Conversion buffer */ 212 213 bufpt = 0; 214 if( bFlags ){ 215 if( (bArgList = (bFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){ 216 pArgList = va_arg(ap, PrintfArguments*); 217 } 218 useIntern = bFlags & SQLITE_PRINTF_INTERNAL; 219 }else{ 220 bArgList = useIntern = 0; 221 } 222 for(; (c=(*fmt))!=0; ++fmt){ 223 if( c!='%' ){ 224 bufpt = (char *)fmt; 225 #if HAVE_STRCHRNUL 226 fmt = strchrnul(fmt, '%'); 227 #else 228 do{ fmt++; }while( *fmt && *fmt != '%' ); 229 #endif 230 sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt)); 231 if( *fmt==0 ) break; 232 } 233 if( (c=(*++fmt))==0 ){ 234 sqlite3StrAccumAppend(pAccum, "%", 1); 235 break; 236 } 237 /* Find out what flags are present */ 238 flag_leftjustify = flag_plussign = flag_blanksign = 239 flag_alternateform = flag_altform2 = flag_zeropad = 0; 240 done = 0; 241 do{ 242 switch( c ){ 243 case '-': flag_leftjustify = 1; break; 244 case '+': flag_plussign = 1; break; 245 case ' ': flag_blanksign = 1; break; 246 case '#': flag_alternateform = 1; break; 247 case '!': flag_altform2 = 1; break; 248 case '0': flag_zeropad = 1; break; 249 default: done = 1; break; 250 } 251 }while( !done && (c=(*++fmt))!=0 ); 252 /* Get the field width */ 253 if( c=='*' ){ 254 if( bArgList ){ 255 width = (int)getIntArg(pArgList); 256 }else{ 257 width = va_arg(ap,int); 258 } 259 if( width<0 ){ 260 flag_leftjustify = 1; 261 width = width >= -2147483647 ? -width : 0; 262 } 263 c = *++fmt; 264 }else{ 265 unsigned wx = 0; 266 while( c>='0' && c<='9' ){ 267 wx = wx*10 + c - '0'; 268 c = *++fmt; 269 } 270 testcase( wx>0x7fffffff ); 271 width = wx & 0x7fffffff; 272 } 273 274 /* Get the precision */ 275 if( c=='.' ){ 276 c = *++fmt; 277 if( c=='*' ){ 278 if( bArgList ){ 279 precision = (int)getIntArg(pArgList); 280 }else{ 281 precision = va_arg(ap,int); 282 } 283 c = *++fmt; 284 if( precision<0 ){ 285 precision = precision >= -2147483647 ? -precision : -1; 286 } 287 }else{ 288 unsigned px = 0; 289 while( c>='0' && c<='9' ){ 290 px = px*10 + c - '0'; 291 c = *++fmt; 292 } 293 testcase( px>0x7fffffff ); 294 precision = px & 0x7fffffff; 295 } 296 }else{ 297 precision = -1; 298 } 299 /* Get the conversion type modifier */ 300 if( c=='l' ){ 301 flag_long = 1; 302 c = *++fmt; 303 if( c=='l' ){ 304 flag_longlong = 1; 305 c = *++fmt; 306 }else{ 307 flag_longlong = 0; 308 } 309 }else{ 310 flag_long = flag_longlong = 0; 311 } 312 /* Fetch the info entry for the field */ 313 infop = &fmtinfo[0]; 314 xtype = etINVALID; 315 for(idx=0; idx<ArraySize(fmtinfo); idx++){ 316 if( c==fmtinfo[idx].fmttype ){ 317 infop = &fmtinfo[idx]; 318 if( useIntern || (infop->flags & FLAG_INTERN)==0 ){ 319 xtype = infop->type; 320 }else{ 321 return; 322 } 323 break; 324 } 325 } 326 327 /* 328 ** At this point, variables are initialized as follows: 329 ** 330 ** flag_alternateform TRUE if a '#' is present. 331 ** flag_altform2 TRUE if a '!' is present. 332 ** flag_plussign TRUE if a '+' is present. 333 ** flag_leftjustify TRUE if a '-' is present or if the 334 ** field width was negative. 335 ** flag_zeropad TRUE if the width began with 0. 336 ** flag_long TRUE if the letter 'l' (ell) prefixed 337 ** the conversion character. 338 ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed 339 ** the conversion character. 340 ** flag_blanksign TRUE if a ' ' is present. 341 ** width The specified field width. This is 342 ** always non-negative. Zero is the default. 343 ** precision The specified precision. The default 344 ** is -1. 345 ** xtype The class of the conversion. 346 ** infop Pointer to the appropriate info struct. 347 */ 348 switch( xtype ){ 349 case etPOINTER: 350 flag_longlong = sizeof(char*)==sizeof(i64); 351 flag_long = sizeof(char*)==sizeof(long int); 352 /* Fall through into the next case */ 353 case etORDINAL: 354 case etRADIX: 355 if( infop->flags & FLAG_SIGNED ){ 356 i64 v; 357 if( bArgList ){ 358 v = getIntArg(pArgList); 359 }else if( flag_longlong ){ 360 v = va_arg(ap,i64); 361 }else if( flag_long ){ 362 v = va_arg(ap,long int); 363 }else{ 364 v = va_arg(ap,int); 365 } 366 if( v<0 ){ 367 if( v==SMALLEST_INT64 ){ 368 longvalue = ((u64)1)<<63; 369 }else{ 370 longvalue = -v; 371 } 372 prefix = '-'; 373 }else{ 374 longvalue = v; 375 if( flag_plussign ) prefix = '+'; 376 else if( flag_blanksign ) prefix = ' '; 377 else prefix = 0; 378 } 379 }else{ 380 if( bArgList ){ 381 longvalue = (u64)getIntArg(pArgList); 382 }else if( flag_longlong ){ 383 longvalue = va_arg(ap,u64); 384 }else if( flag_long ){ 385 longvalue = va_arg(ap,unsigned long int); 386 }else{ 387 longvalue = va_arg(ap,unsigned int); 388 } 389 prefix = 0; 390 } 391 if( longvalue==0 ) flag_alternateform = 0; 392 if( flag_zeropad && precision<width-(prefix!=0) ){ 393 precision = width-(prefix!=0); 394 } 395 if( precision<etBUFSIZE-10 ){ 396 nOut = etBUFSIZE; 397 zOut = buf; 398 }else{ 399 nOut = precision + 10; 400 zOut = zExtra = sqlite3Malloc( nOut ); 401 if( zOut==0 ){ 402 setStrAccumError(pAccum, STRACCUM_NOMEM); 403 return; 404 } 405 } 406 bufpt = &zOut[nOut-1]; 407 if( xtype==etORDINAL ){ 408 static const char zOrd[] = "thstndrd"; 409 int x = (int)(longvalue % 10); 410 if( x>=4 || (longvalue/10)%10==1 ){ 411 x = 0; 412 } 413 *(--bufpt) = zOrd[x*2+1]; 414 *(--bufpt) = zOrd[x*2]; 415 } 416 { 417 const char *cset = &aDigits[infop->charset]; 418 u8 base = infop->base; 419 do{ /* Convert to ascii */ 420 *(--bufpt) = cset[longvalue%base]; 421 longvalue = longvalue/base; 422 }while( longvalue>0 ); 423 } 424 length = (int)(&zOut[nOut-1]-bufpt); 425 for(idx=precision-length; idx>0; idx--){ 426 *(--bufpt) = '0'; /* Zero pad */ 427 } 428 if( prefix ) *(--bufpt) = prefix; /* Add sign */ 429 if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */ 430 const char *pre; 431 char x; 432 pre = &aPrefix[infop->prefix]; 433 for(; (x=(*pre))!=0; pre++) *(--bufpt) = x; 434 } 435 length = (int)(&zOut[nOut-1]-bufpt); 436 break; 437 case etFLOAT: 438 case etEXP: 439 case etGENERIC: 440 if( bArgList ){ 441 realvalue = getDoubleArg(pArgList); 442 }else{ 443 realvalue = va_arg(ap,double); 444 } 445 #ifdef SQLITE_OMIT_FLOATING_POINT 446 length = 0; 447 #else 448 if( precision<0 ) precision = 6; /* Set default precision */ 449 if( realvalue<0.0 ){ 450 realvalue = -realvalue; 451 prefix = '-'; 452 }else{ 453 if( flag_plussign ) prefix = '+'; 454 else if( flag_blanksign ) prefix = ' '; 455 else prefix = 0; 456 } 457 if( xtype==etGENERIC && precision>0 ) precision--; 458 testcase( precision>0xfff ); 459 for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){} 460 if( xtype==etFLOAT ) realvalue += rounder; 461 /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */ 462 exp = 0; 463 if( sqlite3IsNaN((double)realvalue) ){ 464 bufpt = "NaN"; 465 length = 3; 466 break; 467 } 468 if( realvalue>0.0 ){ 469 LONGDOUBLE_TYPE scale = 1.0; 470 while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;} 471 while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; } 472 while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; } 473 while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; } 474 realvalue /= scale; 475 while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; } 476 while( realvalue<1.0 ){ realvalue *= 10.0; exp--; } 477 if( exp>350 ){ 478 if( prefix=='-' ){ 479 bufpt = "-Inf"; 480 }else if( prefix=='+' ){ 481 bufpt = "+Inf"; 482 }else{ 483 bufpt = "Inf"; 484 } 485 length = sqlite3Strlen30(bufpt); 486 break; 487 } 488 } 489 bufpt = buf; 490 /* 491 ** If the field type is etGENERIC, then convert to either etEXP 492 ** or etFLOAT, as appropriate. 493 */ 494 if( xtype!=etFLOAT ){ 495 realvalue += rounder; 496 if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; } 497 } 498 if( xtype==etGENERIC ){ 499 flag_rtz = !flag_alternateform; 500 if( exp<-4 || exp>precision ){ 501 xtype = etEXP; 502 }else{ 503 precision = precision - exp; 504 xtype = etFLOAT; 505 } 506 }else{ 507 flag_rtz = flag_altform2; 508 } 509 if( xtype==etEXP ){ 510 e2 = 0; 511 }else{ 512 e2 = exp; 513 } 514 if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){ 515 bufpt = zExtra 516 = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 ); 517 if( bufpt==0 ){ 518 setStrAccumError(pAccum, STRACCUM_NOMEM); 519 return; 520 } 521 } 522 zOut = bufpt; 523 nsd = 16 + flag_altform2*10; 524 flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2; 525 /* The sign in front of the number */ 526 if( prefix ){ 527 *(bufpt++) = prefix; 528 } 529 /* Digits prior to the decimal point */ 530 if( e2<0 ){ 531 *(bufpt++) = '0'; 532 }else{ 533 for(; e2>=0; e2--){ 534 *(bufpt++) = et_getdigit(&realvalue,&nsd); 535 } 536 } 537 /* The decimal point */ 538 if( flag_dp ){ 539 *(bufpt++) = '.'; 540 } 541 /* "0" digits after the decimal point but before the first 542 ** significant digit of the number */ 543 for(e2++; e2<0; precision--, e2++){ 544 assert( precision>0 ); 545 *(bufpt++) = '0'; 546 } 547 /* Significant digits after the decimal point */ 548 while( (precision--)>0 ){ 549 *(bufpt++) = et_getdigit(&realvalue,&nsd); 550 } 551 /* Remove trailing zeros and the "." if no digits follow the "." */ 552 if( flag_rtz && flag_dp ){ 553 while( bufpt[-1]=='0' ) *(--bufpt) = 0; 554 assert( bufpt>zOut ); 555 if( bufpt[-1]=='.' ){ 556 if( flag_altform2 ){ 557 *(bufpt++) = '0'; 558 }else{ 559 *(--bufpt) = 0; 560 } 561 } 562 } 563 /* Add the "eNNN" suffix */ 564 if( xtype==etEXP ){ 565 *(bufpt++) = aDigits[infop->charset]; 566 if( exp<0 ){ 567 *(bufpt++) = '-'; exp = -exp; 568 }else{ 569 *(bufpt++) = '+'; 570 } 571 if( exp>=100 ){ 572 *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */ 573 exp %= 100; 574 } 575 *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */ 576 *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */ 577 } 578 *bufpt = 0; 579 580 /* The converted number is in buf[] and zero terminated. Output it. 581 ** Note that the number is in the usual order, not reversed as with 582 ** integer conversions. */ 583 length = (int)(bufpt-zOut); 584 bufpt = zOut; 585 586 /* Special case: Add leading zeros if the flag_zeropad flag is 587 ** set and we are not left justified */ 588 if( flag_zeropad && !flag_leftjustify && length < width){ 589 int i; 590 int nPad = width - length; 591 for(i=width; i>=nPad; i--){ 592 bufpt[i] = bufpt[i-nPad]; 593 } 594 i = prefix!=0; 595 while( nPad-- ) bufpt[i++] = '0'; 596 length = width; 597 } 598 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */ 599 break; 600 case etSIZE: 601 if( !bArgList ){ 602 *(va_arg(ap,int*)) = pAccum->nChar; 603 } 604 length = width = 0; 605 break; 606 case etPERCENT: 607 buf[0] = '%'; 608 bufpt = buf; 609 length = 1; 610 break; 611 case etCHARX: 612 if( bArgList ){ 613 bufpt = getTextArg(pArgList); 614 c = bufpt ? bufpt[0] : 0; 615 }else{ 616 c = va_arg(ap,int); 617 } 618 if( precision>1 ){ 619 width -= precision-1; 620 if( width>1 && !flag_leftjustify ){ 621 sqlite3AppendChar(pAccum, width-1, ' '); 622 width = 0; 623 } 624 sqlite3AppendChar(pAccum, precision-1, c); 625 } 626 length = 1; 627 buf[0] = c; 628 bufpt = buf; 629 break; 630 case etSTRING: 631 case etDYNSTRING: 632 if( bArgList ){ 633 bufpt = getTextArg(pArgList); 634 }else{ 635 bufpt = va_arg(ap,char*); 636 } 637 if( bufpt==0 ){ 638 bufpt = ""; 639 }else if( xtype==etDYNSTRING && !bArgList ){ 640 zExtra = bufpt; 641 } 642 if( precision>=0 ){ 643 for(length=0; length<precision && bufpt[length]; length++){} 644 }else{ 645 length = sqlite3Strlen30(bufpt); 646 } 647 break; 648 case etSQLESCAPE: 649 case etSQLESCAPE2: 650 case etSQLESCAPE3: { 651 int i, j, k, n, isnull; 652 int needQuote; 653 char ch; 654 char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */ 655 char *escarg; 656 657 if( bArgList ){ 658 escarg = getTextArg(pArgList); 659 }else{ 660 escarg = va_arg(ap,char*); 661 } 662 isnull = escarg==0; 663 if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)"); 664 k = precision; 665 for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){ 666 if( ch==q ) n++; 667 } 668 needQuote = !isnull && xtype==etSQLESCAPE2; 669 n += i + 1 + needQuote*2; 670 if( n>etBUFSIZE ){ 671 bufpt = zExtra = sqlite3Malloc( n ); 672 if( bufpt==0 ){ 673 setStrAccumError(pAccum, STRACCUM_NOMEM); 674 return; 675 } 676 }else{ 677 bufpt = buf; 678 } 679 j = 0; 680 if( needQuote ) bufpt[j++] = q; 681 k = i; 682 for(i=0; i<k; i++){ 683 bufpt[j++] = ch = escarg[i]; 684 if( ch==q ) bufpt[j++] = ch; 685 } 686 if( needQuote ) bufpt[j++] = q; 687 bufpt[j] = 0; 688 length = j; 689 /* The precision in %q and %Q means how many input characters to 690 ** consume, not the length of the output... 691 ** if( precision>=0 && precision<length ) length = precision; */ 692 break; 693 } 694 case etTOKEN: { 695 Token *pToken = va_arg(ap, Token*); 696 assert( bArgList==0 ); 697 if( pToken && pToken->n ){ 698 sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n); 699 } 700 length = width = 0; 701 break; 702 } 703 case etSRCLIST: { 704 SrcList *pSrc = va_arg(ap, SrcList*); 705 int k = va_arg(ap, int); 706 struct SrcList_item *pItem = &pSrc->a[k]; 707 assert( bArgList==0 ); 708 assert( k>=0 && k<pSrc->nSrc ); 709 if( pItem->zDatabase ){ 710 sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase); 711 sqlite3StrAccumAppend(pAccum, ".", 1); 712 } 713 sqlite3StrAccumAppendAll(pAccum, pItem->zName); 714 length = width = 0; 715 break; 716 } 717 default: { 718 assert( xtype==etINVALID ); 719 return; 720 } 721 }/* End switch over the format type */ 722 /* 723 ** The text of the conversion is pointed to by "bufpt" and is 724 ** "length" characters long. The field width is "width". Do 725 ** the output. 726 */ 727 width -= length; 728 if( width>0 && !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' '); 729 sqlite3StrAccumAppend(pAccum, bufpt, length); 730 if( width>0 && flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' '); 731 732 if( zExtra ){ 733 sqlite3_free(zExtra); 734 zExtra = 0; 735 } 736 }/* End for loop over the format string */ 737 } /* End of function */ 738 739 /* 740 ** Enlarge the memory allocation on a StrAccum object so that it is 741 ** able to accept at least N more bytes of text. 742 ** 743 ** Return the number of bytes of text that StrAccum is able to accept 744 ** after the attempted enlargement. The value returned might be zero. 745 */ 746 static int sqlite3StrAccumEnlarge(StrAccum *p, int N){ 747 char *zNew; 748 assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */ 749 if( p->accError ){ 750 testcase(p->accError==STRACCUM_TOOBIG); 751 testcase(p->accError==STRACCUM_NOMEM); 752 return 0; 753 } 754 if( p->mxAlloc==0 ){ 755 N = p->nAlloc - p->nChar - 1; 756 setStrAccumError(p, STRACCUM_TOOBIG); 757 return N; 758 }else{ 759 char *zOld = (p->zText==p->zBase ? 0 : p->zText); 760 i64 szNew = p->nChar; 761 szNew += N + 1; 762 if( szNew+p->nChar<=p->mxAlloc ){ 763 /* Force exponential buffer size growth as long as it does not overflow, 764 ** to avoid having to call this routine too often */ 765 szNew += p->nChar; 766 } 767 if( szNew > p->mxAlloc ){ 768 sqlite3StrAccumReset(p); 769 setStrAccumError(p, STRACCUM_TOOBIG); 770 return 0; 771 }else{ 772 p->nAlloc = (int)szNew; 773 } 774 if( p->db ){ 775 zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc); 776 }else{ 777 zNew = sqlite3_realloc64(zOld, p->nAlloc); 778 } 779 if( zNew ){ 780 assert( p->zText!=0 || p->nChar==0 ); 781 if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar); 782 p->zText = zNew; 783 p->nAlloc = sqlite3DbMallocSize(p->db, zNew); 784 }else{ 785 sqlite3StrAccumReset(p); 786 setStrAccumError(p, STRACCUM_NOMEM); 787 return 0; 788 } 789 } 790 return N; 791 } 792 793 /* 794 ** Append N copies of character c to the given string buffer. 795 */ 796 void sqlite3AppendChar(StrAccum *p, int N, char c){ 797 testcase( p->nChar + (i64)N > 0x7fffffff ); 798 if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){ 799 return; 800 } 801 while( (N--)>0 ) p->zText[p->nChar++] = c; 802 } 803 804 /* 805 ** The StrAccum "p" is not large enough to accept N new bytes of z[]. 806 ** So enlarge if first, then do the append. 807 ** 808 ** This is a helper routine to sqlite3StrAccumAppend() that does special-case 809 ** work (enlarging the buffer) using tail recursion, so that the 810 ** sqlite3StrAccumAppend() routine can use fast calling semantics. 811 */ 812 static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){ 813 N = sqlite3StrAccumEnlarge(p, N); 814 if( N>0 ){ 815 memcpy(&p->zText[p->nChar], z, N); 816 p->nChar += N; 817 } 818 } 819 820 /* 821 ** Append N bytes of text from z to the StrAccum object. Increase the 822 ** size of the memory allocation for StrAccum if necessary. 823 */ 824 void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){ 825 assert( z!=0 || N==0 ); 826 assert( p->zText!=0 || p->nChar==0 || p->accError ); 827 assert( N>=0 ); 828 assert( p->accError==0 || p->nAlloc==0 ); 829 if( p->nChar+N >= p->nAlloc ){ 830 enlargeAndAppend(p,z,N); 831 }else{ 832 assert( p->zText ); 833 p->nChar += N; 834 memcpy(&p->zText[p->nChar-N], z, N); 835 } 836 } 837 838 /* 839 ** Append the complete text of zero-terminated string z[] to the p string. 840 */ 841 void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){ 842 sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z)); 843 } 844 845 846 /* 847 ** Finish off a string by making sure it is zero-terminated. 848 ** Return a pointer to the resulting string. Return a NULL 849 ** pointer if any kind of error was encountered. 850 */ 851 char *sqlite3StrAccumFinish(StrAccum *p){ 852 if( p->zText ){ 853 p->zText[p->nChar] = 0; 854 if( p->mxAlloc>0 && p->zText==p->zBase ){ 855 p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 ); 856 if( p->zText ){ 857 memcpy(p->zText, p->zBase, p->nChar+1); 858 }else{ 859 setStrAccumError(p, STRACCUM_NOMEM); 860 } 861 } 862 } 863 return p->zText; 864 } 865 866 /* 867 ** Reset an StrAccum string. Reclaim all malloced memory. 868 */ 869 void sqlite3StrAccumReset(StrAccum *p){ 870 if( p->zText!=p->zBase ){ 871 sqlite3DbFree(p->db, p->zText); 872 } 873 p->zText = 0; 874 } 875 876 /* 877 ** Initialize a string accumulator. 878 ** 879 ** p: The accumulator to be initialized. 880 ** db: Pointer to a database connection. May be NULL. Lookaside 881 ** memory is used if not NULL. db->mallocFailed is set appropriately 882 ** when not NULL. 883 ** zBase: An initial buffer. May be NULL in which case the initial buffer 884 ** is malloced. 885 ** n: Size of zBase in bytes. If total space requirements never exceed 886 ** n then no memory allocations ever occur. 887 ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory 888 ** allocations will ever occur. 889 */ 890 void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){ 891 p->zText = p->zBase = zBase; 892 p->db = db; 893 p->nChar = 0; 894 p->nAlloc = n; 895 p->mxAlloc = mx; 896 p->accError = 0; 897 } 898 899 /* 900 ** Print into memory obtained from sqliteMalloc(). Use the internal 901 ** %-conversion extensions. 902 */ 903 char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){ 904 char *z; 905 char zBase[SQLITE_PRINT_BUF_SIZE]; 906 StrAccum acc; 907 assert( db!=0 ); 908 sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase), 909 db->aLimit[SQLITE_LIMIT_LENGTH]); 910 sqlite3VXPrintf(&acc, SQLITE_PRINTF_INTERNAL, zFormat, ap); 911 z = sqlite3StrAccumFinish(&acc); 912 if( acc.accError==STRACCUM_NOMEM ){ 913 db->mallocFailed = 1; 914 } 915 return z; 916 } 917 918 /* 919 ** Print into memory obtained from sqliteMalloc(). Use the internal 920 ** %-conversion extensions. 921 */ 922 char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){ 923 va_list ap; 924 char *z; 925 va_start(ap, zFormat); 926 z = sqlite3VMPrintf(db, zFormat, ap); 927 va_end(ap); 928 return z; 929 } 930 931 /* 932 ** Print into memory obtained from sqlite3_malloc(). Omit the internal 933 ** %-conversion extensions. 934 */ 935 char *sqlite3_vmprintf(const char *zFormat, va_list ap){ 936 char *z; 937 char zBase[SQLITE_PRINT_BUF_SIZE]; 938 StrAccum acc; 939 940 #ifdef SQLITE_ENABLE_API_ARMOR 941 if( zFormat==0 ){ 942 (void)SQLITE_MISUSE_BKPT; 943 return 0; 944 } 945 #endif 946 #ifndef SQLITE_OMIT_AUTOINIT 947 if( sqlite3_initialize() ) return 0; 948 #endif 949 sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH); 950 sqlite3VXPrintf(&acc, 0, zFormat, ap); 951 z = sqlite3StrAccumFinish(&acc); 952 return z; 953 } 954 955 /* 956 ** Print into memory obtained from sqlite3_malloc()(). Omit the internal 957 ** %-conversion extensions. 958 */ 959 char *sqlite3_mprintf(const char *zFormat, ...){ 960 va_list ap; 961 char *z; 962 #ifndef SQLITE_OMIT_AUTOINIT 963 if( sqlite3_initialize() ) return 0; 964 #endif 965 va_start(ap, zFormat); 966 z = sqlite3_vmprintf(zFormat, ap); 967 va_end(ap); 968 return z; 969 } 970 971 /* 972 ** sqlite3_snprintf() works like snprintf() except that it ignores the 973 ** current locale settings. This is important for SQLite because we 974 ** are not able to use a "," as the decimal point in place of "." as 975 ** specified by some locales. 976 ** 977 ** Oops: The first two arguments of sqlite3_snprintf() are backwards 978 ** from the snprintf() standard. Unfortunately, it is too late to change 979 ** this without breaking compatibility, so we just have to live with the 980 ** mistake. 981 ** 982 ** sqlite3_vsnprintf() is the varargs version. 983 */ 984 char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){ 985 StrAccum acc; 986 if( n<=0 ) return zBuf; 987 #ifdef SQLITE_ENABLE_API_ARMOR 988 if( zBuf==0 || zFormat==0 ) { 989 (void)SQLITE_MISUSE_BKPT; 990 if( zBuf ) zBuf[0] = 0; 991 return zBuf; 992 } 993 #endif 994 sqlite3StrAccumInit(&acc, 0, zBuf, n, 0); 995 sqlite3VXPrintf(&acc, 0, zFormat, ap); 996 return sqlite3StrAccumFinish(&acc); 997 } 998 char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){ 999 char *z; 1000 va_list ap; 1001 va_start(ap,zFormat); 1002 z = sqlite3_vsnprintf(n, zBuf, zFormat, ap); 1003 va_end(ap); 1004 return z; 1005 } 1006 1007 /* 1008 ** This is the routine that actually formats the sqlite3_log() message. 1009 ** We house it in a separate routine from sqlite3_log() to avoid using 1010 ** stack space on small-stack systems when logging is disabled. 1011 ** 1012 ** sqlite3_log() must render into a static buffer. It cannot dynamically 1013 ** allocate memory because it might be called while the memory allocator 1014 ** mutex is held. 1015 ** 1016 ** sqlite3VXPrintf() might ask for *temporary* memory allocations for 1017 ** certain format characters (%q) or for very large precisions or widths. 1018 ** Care must be taken that any sqlite3_log() calls that occur while the 1019 ** memory mutex is held do not use these mechanisms. 1020 */ 1021 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){ 1022 StrAccum acc; /* String accumulator */ 1023 char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */ 1024 1025 sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0); 1026 sqlite3VXPrintf(&acc, 0, zFormat, ap); 1027 sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode, 1028 sqlite3StrAccumFinish(&acc)); 1029 } 1030 1031 /* 1032 ** Format and write a message to the log if logging is enabled. 1033 */ 1034 void sqlite3_log(int iErrCode, const char *zFormat, ...){ 1035 va_list ap; /* Vararg list */ 1036 if( sqlite3GlobalConfig.xLog ){ 1037 va_start(ap, zFormat); 1038 renderLogMsg(iErrCode, zFormat, ap); 1039 va_end(ap); 1040 } 1041 } 1042 1043 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE) 1044 /* 1045 ** A version of printf() that understands %lld. Used for debugging. 1046 ** The printf() built into some versions of windows does not understand %lld 1047 ** and segfaults if you give it a long long int. 1048 */ 1049 void sqlite3DebugPrintf(const char *zFormat, ...){ 1050 va_list ap; 1051 StrAccum acc; 1052 char zBuf[500]; 1053 sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0); 1054 va_start(ap,zFormat); 1055 sqlite3VXPrintf(&acc, 0, zFormat, ap); 1056 va_end(ap); 1057 sqlite3StrAccumFinish(&acc); 1058 fprintf(stdout,"%s", zBuf); 1059 fflush(stdout); 1060 } 1061 #endif 1062 1063 1064 /* 1065 ** variable-argument wrapper around sqlite3VXPrintf(). 1066 */ 1067 void sqlite3XPrintf(StrAccum *p, u32 bFlags, const char *zFormat, ...){ 1068 va_list ap; 1069 va_start(ap,zFormat); 1070 sqlite3VXPrintf(p, bFlags, zFormat, ap); 1071 va_end(ap); 1072 } 1073