1 /* 2 ** The "printf" code that follows dates from the 1980's. It is in 3 ** the public domain. The original comments are included here for 4 ** completeness. They are very out-of-date but might be useful as 5 ** an historical reference. Most of the "enhancements" have been backed 6 ** out so that the functionality is now the same as standard printf(). 7 ** 8 ************************************************************************** 9 ** 10 ** This file contains code for a set of "printf"-like routines. These 11 ** routines format strings much like the printf() from the standard C 12 ** library, though the implementation here has enhancements to support 13 ** SQLlite. 14 */ 15 #include "sqliteInt.h" 16 17 /* 18 ** Conversion types fall into various categories as defined by the 19 ** following enumeration. 20 */ 21 #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */ 22 #define etFLOAT 2 /* Floating point. %f */ 23 #define etEXP 3 /* Exponentional notation. %e and %E */ 24 #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */ 25 #define etSIZE 5 /* Return number of characters processed so far. %n */ 26 #define etSTRING 6 /* Strings. %s */ 27 #define etDYNSTRING 7 /* Dynamically allocated strings. %z */ 28 #define etPERCENT 8 /* Percent symbol. %% */ 29 #define etCHARX 9 /* Characters. %c */ 30 /* The rest are extensions, not normally found in printf() */ 31 #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */ 32 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '', 33 NULL pointers replaced by SQL NULL. %Q */ 34 #define etTOKEN 12 /* a pointer to a Token structure */ 35 #define etSRCLIST 13 /* a pointer to a SrcList */ 36 #define etPOINTER 14 /* The %p conversion */ 37 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */ 38 #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */ 39 40 #define etINVALID 0 /* Any unrecognized conversion type */ 41 42 43 /* 44 ** An "etByte" is an 8-bit unsigned value. 45 */ 46 typedef unsigned char etByte; 47 48 /* 49 ** Each builtin conversion character (ex: the 'd' in "%d") is described 50 ** by an instance of the following structure 51 */ 52 typedef struct et_info { /* Information about each format field */ 53 char fmttype; /* The format field code letter */ 54 etByte base; /* The base for radix conversion */ 55 etByte flags; /* One or more of FLAG_ constants below */ 56 etByte type; /* Conversion paradigm */ 57 etByte charset; /* Offset into aDigits[] of the digits string */ 58 etByte prefix; /* Offset into aPrefix[] of the prefix string */ 59 } et_info; 60 61 /* 62 ** Allowed values for et_info.flags 63 */ 64 #define FLAG_SIGNED 1 /* True if the value to convert is signed */ 65 #define FLAG_INTERN 2 /* True if for internal use only */ 66 #define FLAG_STRING 4 /* Allow infinity precision */ 67 68 69 /* 70 ** The following table is searched linearly, so it is good to put the 71 ** most frequently used conversion types first. 72 */ 73 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef"; 74 static const char aPrefix[] = "-x0\000X0"; 75 static const et_info fmtinfo[] = { 76 { 'd', 10, 1, etRADIX, 0, 0 }, 77 { 's', 0, 4, etSTRING, 0, 0 }, 78 { 'g', 0, 1, etGENERIC, 30, 0 }, 79 { 'z', 0, 4, etDYNSTRING, 0, 0 }, 80 { 'q', 0, 4, etSQLESCAPE, 0, 0 }, 81 { 'Q', 0, 4, etSQLESCAPE2, 0, 0 }, 82 { 'w', 0, 4, etSQLESCAPE3, 0, 0 }, 83 { 'c', 0, 0, etCHARX, 0, 0 }, 84 { 'o', 8, 0, etRADIX, 0, 2 }, 85 { 'u', 10, 0, etRADIX, 0, 0 }, 86 { 'x', 16, 0, etRADIX, 16, 1 }, 87 { 'X', 16, 0, etRADIX, 0, 4 }, 88 #ifndef SQLITE_OMIT_FLOATING_POINT 89 { 'f', 0, 1, etFLOAT, 0, 0 }, 90 { 'e', 0, 1, etEXP, 30, 0 }, 91 { 'E', 0, 1, etEXP, 14, 0 }, 92 { 'G', 0, 1, etGENERIC, 14, 0 }, 93 #endif 94 { 'i', 10, 1, etRADIX, 0, 0 }, 95 { 'n', 0, 0, etSIZE, 0, 0 }, 96 { '%', 0, 0, etPERCENT, 0, 0 }, 97 { 'p', 16, 0, etPOINTER, 0, 1 }, 98 99 /* All the rest have the FLAG_INTERN bit set and are thus for internal 100 ** use only */ 101 { 'T', 0, 2, etTOKEN, 0, 0 }, 102 { 'S', 0, 2, etSRCLIST, 0, 0 }, 103 { 'r', 10, 3, etORDINAL, 0, 0 }, 104 }; 105 106 /* 107 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point 108 ** conversions will work. 109 */ 110 #ifndef SQLITE_OMIT_FLOATING_POINT 111 /* 112 ** "*val" is a double such that 0.1 <= *val < 10.0 113 ** Return the ascii code for the leading digit of *val, then 114 ** multiply "*val" by 10.0 to renormalize. 115 ** 116 ** Example: 117 ** input: *val = 3.14159 118 ** output: *val = 1.4159 function return = '3' 119 ** 120 ** The counter *cnt is incremented each time. After counter exceeds 121 ** 16 (the number of significant digits in a 64-bit float) '0' is 122 ** always returned. 123 */ 124 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){ 125 int digit; 126 LONGDOUBLE_TYPE d; 127 if( (*cnt)<=0 ) return '0'; 128 (*cnt)--; 129 digit = (int)*val; 130 d = digit; 131 digit += '0'; 132 *val = (*val - d)*10.0; 133 return (char)digit; 134 } 135 #endif /* SQLITE_OMIT_FLOATING_POINT */ 136 137 /* 138 ** Set the StrAccum object to an error mode. 139 */ 140 static void setStrAccumError(StrAccum *p, u8 eError){ 141 p->accError = eError; 142 p->nAlloc = 0; 143 } 144 145 /* 146 ** Extra argument values from a PrintfArguments object 147 */ 148 static sqlite3_int64 getIntArg(PrintfArguments *p){ 149 if( p->nArg<=p->nUsed ) return 0; 150 return sqlite3_value_int64(p->apArg[p->nUsed++]); 151 } 152 static double getDoubleArg(PrintfArguments *p){ 153 if( p->nArg<=p->nUsed ) return 0.0; 154 return sqlite3_value_double(p->apArg[p->nUsed++]); 155 } 156 static char *getTextArg(PrintfArguments *p){ 157 if( p->nArg<=p->nUsed ) return 0; 158 return (char*)sqlite3_value_text(p->apArg[p->nUsed++]); 159 } 160 161 162 /* 163 ** On machines with a small stack size, you can redefine the 164 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired. 165 */ 166 #ifndef SQLITE_PRINT_BUF_SIZE 167 # define SQLITE_PRINT_BUF_SIZE 70 168 #endif 169 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */ 170 171 /* 172 ** Render a string given by "fmt" into the StrAccum object. 173 */ 174 void sqlite3VXPrintf( 175 StrAccum *pAccum, /* Accumulate results here */ 176 u32 bFlags, /* SQLITE_PRINTF_* flags */ 177 const char *fmt, /* Format string */ 178 va_list ap /* arguments */ 179 ){ 180 int c; /* Next character in the format string */ 181 char *bufpt; /* Pointer to the conversion buffer */ 182 int precision; /* Precision of the current field */ 183 int length; /* Length of the field */ 184 int idx; /* A general purpose loop counter */ 185 int width; /* Width of the current field */ 186 etByte flag_leftjustify; /* True if "-" flag is present */ 187 etByte flag_plussign; /* True if "+" flag is present */ 188 etByte flag_blanksign; /* True if " " flag is present */ 189 etByte flag_alternateform; /* True if "#" flag is present */ 190 etByte flag_altform2; /* True if "!" flag is present */ 191 etByte flag_zeropad; /* True if field width constant starts with zero */ 192 etByte flag_long; /* True if "l" flag is present */ 193 etByte flag_longlong; /* True if the "ll" flag is present */ 194 etByte done; /* Loop termination flag */ 195 etByte xtype = 0; /* Conversion paradigm */ 196 u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */ 197 u8 useIntern; /* Ok to use internal conversions (ex: %T) */ 198 char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */ 199 sqlite_uint64 longvalue; /* Value for integer types */ 200 LONGDOUBLE_TYPE realvalue; /* Value for real types */ 201 const et_info *infop; /* Pointer to the appropriate info structure */ 202 char *zOut; /* Rendering buffer */ 203 int nOut; /* Size of the rendering buffer */ 204 char *zExtra = 0; /* Malloced memory used by some conversion */ 205 #ifndef SQLITE_OMIT_FLOATING_POINT 206 int exp, e2; /* exponent of real numbers */ 207 int nsd; /* Number of significant digits returned */ 208 double rounder; /* Used for rounding floating point values */ 209 etByte flag_dp; /* True if decimal point should be shown */ 210 etByte flag_rtz; /* True if trailing zeros should be removed */ 211 #endif 212 PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */ 213 char buf[etBUFSIZE]; /* Conversion buffer */ 214 215 #ifdef SQLITE_ENABLE_API_ARMOR 216 if( ap==0 ){ 217 (void)SQLITE_MISUSE_BKPT; 218 sqlite3StrAccumReset(pAccum); 219 return; 220 } 221 #endif 222 bufpt = 0; 223 if( bFlags ){ 224 if( (bArgList = (bFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){ 225 pArgList = va_arg(ap, PrintfArguments*); 226 } 227 useIntern = bFlags & SQLITE_PRINTF_INTERNAL; 228 }else{ 229 bArgList = useIntern = 0; 230 } 231 for(; (c=(*fmt))!=0; ++fmt){ 232 if( c!='%' ){ 233 bufpt = (char *)fmt; 234 #if HAVE_STRCHRNUL 235 fmt = strchrnul(fmt, '%'); 236 #else 237 do{ fmt++; }while( *fmt && *fmt != '%' ); 238 #endif 239 sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt)); 240 if( *fmt==0 ) break; 241 } 242 if( (c=(*++fmt))==0 ){ 243 sqlite3StrAccumAppend(pAccum, "%", 1); 244 break; 245 } 246 /* Find out what flags are present */ 247 flag_leftjustify = flag_plussign = flag_blanksign = 248 flag_alternateform = flag_altform2 = flag_zeropad = 0; 249 done = 0; 250 do{ 251 switch( c ){ 252 case '-': flag_leftjustify = 1; break; 253 case '+': flag_plussign = 1; break; 254 case ' ': flag_blanksign = 1; break; 255 case '#': flag_alternateform = 1; break; 256 case '!': flag_altform2 = 1; break; 257 case '0': flag_zeropad = 1; break; 258 default: done = 1; break; 259 } 260 }while( !done && (c=(*++fmt))!=0 ); 261 /* Get the field width */ 262 width = 0; 263 if( c=='*' ){ 264 if( bArgList ){ 265 width = (int)getIntArg(pArgList); 266 }else{ 267 width = va_arg(ap,int); 268 } 269 if( width<0 ){ 270 flag_leftjustify = 1; 271 width = -width; 272 } 273 c = *++fmt; 274 }else{ 275 while( c>='0' && c<='9' ){ 276 width = width*10 + c - '0'; 277 c = *++fmt; 278 } 279 } 280 /* Get the precision */ 281 if( c=='.' ){ 282 precision = 0; 283 c = *++fmt; 284 if( c=='*' ){ 285 if( bArgList ){ 286 precision = (int)getIntArg(pArgList); 287 }else{ 288 precision = va_arg(ap,int); 289 } 290 if( precision<0 ) precision = -precision; 291 c = *++fmt; 292 }else{ 293 while( c>='0' && c<='9' ){ 294 precision = precision*10 + c - '0'; 295 c = *++fmt; 296 } 297 } 298 }else{ 299 precision = -1; 300 } 301 /* Get the conversion type modifier */ 302 if( c=='l' ){ 303 flag_long = 1; 304 c = *++fmt; 305 if( c=='l' ){ 306 flag_longlong = 1; 307 c = *++fmt; 308 }else{ 309 flag_longlong = 0; 310 } 311 }else{ 312 flag_long = flag_longlong = 0; 313 } 314 /* Fetch the info entry for the field */ 315 infop = &fmtinfo[0]; 316 xtype = etINVALID; 317 for(idx=0; idx<ArraySize(fmtinfo); idx++){ 318 if( c==fmtinfo[idx].fmttype ){ 319 infop = &fmtinfo[idx]; 320 if( useIntern || (infop->flags & FLAG_INTERN)==0 ){ 321 xtype = infop->type; 322 }else{ 323 return; 324 } 325 break; 326 } 327 } 328 329 /* 330 ** At this point, variables are initialized as follows: 331 ** 332 ** flag_alternateform TRUE if a '#' is present. 333 ** flag_altform2 TRUE if a '!' is present. 334 ** flag_plussign TRUE if a '+' is present. 335 ** flag_leftjustify TRUE if a '-' is present or if the 336 ** field width was negative. 337 ** flag_zeropad TRUE if the width began with 0. 338 ** flag_long TRUE if the letter 'l' (ell) prefixed 339 ** the conversion character. 340 ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed 341 ** the conversion character. 342 ** flag_blanksign TRUE if a ' ' is present. 343 ** width The specified field width. This is 344 ** always non-negative. Zero is the default. 345 ** precision The specified precision. The default 346 ** is -1. 347 ** xtype The class of the conversion. 348 ** infop Pointer to the appropriate info struct. 349 */ 350 switch( xtype ){ 351 case etPOINTER: 352 flag_longlong = sizeof(char*)==sizeof(i64); 353 flag_long = sizeof(char*)==sizeof(long int); 354 /* Fall through into the next case */ 355 case etORDINAL: 356 case etRADIX: 357 if( infop->flags & FLAG_SIGNED ){ 358 i64 v; 359 if( bArgList ){ 360 v = getIntArg(pArgList); 361 }else if( flag_longlong ){ 362 v = va_arg(ap,i64); 363 }else if( flag_long ){ 364 v = va_arg(ap,long int); 365 }else{ 366 v = va_arg(ap,int); 367 } 368 if( v<0 ){ 369 if( v==SMALLEST_INT64 ){ 370 longvalue = ((u64)1)<<63; 371 }else{ 372 longvalue = -v; 373 } 374 prefix = '-'; 375 }else{ 376 longvalue = v; 377 if( flag_plussign ) prefix = '+'; 378 else if( flag_blanksign ) prefix = ' '; 379 else prefix = 0; 380 } 381 }else{ 382 if( bArgList ){ 383 longvalue = (u64)getIntArg(pArgList); 384 }else if( flag_longlong ){ 385 longvalue = va_arg(ap,u64); 386 }else if( flag_long ){ 387 longvalue = va_arg(ap,unsigned long int); 388 }else{ 389 longvalue = va_arg(ap,unsigned int); 390 } 391 prefix = 0; 392 } 393 if( longvalue==0 ) flag_alternateform = 0; 394 if( flag_zeropad && precision<width-(prefix!=0) ){ 395 precision = width-(prefix!=0); 396 } 397 if( precision<etBUFSIZE-10 ){ 398 nOut = etBUFSIZE; 399 zOut = buf; 400 }else{ 401 nOut = precision + 10; 402 zOut = zExtra = sqlite3Malloc( nOut ); 403 if( zOut==0 ){ 404 setStrAccumError(pAccum, STRACCUM_NOMEM); 405 return; 406 } 407 } 408 bufpt = &zOut[nOut-1]; 409 if( xtype==etORDINAL ){ 410 static const char zOrd[] = "thstndrd"; 411 int x = (int)(longvalue % 10); 412 if( x>=4 || (longvalue/10)%10==1 ){ 413 x = 0; 414 } 415 *(--bufpt) = zOrd[x*2+1]; 416 *(--bufpt) = zOrd[x*2]; 417 } 418 { 419 const char *cset = &aDigits[infop->charset]; 420 u8 base = infop->base; 421 do{ /* Convert to ascii */ 422 *(--bufpt) = cset[longvalue%base]; 423 longvalue = longvalue/base; 424 }while( longvalue>0 ); 425 } 426 length = (int)(&zOut[nOut-1]-bufpt); 427 for(idx=precision-length; idx>0; idx--){ 428 *(--bufpt) = '0'; /* Zero pad */ 429 } 430 if( prefix ) *(--bufpt) = prefix; /* Add sign */ 431 if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */ 432 const char *pre; 433 char x; 434 pre = &aPrefix[infop->prefix]; 435 for(; (x=(*pre))!=0; pre++) *(--bufpt) = x; 436 } 437 length = (int)(&zOut[nOut-1]-bufpt); 438 break; 439 case etFLOAT: 440 case etEXP: 441 case etGENERIC: 442 if( bArgList ){ 443 realvalue = getDoubleArg(pArgList); 444 }else{ 445 realvalue = va_arg(ap,double); 446 } 447 #ifdef SQLITE_OMIT_FLOATING_POINT 448 length = 0; 449 #else 450 if( precision<0 ) precision = 6; /* Set default precision */ 451 if( realvalue<0.0 ){ 452 realvalue = -realvalue; 453 prefix = '-'; 454 }else{ 455 if( flag_plussign ) prefix = '+'; 456 else if( flag_blanksign ) prefix = ' '; 457 else prefix = 0; 458 } 459 if( xtype==etGENERIC && precision>0 ) precision--; 460 for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){} 461 if( xtype==etFLOAT ) realvalue += rounder; 462 /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */ 463 exp = 0; 464 if( sqlite3IsNaN((double)realvalue) ){ 465 bufpt = "NaN"; 466 length = 3; 467 break; 468 } 469 if( realvalue>0.0 ){ 470 LONGDOUBLE_TYPE scale = 1.0; 471 while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;} 472 while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; } 473 while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; } 474 while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; } 475 realvalue /= scale; 476 while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; } 477 while( realvalue<1.0 ){ realvalue *= 10.0; exp--; } 478 if( exp>350 ){ 479 if( prefix=='-' ){ 480 bufpt = "-Inf"; 481 }else if( prefix=='+' ){ 482 bufpt = "+Inf"; 483 }else{ 484 bufpt = "Inf"; 485 } 486 length = sqlite3Strlen30(bufpt); 487 break; 488 } 489 } 490 bufpt = buf; 491 /* 492 ** If the field type is etGENERIC, then convert to either etEXP 493 ** or etFLOAT, as appropriate. 494 */ 495 if( xtype!=etFLOAT ){ 496 realvalue += rounder; 497 if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; } 498 } 499 if( xtype==etGENERIC ){ 500 flag_rtz = !flag_alternateform; 501 if( exp<-4 || exp>precision ){ 502 xtype = etEXP; 503 }else{ 504 precision = precision - exp; 505 xtype = etFLOAT; 506 } 507 }else{ 508 flag_rtz = flag_altform2; 509 } 510 if( xtype==etEXP ){ 511 e2 = 0; 512 }else{ 513 e2 = exp; 514 } 515 if( MAX(e2,0)+precision+width > etBUFSIZE - 15 ){ 516 bufpt = zExtra = sqlite3Malloc( MAX(e2,0)+precision+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+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->useMalloc ){ 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->useMalloc==1 ){ 775 zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc); 776 }else{ 777 zNew = sqlite3_realloc(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 if( p->nChar+N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ) return; 798 while( (N--)>0 ) p->zText[p->nChar++] = c; 799 } 800 801 /* 802 ** The StrAccum "p" is not large enough to accept N new bytes of z[]. 803 ** So enlarge if first, then do the append. 804 ** 805 ** This is a helper routine to sqlite3StrAccumAppend() that does special-case 806 ** work (enlarging the buffer) using tail recursion, so that the 807 ** sqlite3StrAccumAppend() routine can use fast calling semantics. 808 */ 809 static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){ 810 N = sqlite3StrAccumEnlarge(p, N); 811 if( N>0 ){ 812 memcpy(&p->zText[p->nChar], z, N); 813 p->nChar += N; 814 } 815 } 816 817 /* 818 ** Append N bytes of text from z to the StrAccum object. Increase the 819 ** size of the memory allocation for StrAccum if necessary. 820 */ 821 void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){ 822 assert( z!=0 ); 823 assert( p->zText!=0 || p->nChar==0 || p->accError ); 824 assert( N>=0 ); 825 assert( p->accError==0 || p->nAlloc==0 ); 826 if( p->nChar+N >= p->nAlloc ){ 827 enlargeAndAppend(p,z,N); 828 }else{ 829 assert( p->zText ); 830 p->nChar += N; 831 memcpy(&p->zText[p->nChar-N], z, N); 832 } 833 } 834 835 /* 836 ** Append the complete text of zero-terminated string z[] to the p string. 837 */ 838 void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){ 839 sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z)); 840 } 841 842 843 /* 844 ** Finish off a string by making sure it is zero-terminated. 845 ** Return a pointer to the resulting string. Return a NULL 846 ** pointer if any kind of error was encountered. 847 */ 848 char *sqlite3StrAccumFinish(StrAccum *p){ 849 if( p->zText ){ 850 p->zText[p->nChar] = 0; 851 if( p->useMalloc && p->zText==p->zBase ){ 852 if( p->useMalloc==1 ){ 853 p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 ); 854 }else{ 855 p->zText = sqlite3_malloc(p->nChar+1); 856 } 857 if( p->zText ){ 858 memcpy(p->zText, p->zBase, p->nChar+1); 859 }else{ 860 setStrAccumError(p, STRACCUM_NOMEM); 861 } 862 } 863 } 864 return p->zText; 865 } 866 867 /* 868 ** Reset an StrAccum string. Reclaim all malloced memory. 869 */ 870 void sqlite3StrAccumReset(StrAccum *p){ 871 if( p->zText!=p->zBase ){ 872 if( p->useMalloc==1 ){ 873 sqlite3DbFree(p->db, p->zText); 874 }else{ 875 sqlite3_free(p->zText); 876 } 877 } 878 p->zText = 0; 879 } 880 881 /* 882 ** Initialize a string accumulator 883 */ 884 void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){ 885 p->zText = p->zBase = zBase; 886 p->db = 0; 887 p->nChar = 0; 888 p->nAlloc = n; 889 p->mxAlloc = mx; 890 p->useMalloc = 1; 891 p->accError = 0; 892 } 893 894 /* 895 ** Print into memory obtained from sqliteMalloc(). Use the internal 896 ** %-conversion extensions. 897 */ 898 char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){ 899 char *z; 900 char zBase[SQLITE_PRINT_BUF_SIZE]; 901 StrAccum acc; 902 assert( db!=0 ); 903 sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), 904 db->aLimit[SQLITE_LIMIT_LENGTH]); 905 acc.db = db; 906 sqlite3VXPrintf(&acc, SQLITE_PRINTF_INTERNAL, zFormat, ap); 907 z = sqlite3StrAccumFinish(&acc); 908 if( acc.accError==STRACCUM_NOMEM ){ 909 db->mallocFailed = 1; 910 } 911 return z; 912 } 913 914 /* 915 ** Print into memory obtained from sqliteMalloc(). Use the internal 916 ** %-conversion extensions. 917 */ 918 char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){ 919 va_list ap; 920 char *z; 921 va_start(ap, zFormat); 922 z = sqlite3VMPrintf(db, zFormat, ap); 923 va_end(ap); 924 return z; 925 } 926 927 /* 928 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting 929 ** the string and before returning. This routine is intended to be used 930 ** to modify an existing string. For example: 931 ** 932 ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x); 933 ** 934 */ 935 char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){ 936 va_list ap; 937 char *z; 938 va_start(ap, zFormat); 939 z = sqlite3VMPrintf(db, zFormat, ap); 940 va_end(ap); 941 sqlite3DbFree(db, zStr); 942 return z; 943 } 944 945 /* 946 ** Print into memory obtained from sqlite3_malloc(). Omit the internal 947 ** %-conversion extensions. 948 */ 949 char *sqlite3_vmprintf(const char *zFormat, va_list ap){ 950 char *z; 951 char zBase[SQLITE_PRINT_BUF_SIZE]; 952 StrAccum acc; 953 954 #ifdef SQLITE_ENABLE_API_ARMOR 955 if( zFormat==0 ){ 956 (void)SQLITE_MISUSE_BKPT; 957 return 0; 958 } 959 #endif 960 #ifndef SQLITE_OMIT_AUTOINIT 961 if( sqlite3_initialize() ) return 0; 962 #endif 963 sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH); 964 acc.useMalloc = 2; 965 sqlite3VXPrintf(&acc, 0, zFormat, ap); 966 z = sqlite3StrAccumFinish(&acc); 967 return z; 968 } 969 970 /* 971 ** Print into memory obtained from sqlite3_malloc()(). Omit the internal 972 ** %-conversion extensions. 973 */ 974 char *sqlite3_mprintf(const char *zFormat, ...){ 975 va_list ap; 976 char *z; 977 #ifndef SQLITE_OMIT_AUTOINIT 978 if( sqlite3_initialize() ) return 0; 979 #endif 980 va_start(ap, zFormat); 981 z = sqlite3_vmprintf(zFormat, ap); 982 va_end(ap); 983 return z; 984 } 985 986 /* 987 ** sqlite3_snprintf() works like snprintf() except that it ignores the 988 ** current locale settings. This is important for SQLite because we 989 ** are not able to use a "," as the decimal point in place of "." as 990 ** specified by some locales. 991 ** 992 ** Oops: The first two arguments of sqlite3_snprintf() are backwards 993 ** from the snprintf() standard. Unfortunately, it is too late to change 994 ** this without breaking compatibility, so we just have to live with the 995 ** mistake. 996 ** 997 ** sqlite3_vsnprintf() is the varargs version. 998 */ 999 char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){ 1000 StrAccum acc; 1001 if( n<=0 ) return zBuf; 1002 #ifdef SQLITE_ENABLE_API_ARMOR 1003 if( zBuf==0 || zFormat==0 ) { 1004 (void)SQLITE_MISUSE_BKPT; 1005 if( zBuf && n>0 ) zBuf[0] = 0; 1006 return zBuf; 1007 } 1008 #endif 1009 sqlite3StrAccumInit(&acc, zBuf, n, 0); 1010 acc.useMalloc = 0; 1011 sqlite3VXPrintf(&acc, 0, zFormat, ap); 1012 return sqlite3StrAccumFinish(&acc); 1013 } 1014 char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){ 1015 char *z; 1016 va_list ap; 1017 va_start(ap,zFormat); 1018 z = sqlite3_vsnprintf(n, zBuf, zFormat, ap); 1019 va_end(ap); 1020 return z; 1021 } 1022 1023 /* 1024 ** This is the routine that actually formats the sqlite3_log() message. 1025 ** We house it in a separate routine from sqlite3_log() to avoid using 1026 ** stack space on small-stack systems when logging is disabled. 1027 ** 1028 ** sqlite3_log() must render into a static buffer. It cannot dynamically 1029 ** allocate memory because it might be called while the memory allocator 1030 ** mutex is held. 1031 */ 1032 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){ 1033 StrAccum acc; /* String accumulator */ 1034 char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */ 1035 1036 sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0); 1037 acc.useMalloc = 0; 1038 sqlite3VXPrintf(&acc, 0, zFormat, ap); 1039 sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode, 1040 sqlite3StrAccumFinish(&acc)); 1041 } 1042 1043 /* 1044 ** Format and write a message to the log if logging is enabled. 1045 */ 1046 void sqlite3_log(int iErrCode, const char *zFormat, ...){ 1047 va_list ap; /* Vararg list */ 1048 if( sqlite3GlobalConfig.xLog ){ 1049 va_start(ap, zFormat); 1050 renderLogMsg(iErrCode, zFormat, ap); 1051 va_end(ap); 1052 } 1053 } 1054 1055 #if defined(SQLITE_DEBUG) 1056 /* 1057 ** A version of printf() that understands %lld. Used for debugging. 1058 ** The printf() built into some versions of windows does not understand %lld 1059 ** and segfaults if you give it a long long int. 1060 */ 1061 void sqlite3DebugPrintf(const char *zFormat, ...){ 1062 va_list ap; 1063 StrAccum acc; 1064 char zBuf[500]; 1065 sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0); 1066 acc.useMalloc = 0; 1067 va_start(ap,zFormat); 1068 sqlite3VXPrintf(&acc, 0, zFormat, ap); 1069 va_end(ap); 1070 sqlite3StrAccumFinish(&acc); 1071 fprintf(stdout,"%s", zBuf); 1072 fflush(stdout); 1073 } 1074 #endif 1075 1076 #ifdef SQLITE_DEBUG 1077 /************************************************************************* 1078 ** Routines for implementing the "TreeView" display of hierarchical 1079 ** data structures for debugging. 1080 ** 1081 ** The main entry points (coded elsewhere) are: 1082 ** sqlite3TreeViewExpr(0, pExpr, 0); 1083 ** sqlite3TreeViewExprList(0, pList, 0, 0); 1084 ** sqlite3TreeViewSelect(0, pSelect, 0); 1085 ** Insert calls to those routines while debugging in order to display 1086 ** a diagram of Expr, ExprList, and Select objects. 1087 ** 1088 */ 1089 /* Add a new subitem to the tree. The moreToFollow flag indicates that this 1090 ** is not the last item in the tree. */ 1091 TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){ 1092 if( p==0 ){ 1093 p = sqlite3_malloc( sizeof(*p) ); 1094 if( p==0 ) return 0; 1095 memset(p, 0, sizeof(*p)); 1096 }else{ 1097 p->iLevel++; 1098 } 1099 assert( moreToFollow==0 || moreToFollow==1 ); 1100 if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow; 1101 return p; 1102 } 1103 /* Finished with one layer of the tree */ 1104 void sqlite3TreeViewPop(TreeView *p){ 1105 if( p==0 ) return; 1106 p->iLevel--; 1107 if( p->iLevel<0 ) sqlite3_free(p); 1108 } 1109 /* Generate a single line of output for the tree, with a prefix that contains 1110 ** all the appropriate tree lines */ 1111 void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){ 1112 va_list ap; 1113 int i; 1114 StrAccum acc; 1115 char zBuf[500]; 1116 sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0); 1117 acc.useMalloc = 0; 1118 if( p ){ 1119 for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){ 1120 sqlite3StrAccumAppend(&acc, p->bLine[i] ? "| " : " ", 4); 1121 } 1122 sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4); 1123 } 1124 va_start(ap, zFormat); 1125 sqlite3VXPrintf(&acc, 0, zFormat, ap); 1126 va_end(ap); 1127 if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1); 1128 sqlite3StrAccumFinish(&acc); 1129 fprintf(stdout,"%s", zBuf); 1130 fflush(stdout); 1131 } 1132 /* Shorthand for starting a new tree item that consists of a single label */ 1133 void sqlite3TreeViewItem(TreeView *p, const char *zLabel, u8 moreToFollow){ 1134 p = sqlite3TreeViewPush(p, moreToFollow); 1135 sqlite3TreeViewLine(p, "%s", zLabel); 1136 } 1137 #endif /* SQLITE_DEBUG */ 1138 1139 /* 1140 ** variable-argument wrapper around sqlite3VXPrintf(). 1141 */ 1142 void sqlite3XPrintf(StrAccum *p, u32 bFlags, const char *zFormat, ...){ 1143 va_list ap; 1144 va_start(ap,zFormat); 1145 sqlite3VXPrintf(p, bFlags, zFormat, ap); 1146 va_end(ap); 1147 } 1148