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 0 /* non-decimal integer types. %x %o */
19 #define etFLOAT 1 /* Floating point. %f */
20 #define etEXP 2 /* Exponentional notation. %e and %E */
21 #define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */
22 #define etSIZE 4 /* Return number of characters processed so far. %n */
23 #define etSTRING 5 /* Strings. %s */
24 #define etDYNSTRING 6 /* Dynamically allocated strings. %z */
25 #define etPERCENT 7 /* Percent symbol. %% */
26 #define etCHARX 8 /* Characters. %c */
27 /* The rest are extensions, not normally found in printf() */
28 #define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */
29 #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
30 NULL pointers replaced by SQL NULL. %Q */
31 #define etTOKEN 11 /* a pointer to a Token structure */
32 #define etSRCLIST 12 /* a pointer to a SrcList */
33 #define etPOINTER 13 /* The %p conversion */
34 #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
35 #define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
36 #define etDECIMAL 16 /* %d or %u, but not %x, %o */
37
38 #define etINVALID 17 /* Any unrecognized conversion type */
39
40
41 /*
42 ** An "etByte" is an 8-bit unsigned value.
43 */
44 typedef unsigned char etByte;
45
46 /*
47 ** Each builtin conversion character (ex: the 'd' in "%d") is described
48 ** by an instance of the following structure
49 */
50 typedef struct et_info { /* Information about each format field */
51 char fmttype; /* The format field code letter */
52 etByte base; /* The base for radix conversion */
53 etByte flags; /* One or more of FLAG_ constants below */
54 etByte type; /* Conversion paradigm */
55 etByte charset; /* Offset into aDigits[] of the digits string */
56 etByte prefix; /* Offset into aPrefix[] of the prefix string */
57 } et_info;
58
59 /*
60 ** Allowed values for et_info.flags
61 */
62 #define FLAG_SIGNED 1 /* True if the value to convert is signed */
63 #define FLAG_STRING 4 /* Allow infinite 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, etDECIMAL, 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, etDECIMAL, 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, etDECIMAL, 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 are undocumented and are for internal use only */
97 { 'T', 0, 0, etTOKEN, 0, 0 },
98 { 'S', 0, 0, etSRCLIST, 0, 0 },
99 { 'r', 10, 1, etORDINAL, 0, 0 },
100 };
101
102 /* Floating point constants used for rounding */
103 static const double arRound[] = {
104 5.0e-01, 5.0e-02, 5.0e-03, 5.0e-04, 5.0e-05,
105 5.0e-06, 5.0e-07, 5.0e-08, 5.0e-09, 5.0e-10,
106 };
107
108 /*
109 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
110 ** conversions will work.
111 */
112 #ifndef SQLITE_OMIT_FLOATING_POINT
113 /*
114 ** "*val" is a double such that 0.1 <= *val < 10.0
115 ** Return the ascii code for the leading digit of *val, then
116 ** multiply "*val" by 10.0 to renormalize.
117 **
118 ** Example:
119 ** input: *val = 3.14159
120 ** output: *val = 1.4159 function return = '3'
121 **
122 ** The counter *cnt is incremented each time. After counter exceeds
123 ** 16 (the number of significant digits in a 64-bit float) '0' is
124 ** always returned.
125 */
et_getdigit(LONGDOUBLE_TYPE * val,int * cnt)126 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
127 int digit;
128 LONGDOUBLE_TYPE d;
129 if( (*cnt)<=0 ) return '0';
130 (*cnt)--;
131 digit = (int)*val;
132 d = digit;
133 digit += '0';
134 *val = (*val - d)*10.0;
135 return (char)digit;
136 }
137 #endif /* SQLITE_OMIT_FLOATING_POINT */
138
139 /*
140 ** Set the StrAccum object to an error mode.
141 */
setStrAccumError(StrAccum * p,u8 eError)142 static void setStrAccumError(StrAccum *p, u8 eError){
143 assert( eError==SQLITE_NOMEM || eError==SQLITE_TOOBIG );
144 p->accError = eError;
145 if( p->mxAlloc ) sqlite3_str_reset(p);
146 if( eError==SQLITE_TOOBIG ) sqlite3ErrorToParser(p->db, eError);
147 }
148
149 /*
150 ** Extra argument values from a PrintfArguments object
151 */
getIntArg(PrintfArguments * p)152 static sqlite3_int64 getIntArg(PrintfArguments *p){
153 if( p->nArg<=p->nUsed ) return 0;
154 return sqlite3_value_int64(p->apArg[p->nUsed++]);
155 }
getDoubleArg(PrintfArguments * p)156 static double getDoubleArg(PrintfArguments *p){
157 if( p->nArg<=p->nUsed ) return 0.0;
158 return sqlite3_value_double(p->apArg[p->nUsed++]);
159 }
getTextArg(PrintfArguments * p)160 static char *getTextArg(PrintfArguments *p){
161 if( p->nArg<=p->nUsed ) return 0;
162 return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
163 }
164
165 /*
166 ** Allocate memory for a temporary buffer needed for printf rendering.
167 **
168 ** If the requested size of the temp buffer is larger than the size
169 ** of the output buffer in pAccum, then cause an SQLITE_TOOBIG error.
170 ** Do the size check before the memory allocation to prevent rogue
171 ** SQL from requesting large allocations using the precision or width
172 ** field of the printf() function.
173 */
printfTempBuf(sqlite3_str * pAccum,sqlite3_int64 n)174 static char *printfTempBuf(sqlite3_str *pAccum, sqlite3_int64 n){
175 char *z;
176 if( pAccum->accError ) return 0;
177 if( n>pAccum->nAlloc && n>pAccum->mxAlloc ){
178 setStrAccumError(pAccum, SQLITE_TOOBIG);
179 return 0;
180 }
181 z = sqlite3DbMallocRaw(pAccum->db, n);
182 if( z==0 ){
183 setStrAccumError(pAccum, SQLITE_NOMEM);
184 }
185 return z;
186 }
187
188 /*
189 ** On machines with a small stack size, you can redefine the
190 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
191 */
192 #ifndef SQLITE_PRINT_BUF_SIZE
193 # define SQLITE_PRINT_BUF_SIZE 70
194 #endif
195 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
196
197 /*
198 ** Hard limit on the precision of floating-point conversions.
199 */
200 #ifndef SQLITE_PRINTF_PRECISION_LIMIT
201 # define SQLITE_FP_PRECISION_LIMIT 100000000
202 #endif
203
204 /*
205 ** Render a string given by "fmt" into the StrAccum object.
206 */
sqlite3_str_vappendf(sqlite3_str * pAccum,const char * fmt,va_list ap)207 void sqlite3_str_vappendf(
208 sqlite3_str *pAccum, /* Accumulate results here */
209 const char *fmt, /* Format string */
210 va_list ap /* arguments */
211 ){
212 int c; /* Next character in the format string */
213 char *bufpt; /* Pointer to the conversion buffer */
214 int precision; /* Precision of the current field */
215 int length; /* Length of the field */
216 int idx; /* A general purpose loop counter */
217 int width; /* Width of the current field */
218 etByte flag_leftjustify; /* True if "-" flag is present */
219 etByte flag_prefix; /* '+' or ' ' or 0 for prefix */
220 etByte flag_alternateform; /* True if "#" flag is present */
221 etByte flag_altform2; /* True if "!" flag is present */
222 etByte flag_zeropad; /* True if field width constant starts with zero */
223 etByte flag_long; /* 1 for the "l" flag, 2 for "ll", 0 by default */
224 etByte done; /* Loop termination flag */
225 etByte cThousand; /* Thousands separator for %d and %u */
226 etByte xtype = etINVALID; /* Conversion paradigm */
227 u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
228 char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
229 sqlite_uint64 longvalue; /* Value for integer types */
230 LONGDOUBLE_TYPE realvalue; /* Value for real types */
231 const et_info *infop; /* Pointer to the appropriate info structure */
232 char *zOut; /* Rendering buffer */
233 int nOut; /* Size of the rendering buffer */
234 char *zExtra = 0; /* Malloced memory used by some conversion */
235 #ifndef SQLITE_OMIT_FLOATING_POINT
236 int exp, e2; /* exponent of real numbers */
237 int nsd; /* Number of significant digits returned */
238 double rounder; /* Used for rounding floating point values */
239 etByte flag_dp; /* True if decimal point should be shown */
240 etByte flag_rtz; /* True if trailing zeros should be removed */
241 #endif
242 PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
243 char buf[etBUFSIZE]; /* Conversion buffer */
244
245 /* pAccum never starts out with an empty buffer that was obtained from
246 ** malloc(). This precondition is required by the mprintf("%z...")
247 ** optimization. */
248 assert( pAccum->nChar>0 || (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
249
250 bufpt = 0;
251 if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
252 pArgList = va_arg(ap, PrintfArguments*);
253 bArgList = 1;
254 }else{
255 bArgList = 0;
256 }
257 for(; (c=(*fmt))!=0; ++fmt){
258 if( c!='%' ){
259 bufpt = (char *)fmt;
260 #if HAVE_STRCHRNUL
261 fmt = strchrnul(fmt, '%');
262 #else
263 do{ fmt++; }while( *fmt && *fmt != '%' );
264 #endif
265 sqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt));
266 if( *fmt==0 ) break;
267 }
268 if( (c=(*++fmt))==0 ){
269 sqlite3_str_append(pAccum, "%", 1);
270 break;
271 }
272 /* Find out what flags are present */
273 flag_leftjustify = flag_prefix = cThousand =
274 flag_alternateform = flag_altform2 = flag_zeropad = 0;
275 done = 0;
276 width = 0;
277 flag_long = 0;
278 precision = -1;
279 do{
280 switch( c ){
281 case '-': flag_leftjustify = 1; break;
282 case '+': flag_prefix = '+'; break;
283 case ' ': flag_prefix = ' '; break;
284 case '#': flag_alternateform = 1; break;
285 case '!': flag_altform2 = 1; break;
286 case '0': flag_zeropad = 1; break;
287 case ',': cThousand = ','; break;
288 default: done = 1; break;
289 case 'l': {
290 flag_long = 1;
291 c = *++fmt;
292 if( c=='l' ){
293 c = *++fmt;
294 flag_long = 2;
295 }
296 done = 1;
297 break;
298 }
299 case '1': case '2': case '3': case '4': case '5':
300 case '6': case '7': case '8': case '9': {
301 unsigned wx = c - '0';
302 while( (c = *++fmt)>='0' && c<='9' ){
303 wx = wx*10 + c - '0';
304 }
305 testcase( wx>0x7fffffff );
306 width = wx & 0x7fffffff;
307 #ifdef SQLITE_PRINTF_PRECISION_LIMIT
308 if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
309 width = SQLITE_PRINTF_PRECISION_LIMIT;
310 }
311 #endif
312 if( c!='.' && c!='l' ){
313 done = 1;
314 }else{
315 fmt--;
316 }
317 break;
318 }
319 case '*': {
320 if( bArgList ){
321 width = (int)getIntArg(pArgList);
322 }else{
323 width = va_arg(ap,int);
324 }
325 if( width<0 ){
326 flag_leftjustify = 1;
327 width = width >= -2147483647 ? -width : 0;
328 }
329 #ifdef SQLITE_PRINTF_PRECISION_LIMIT
330 if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
331 width = SQLITE_PRINTF_PRECISION_LIMIT;
332 }
333 #endif
334 if( (c = fmt[1])!='.' && c!='l' ){
335 c = *++fmt;
336 done = 1;
337 }
338 break;
339 }
340 case '.': {
341 c = *++fmt;
342 if( c=='*' ){
343 if( bArgList ){
344 precision = (int)getIntArg(pArgList);
345 }else{
346 precision = va_arg(ap,int);
347 }
348 if( precision<0 ){
349 precision = precision >= -2147483647 ? -precision : -1;
350 }
351 c = *++fmt;
352 }else{
353 unsigned px = 0;
354 while( c>='0' && c<='9' ){
355 px = px*10 + c - '0';
356 c = *++fmt;
357 }
358 testcase( px>0x7fffffff );
359 precision = px & 0x7fffffff;
360 }
361 #ifdef SQLITE_PRINTF_PRECISION_LIMIT
362 if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
363 precision = SQLITE_PRINTF_PRECISION_LIMIT;
364 }
365 #endif
366 if( c=='l' ){
367 --fmt;
368 }else{
369 done = 1;
370 }
371 break;
372 }
373 }
374 }while( !done && (c=(*++fmt))!=0 );
375
376 /* Fetch the info entry for the field */
377 infop = &fmtinfo[0];
378 xtype = etINVALID;
379 for(idx=0; idx<ArraySize(fmtinfo); idx++){
380 if( c==fmtinfo[idx].fmttype ){
381 infop = &fmtinfo[idx];
382 xtype = infop->type;
383 break;
384 }
385 }
386
387 /*
388 ** At this point, variables are initialized as follows:
389 **
390 ** flag_alternateform TRUE if a '#' is present.
391 ** flag_altform2 TRUE if a '!' is present.
392 ** flag_prefix '+' or ' ' or zero
393 ** flag_leftjustify TRUE if a '-' is present or if the
394 ** field width was negative.
395 ** flag_zeropad TRUE if the width began with 0.
396 ** flag_long 1 for "l", 2 for "ll"
397 ** width The specified field width. This is
398 ** always non-negative. Zero is the default.
399 ** precision The specified precision. The default
400 ** is -1.
401 ** xtype The class of the conversion.
402 ** infop Pointer to the appropriate info struct.
403 */
404 assert( width>=0 );
405 assert( precision>=(-1) );
406 switch( xtype ){
407 case etPOINTER:
408 flag_long = sizeof(char*)==sizeof(i64) ? 2 :
409 sizeof(char*)==sizeof(long int) ? 1 : 0;
410 /* no break */ deliberate_fall_through
411 case etORDINAL:
412 case etRADIX:
413 cThousand = 0;
414 /* no break */ deliberate_fall_through
415 case etDECIMAL:
416 if( infop->flags & FLAG_SIGNED ){
417 i64 v;
418 if( bArgList ){
419 v = getIntArg(pArgList);
420 }else if( flag_long ){
421 if( flag_long==2 ){
422 v = va_arg(ap,i64) ;
423 }else{
424 v = va_arg(ap,long int);
425 }
426 }else{
427 v = va_arg(ap,int);
428 }
429 if( v<0 ){
430 testcase( v==SMALLEST_INT64 );
431 testcase( v==(-1) );
432 longvalue = ~v;
433 longvalue++;
434 prefix = '-';
435 }else{
436 longvalue = v;
437 prefix = flag_prefix;
438 }
439 }else{
440 if( bArgList ){
441 longvalue = (u64)getIntArg(pArgList);
442 }else if( flag_long ){
443 if( flag_long==2 ){
444 longvalue = va_arg(ap,u64);
445 }else{
446 longvalue = va_arg(ap,unsigned long int);
447 }
448 }else{
449 longvalue = va_arg(ap,unsigned int);
450 }
451 prefix = 0;
452 }
453 if( longvalue==0 ) flag_alternateform = 0;
454 if( flag_zeropad && precision<width-(prefix!=0) ){
455 precision = width-(prefix!=0);
456 }
457 if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
458 nOut = etBUFSIZE;
459 zOut = buf;
460 }else{
461 u64 n;
462 n = (u64)precision + 10;
463 if( cThousand ) n += precision/3;
464 zOut = zExtra = printfTempBuf(pAccum, n);
465 if( zOut==0 ) return;
466 nOut = (int)n;
467 }
468 bufpt = &zOut[nOut-1];
469 if( xtype==etORDINAL ){
470 static const char zOrd[] = "thstndrd";
471 int x = (int)(longvalue % 10);
472 if( x>=4 || (longvalue/10)%10==1 ){
473 x = 0;
474 }
475 *(--bufpt) = zOrd[x*2+1];
476 *(--bufpt) = zOrd[x*2];
477 }
478 {
479 const char *cset = &aDigits[infop->charset];
480 u8 base = infop->base;
481 do{ /* Convert to ascii */
482 *(--bufpt) = cset[longvalue%base];
483 longvalue = longvalue/base;
484 }while( longvalue>0 );
485 }
486 length = (int)(&zOut[nOut-1]-bufpt);
487 while( precision>length ){
488 *(--bufpt) = '0'; /* Zero pad */
489 length++;
490 }
491 if( cThousand ){
492 int nn = (length - 1)/3; /* Number of "," to insert */
493 int ix = (length - 1)%3 + 1;
494 bufpt -= nn;
495 for(idx=0; nn>0; idx++){
496 bufpt[idx] = bufpt[idx+nn];
497 ix--;
498 if( ix==0 ){
499 bufpt[++idx] = cThousand;
500 nn--;
501 ix = 3;
502 }
503 }
504 }
505 if( prefix ) *(--bufpt) = prefix; /* Add sign */
506 if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
507 const char *pre;
508 char x;
509 pre = &aPrefix[infop->prefix];
510 for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
511 }
512 length = (int)(&zOut[nOut-1]-bufpt);
513 break;
514 case etFLOAT:
515 case etEXP:
516 case etGENERIC:
517 if( bArgList ){
518 realvalue = getDoubleArg(pArgList);
519 }else{
520 realvalue = va_arg(ap,double);
521 }
522 #ifdef SQLITE_OMIT_FLOATING_POINT
523 length = 0;
524 #else
525 if( precision<0 ) precision = 6; /* Set default precision */
526 #ifdef SQLITE_FP_PRECISION_LIMIT
527 if( precision>SQLITE_FP_PRECISION_LIMIT ){
528 precision = SQLITE_FP_PRECISION_LIMIT;
529 }
530 #endif
531 if( realvalue<0.0 ){
532 realvalue = -realvalue;
533 prefix = '-';
534 }else{
535 prefix = flag_prefix;
536 }
537 if( xtype==etGENERIC && precision>0 ) precision--;
538 testcase( precision>0xfff );
539 idx = precision & 0xfff;
540 rounder = arRound[idx%10];
541 while( idx>=10 ){ rounder *= 1.0e-10; idx -= 10; }
542 if( xtype==etFLOAT ){
543 double rx = (double)realvalue;
544 sqlite3_uint64 u;
545 int ex;
546 memcpy(&u, &rx, sizeof(u));
547 ex = -1023 + (int)((u>>52)&0x7ff);
548 if( precision+(ex/3) < 15 ) rounder += realvalue*3e-16;
549 realvalue += rounder;
550 }
551 /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
552 exp = 0;
553 if( sqlite3IsNaN((double)realvalue) ){
554 bufpt = "NaN";
555 length = 3;
556 break;
557 }
558 if( realvalue>0.0 ){
559 LONGDOUBLE_TYPE scale = 1.0;
560 while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
561 while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
562 while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
563 realvalue /= scale;
564 while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
565 while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
566 if( exp>350 ){
567 bufpt = buf;
568 buf[0] = prefix;
569 memcpy(buf+(prefix!=0),"Inf",4);
570 length = 3+(prefix!=0);
571 break;
572 }
573 }
574 bufpt = buf;
575 /*
576 ** If the field type is etGENERIC, then convert to either etEXP
577 ** or etFLOAT, as appropriate.
578 */
579 if( xtype!=etFLOAT ){
580 realvalue += rounder;
581 if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
582 }
583 if( xtype==etGENERIC ){
584 flag_rtz = !flag_alternateform;
585 if( exp<-4 || exp>precision ){
586 xtype = etEXP;
587 }else{
588 precision = precision - exp;
589 xtype = etFLOAT;
590 }
591 }else{
592 flag_rtz = flag_altform2;
593 }
594 if( xtype==etEXP ){
595 e2 = 0;
596 }else{
597 e2 = exp;
598 }
599 {
600 i64 szBufNeeded; /* Size of a temporary buffer needed */
601 szBufNeeded = MAX(e2,0)+(i64)precision+(i64)width+15;
602 if( szBufNeeded > etBUFSIZE ){
603 bufpt = zExtra = printfTempBuf(pAccum, szBufNeeded);
604 if( bufpt==0 ) return;
605 }
606 }
607 zOut = bufpt;
608 nsd = 16 + flag_altform2*10;
609 flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
610 /* The sign in front of the number */
611 if( prefix ){
612 *(bufpt++) = prefix;
613 }
614 /* Digits prior to the decimal point */
615 if( e2<0 ){
616 *(bufpt++) = '0';
617 }else{
618 for(; e2>=0; e2--){
619 *(bufpt++) = et_getdigit(&realvalue,&nsd);
620 }
621 }
622 /* The decimal point */
623 if( flag_dp ){
624 *(bufpt++) = '.';
625 }
626 /* "0" digits after the decimal point but before the first
627 ** significant digit of the number */
628 for(e2++; e2<0; precision--, e2++){
629 assert( precision>0 );
630 *(bufpt++) = '0';
631 }
632 /* Significant digits after the decimal point */
633 while( (precision--)>0 ){
634 *(bufpt++) = et_getdigit(&realvalue,&nsd);
635 }
636 /* Remove trailing zeros and the "." if no digits follow the "." */
637 if( flag_rtz && flag_dp ){
638 while( bufpt[-1]=='0' ) *(--bufpt) = 0;
639 assert( bufpt>zOut );
640 if( bufpt[-1]=='.' ){
641 if( flag_altform2 ){
642 *(bufpt++) = '0';
643 }else{
644 *(--bufpt) = 0;
645 }
646 }
647 }
648 /* Add the "eNNN" suffix */
649 if( xtype==etEXP ){
650 *(bufpt++) = aDigits[infop->charset];
651 if( exp<0 ){
652 *(bufpt++) = '-'; exp = -exp;
653 }else{
654 *(bufpt++) = '+';
655 }
656 if( exp>=100 ){
657 *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
658 exp %= 100;
659 }
660 *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
661 *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
662 }
663 *bufpt = 0;
664
665 /* The converted number is in buf[] and zero terminated. Output it.
666 ** Note that the number is in the usual order, not reversed as with
667 ** integer conversions. */
668 length = (int)(bufpt-zOut);
669 bufpt = zOut;
670
671 /* Special case: Add leading zeros if the flag_zeropad flag is
672 ** set and we are not left justified */
673 if( flag_zeropad && !flag_leftjustify && length < width){
674 int i;
675 int nPad = width - length;
676 for(i=width; i>=nPad; i--){
677 bufpt[i] = bufpt[i-nPad];
678 }
679 i = prefix!=0;
680 while( nPad-- ) bufpt[i++] = '0';
681 length = width;
682 }
683 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
684 break;
685 case etSIZE:
686 if( !bArgList ){
687 *(va_arg(ap,int*)) = pAccum->nChar;
688 }
689 length = width = 0;
690 break;
691 case etPERCENT:
692 buf[0] = '%';
693 bufpt = buf;
694 length = 1;
695 break;
696 case etCHARX:
697 if( bArgList ){
698 bufpt = getTextArg(pArgList);
699 length = 1;
700 if( bufpt ){
701 buf[0] = c = *(bufpt++);
702 if( (c&0xc0)==0xc0 ){
703 while( length<4 && (bufpt[0]&0xc0)==0x80 ){
704 buf[length++] = *(bufpt++);
705 }
706 }
707 }else{
708 buf[0] = 0;
709 }
710 }else{
711 unsigned int ch = va_arg(ap,unsigned int);
712 if( ch<0x00080 ){
713 buf[0] = ch & 0xff;
714 length = 1;
715 }else if( ch<0x00800 ){
716 buf[0] = 0xc0 + (u8)((ch>>6)&0x1f);
717 buf[1] = 0x80 + (u8)(ch & 0x3f);
718 length = 2;
719 }else if( ch<0x10000 ){
720 buf[0] = 0xe0 + (u8)((ch>>12)&0x0f);
721 buf[1] = 0x80 + (u8)((ch>>6) & 0x3f);
722 buf[2] = 0x80 + (u8)(ch & 0x3f);
723 length = 3;
724 }else{
725 buf[0] = 0xf0 + (u8)((ch>>18) & 0x07);
726 buf[1] = 0x80 + (u8)((ch>>12) & 0x3f);
727 buf[2] = 0x80 + (u8)((ch>>6) & 0x3f);
728 buf[3] = 0x80 + (u8)(ch & 0x3f);
729 length = 4;
730 }
731 }
732 if( precision>1 ){
733 width -= precision-1;
734 if( width>1 && !flag_leftjustify ){
735 sqlite3_str_appendchar(pAccum, width-1, ' ');
736 width = 0;
737 }
738 while( precision-- > 1 ){
739 sqlite3_str_append(pAccum, buf, length);
740 }
741 }
742 bufpt = buf;
743 flag_altform2 = 1;
744 goto adjust_width_for_utf8;
745 case etSTRING:
746 case etDYNSTRING:
747 if( bArgList ){
748 bufpt = getTextArg(pArgList);
749 xtype = etSTRING;
750 }else{
751 bufpt = va_arg(ap,char*);
752 }
753 if( bufpt==0 ){
754 bufpt = "";
755 }else if( xtype==etDYNSTRING ){
756 if( pAccum->nChar==0
757 && pAccum->mxAlloc
758 && width==0
759 && precision<0
760 && pAccum->accError==0
761 ){
762 /* Special optimization for sqlite3_mprintf("%z..."):
763 ** Extend an existing memory allocation rather than creating
764 ** a new one. */
765 assert( (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
766 pAccum->zText = bufpt;
767 pAccum->nAlloc = sqlite3DbMallocSize(pAccum->db, bufpt);
768 pAccum->nChar = 0x7fffffff & (int)strlen(bufpt);
769 pAccum->printfFlags |= SQLITE_PRINTF_MALLOCED;
770 length = 0;
771 break;
772 }
773 zExtra = bufpt;
774 }
775 if( precision>=0 ){
776 if( flag_altform2 ){
777 /* Set length to the number of bytes needed in order to display
778 ** precision characters */
779 unsigned char *z = (unsigned char*)bufpt;
780 while( precision-- > 0 && z[0] ){
781 SQLITE_SKIP_UTF8(z);
782 }
783 length = (int)(z - (unsigned char*)bufpt);
784 }else{
785 for(length=0; length<precision && bufpt[length]; length++){}
786 }
787 }else{
788 length = 0x7fffffff & (int)strlen(bufpt);
789 }
790 adjust_width_for_utf8:
791 if( flag_altform2 && width>0 ){
792 /* Adjust width to account for extra bytes in UTF-8 characters */
793 int ii = length - 1;
794 while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;
795 }
796 break;
797 case etSQLESCAPE: /* %q: Escape ' characters */
798 case etSQLESCAPE2: /* %Q: Escape ' and enclose in '...' */
799 case etSQLESCAPE3: { /* %w: Escape " characters */
800 int i, j, k, n, isnull;
801 int needQuote;
802 char ch;
803 char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
804 char *escarg;
805
806 if( bArgList ){
807 escarg = getTextArg(pArgList);
808 }else{
809 escarg = va_arg(ap,char*);
810 }
811 isnull = escarg==0;
812 if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
813 /* For %q, %Q, and %w, the precision is the number of bytes (or
814 ** characters if the ! flags is present) to use from the input.
815 ** Because of the extra quoting characters inserted, the number
816 ** of output characters may be larger than the precision.
817 */
818 k = precision;
819 for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
820 if( ch==q ) n++;
821 if( flag_altform2 && (ch&0xc0)==0xc0 ){
822 while( (escarg[i+1]&0xc0)==0x80 ){ i++; }
823 }
824 }
825 needQuote = !isnull && xtype==etSQLESCAPE2;
826 n += i + 3;
827 if( n>etBUFSIZE ){
828 bufpt = zExtra = printfTempBuf(pAccum, n);
829 if( bufpt==0 ) return;
830 }else{
831 bufpt = buf;
832 }
833 j = 0;
834 if( needQuote ) bufpt[j++] = q;
835 k = i;
836 for(i=0; i<k; i++){
837 bufpt[j++] = ch = escarg[i];
838 if( ch==q ) bufpt[j++] = ch;
839 }
840 if( needQuote ) bufpt[j++] = q;
841 bufpt[j] = 0;
842 length = j;
843 goto adjust_width_for_utf8;
844 }
845 case etTOKEN: {
846 Token *pToken;
847 if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
848 pToken = va_arg(ap, Token*);
849 assert( bArgList==0 );
850 if( pToken && pToken->n ){
851 sqlite3_str_append(pAccum, (const char*)pToken->z, pToken->n);
852 }
853 length = width = 0;
854 break;
855 }
856 case etSRCLIST: {
857 SrcList *pSrc;
858 int k;
859 struct SrcList_item *pItem;
860 if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
861 pSrc = va_arg(ap, SrcList*);
862 k = va_arg(ap, int);
863 pItem = &pSrc->a[k];
864 assert( bArgList==0 );
865 assert( k>=0 && k<pSrc->nSrc );
866 if( pItem->zDatabase ){
867 sqlite3_str_appendall(pAccum, pItem->zDatabase);
868 sqlite3_str_append(pAccum, ".", 1);
869 }
870 sqlite3_str_appendall(pAccum, pItem->zName);
871 length = width = 0;
872 break;
873 }
874 default: {
875 assert( xtype==etINVALID );
876 return;
877 }
878 }/* End switch over the format type */
879 /*
880 ** The text of the conversion is pointed to by "bufpt" and is
881 ** "length" characters long. The field width is "width". Do
882 ** the output. Both length and width are in bytes, not characters,
883 ** at this point. If the "!" flag was present on string conversions
884 ** indicating that width and precision should be expressed in characters,
885 ** then the values have been translated prior to reaching this point.
886 */
887 width -= length;
888 if( width>0 ){
889 if( !flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
890 sqlite3_str_append(pAccum, bufpt, length);
891 if( flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
892 }else{
893 sqlite3_str_append(pAccum, bufpt, length);
894 }
895
896 if( zExtra ){
897 sqlite3DbFree(pAccum->db, zExtra);
898 zExtra = 0;
899 }
900 }/* End for loop over the format string */
901 } /* End of function */
902
903 /*
904 ** Enlarge the memory allocation on a StrAccum object so that it is
905 ** able to accept at least N more bytes of text.
906 **
907 ** Return the number of bytes of text that StrAccum is able to accept
908 ** after the attempted enlargement. The value returned might be zero.
909 */
sqlite3StrAccumEnlarge(StrAccum * p,int N)910 static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
911 char *zNew;
912 assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
913 if( p->accError ){
914 testcase(p->accError==SQLITE_TOOBIG);
915 testcase(p->accError==SQLITE_NOMEM);
916 return 0;
917 }
918 if( p->mxAlloc==0 ){
919 setStrAccumError(p, SQLITE_TOOBIG);
920 return p->nAlloc - p->nChar - 1;
921 }else{
922 char *zOld = isMalloced(p) ? p->zText : 0;
923 i64 szNew = p->nChar;
924 szNew += N + 1;
925 if( szNew+p->nChar<=p->mxAlloc ){
926 /* Force exponential buffer size growth as long as it does not overflow,
927 ** to avoid having to call this routine too often */
928 szNew += p->nChar;
929 }
930 if( szNew > p->mxAlloc ){
931 sqlite3_str_reset(p);
932 setStrAccumError(p, SQLITE_TOOBIG);
933 return 0;
934 }else{
935 p->nAlloc = (int)szNew;
936 }
937 if( p->db ){
938 zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
939 }else{
940 zNew = sqlite3Realloc(zOld, p->nAlloc);
941 }
942 if( zNew ){
943 assert( p->zText!=0 || p->nChar==0 );
944 if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
945 p->zText = zNew;
946 p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
947 p->printfFlags |= SQLITE_PRINTF_MALLOCED;
948 }else{
949 sqlite3_str_reset(p);
950 setStrAccumError(p, SQLITE_NOMEM);
951 return 0;
952 }
953 }
954 return N;
955 }
956
957 /*
958 ** Append N copies of character c to the given string buffer.
959 */
sqlite3_str_appendchar(sqlite3_str * p,int N,char c)960 void sqlite3_str_appendchar(sqlite3_str *p, int N, char c){
961 testcase( p->nChar + (i64)N > 0x7fffffff );
962 if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
963 return;
964 }
965 while( (N--)>0 ) p->zText[p->nChar++] = c;
966 }
967
968 /*
969 ** The StrAccum "p" is not large enough to accept N new bytes of z[].
970 ** So enlarge if first, then do the append.
971 **
972 ** This is a helper routine to sqlite3_str_append() that does special-case
973 ** work (enlarging the buffer) using tail recursion, so that the
974 ** sqlite3_str_append() routine can use fast calling semantics.
975 */
enlargeAndAppend(StrAccum * p,const char * z,int N)976 static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
977 N = sqlite3StrAccumEnlarge(p, N);
978 if( N>0 ){
979 memcpy(&p->zText[p->nChar], z, N);
980 p->nChar += N;
981 }
982 }
983
984 /*
985 ** Append N bytes of text from z to the StrAccum object. Increase the
986 ** size of the memory allocation for StrAccum if necessary.
987 */
sqlite3_str_append(sqlite3_str * p,const char * z,int N)988 void sqlite3_str_append(sqlite3_str *p, const char *z, int N){
989 assert( z!=0 || N==0 );
990 assert( p->zText!=0 || p->nChar==0 || p->accError );
991 assert( N>=0 );
992 assert( p->accError==0 || p->nAlloc==0 || p->mxAlloc==0 );
993 if( p->nChar+N >= p->nAlloc ){
994 enlargeAndAppend(p,z,N);
995 }else if( N ){
996 assert( p->zText );
997 p->nChar += N;
998 memcpy(&p->zText[p->nChar-N], z, N);
999 }
1000 }
1001
1002 /*
1003 ** Append the complete text of zero-terminated string z[] to the p string.
1004 */
sqlite3_str_appendall(sqlite3_str * p,const char * z)1005 void sqlite3_str_appendall(sqlite3_str *p, const char *z){
1006 sqlite3_str_append(p, z, sqlite3Strlen30(z));
1007 }
1008
1009
1010 /*
1011 ** Finish off a string by making sure it is zero-terminated.
1012 ** Return a pointer to the resulting string. Return a NULL
1013 ** pointer if any kind of error was encountered.
1014 */
strAccumFinishRealloc(StrAccum * p)1015 static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
1016 char *zText;
1017 assert( p->mxAlloc>0 && !isMalloced(p) );
1018 zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
1019 if( zText ){
1020 memcpy(zText, p->zText, p->nChar+1);
1021 p->printfFlags |= SQLITE_PRINTF_MALLOCED;
1022 }else{
1023 setStrAccumError(p, SQLITE_NOMEM);
1024 }
1025 p->zText = zText;
1026 return zText;
1027 }
sqlite3StrAccumFinish(StrAccum * p)1028 char *sqlite3StrAccumFinish(StrAccum *p){
1029 if( p->zText ){
1030 p->zText[p->nChar] = 0;
1031 if( p->mxAlloc>0 && !isMalloced(p) ){
1032 return strAccumFinishRealloc(p);
1033 }
1034 }
1035 return p->zText;
1036 }
1037
1038 /*
1039 ** This singleton is an sqlite3_str object that is returned if
1040 ** sqlite3_malloc() fails to provide space for a real one. This
1041 ** sqlite3_str object accepts no new text and always returns
1042 ** an SQLITE_NOMEM error.
1043 */
1044 static sqlite3_str sqlite3OomStr = {
1045 0, 0, 0, 0, 0, SQLITE_NOMEM, 0
1046 };
1047
1048 /* Finalize a string created using sqlite3_str_new().
1049 */
sqlite3_str_finish(sqlite3_str * p)1050 char *sqlite3_str_finish(sqlite3_str *p){
1051 char *z;
1052 if( p!=0 && p!=&sqlite3OomStr ){
1053 z = sqlite3StrAccumFinish(p);
1054 sqlite3_free(p);
1055 }else{
1056 z = 0;
1057 }
1058 return z;
1059 }
1060
1061 /* Return any error code associated with p */
sqlite3_str_errcode(sqlite3_str * p)1062 int sqlite3_str_errcode(sqlite3_str *p){
1063 return p ? p->accError : SQLITE_NOMEM;
1064 }
1065
1066 /* Return the current length of p in bytes */
sqlite3_str_length(sqlite3_str * p)1067 int sqlite3_str_length(sqlite3_str *p){
1068 return p ? p->nChar : 0;
1069 }
1070
1071 /* Return the current value for p */
sqlite3_str_value(sqlite3_str * p)1072 char *sqlite3_str_value(sqlite3_str *p){
1073 if( p==0 || p->nChar==0 ) return 0;
1074 p->zText[p->nChar] = 0;
1075 return p->zText;
1076 }
1077
1078 /*
1079 ** Reset an StrAccum string. Reclaim all malloced memory.
1080 */
sqlite3_str_reset(StrAccum * p)1081 void sqlite3_str_reset(StrAccum *p){
1082 if( isMalloced(p) ){
1083 sqlite3DbFree(p->db, p->zText);
1084 p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
1085 }
1086 p->nAlloc = 0;
1087 p->nChar = 0;
1088 p->zText = 0;
1089 }
1090
1091 /*
1092 ** Initialize a string accumulator.
1093 **
1094 ** p: The accumulator to be initialized.
1095 ** db: Pointer to a database connection. May be NULL. Lookaside
1096 ** memory is used if not NULL. db->mallocFailed is set appropriately
1097 ** when not NULL.
1098 ** zBase: An initial buffer. May be NULL in which case the initial buffer
1099 ** is malloced.
1100 ** n: Size of zBase in bytes. If total space requirements never exceed
1101 ** n then no memory allocations ever occur.
1102 ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
1103 ** allocations will ever occur.
1104 */
sqlite3StrAccumInit(StrAccum * p,sqlite3 * db,char * zBase,int n,int mx)1105 void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
1106 p->zText = zBase;
1107 p->db = db;
1108 p->nAlloc = n;
1109 p->mxAlloc = mx;
1110 p->nChar = 0;
1111 p->accError = 0;
1112 p->printfFlags = 0;
1113 }
1114
1115 /* Allocate and initialize a new dynamic string object */
sqlite3_str_new(sqlite3 * db)1116 sqlite3_str *sqlite3_str_new(sqlite3 *db){
1117 sqlite3_str *p = sqlite3_malloc64(sizeof(*p));
1118 if( p ){
1119 sqlite3StrAccumInit(p, 0, 0, 0,
1120 db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
1121 }else{
1122 p = &sqlite3OomStr;
1123 }
1124 return p;
1125 }
1126
1127 /*
1128 ** Print into memory obtained from sqliteMalloc(). Use the internal
1129 ** %-conversion extensions.
1130 */
sqlite3VMPrintf(sqlite3 * db,const char * zFormat,va_list ap)1131 char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
1132 char *z;
1133 char zBase[SQLITE_PRINT_BUF_SIZE];
1134 StrAccum acc;
1135 assert( db!=0 );
1136 sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
1137 db->aLimit[SQLITE_LIMIT_LENGTH]);
1138 acc.printfFlags = SQLITE_PRINTF_INTERNAL;
1139 sqlite3_str_vappendf(&acc, zFormat, ap);
1140 z = sqlite3StrAccumFinish(&acc);
1141 if( acc.accError==SQLITE_NOMEM ){
1142 sqlite3OomFault(db);
1143 }
1144 return z;
1145 }
1146
1147 /*
1148 ** Print into memory obtained from sqliteMalloc(). Use the internal
1149 ** %-conversion extensions.
1150 */
sqlite3MPrintf(sqlite3 * db,const char * zFormat,...)1151 char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
1152 va_list ap;
1153 char *z;
1154 va_start(ap, zFormat);
1155 z = sqlite3VMPrintf(db, zFormat, ap);
1156 va_end(ap);
1157 return z;
1158 }
1159
1160 /*
1161 ** Print into memory obtained from sqlite3_malloc(). Omit the internal
1162 ** %-conversion extensions.
1163 */
sqlite3_vmprintf(const char * zFormat,va_list ap)1164 char *sqlite3_vmprintf(const char *zFormat, va_list ap){
1165 char *z;
1166 char zBase[SQLITE_PRINT_BUF_SIZE];
1167 StrAccum acc;
1168
1169 #ifdef SQLITE_ENABLE_API_ARMOR
1170 if( zFormat==0 ){
1171 (void)SQLITE_MISUSE_BKPT;
1172 return 0;
1173 }
1174 #endif
1175 #ifndef SQLITE_OMIT_AUTOINIT
1176 if( sqlite3_initialize() ) return 0;
1177 #endif
1178 sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
1179 sqlite3_str_vappendf(&acc, zFormat, ap);
1180 z = sqlite3StrAccumFinish(&acc);
1181 return z;
1182 }
1183
1184 /*
1185 ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
1186 ** %-conversion extensions.
1187 */
sqlite3_mprintf(const char * zFormat,...)1188 char *sqlite3_mprintf(const char *zFormat, ...){
1189 va_list ap;
1190 char *z;
1191 #ifndef SQLITE_OMIT_AUTOINIT
1192 if( sqlite3_initialize() ) return 0;
1193 #endif
1194 va_start(ap, zFormat);
1195 z = sqlite3_vmprintf(zFormat, ap);
1196 va_end(ap);
1197 return z;
1198 }
1199
1200 /*
1201 ** sqlite3_snprintf() works like snprintf() except that it ignores the
1202 ** current locale settings. This is important for SQLite because we
1203 ** are not able to use a "," as the decimal point in place of "." as
1204 ** specified by some locales.
1205 **
1206 ** Oops: The first two arguments of sqlite3_snprintf() are backwards
1207 ** from the snprintf() standard. Unfortunately, it is too late to change
1208 ** this without breaking compatibility, so we just have to live with the
1209 ** mistake.
1210 **
1211 ** sqlite3_vsnprintf() is the varargs version.
1212 */
sqlite3_vsnprintf(int n,char * zBuf,const char * zFormat,va_list ap)1213 char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
1214 StrAccum acc;
1215 if( n<=0 ) return zBuf;
1216 #ifdef SQLITE_ENABLE_API_ARMOR
1217 if( zBuf==0 || zFormat==0 ) {
1218 (void)SQLITE_MISUSE_BKPT;
1219 if( zBuf ) zBuf[0] = 0;
1220 return zBuf;
1221 }
1222 #endif
1223 sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
1224 sqlite3_str_vappendf(&acc, zFormat, ap);
1225 zBuf[acc.nChar] = 0;
1226 return zBuf;
1227 }
sqlite3_snprintf(int n,char * zBuf,const char * zFormat,...)1228 char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
1229 char *z;
1230 va_list ap;
1231 va_start(ap,zFormat);
1232 z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
1233 va_end(ap);
1234 return z;
1235 }
1236
1237 /*
1238 ** This is the routine that actually formats the sqlite3_log() message.
1239 ** We house it in a separate routine from sqlite3_log() to avoid using
1240 ** stack space on small-stack systems when logging is disabled.
1241 **
1242 ** sqlite3_log() must render into a static buffer. It cannot dynamically
1243 ** allocate memory because it might be called while the memory allocator
1244 ** mutex is held.
1245 **
1246 ** sqlite3_str_vappendf() might ask for *temporary* memory allocations for
1247 ** certain format characters (%q) or for very large precisions or widths.
1248 ** Care must be taken that any sqlite3_log() calls that occur while the
1249 ** memory mutex is held do not use these mechanisms.
1250 */
renderLogMsg(int iErrCode,const char * zFormat,va_list ap)1251 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
1252 StrAccum acc; /* String accumulator */
1253 char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
1254
1255 sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
1256 sqlite3_str_vappendf(&acc, zFormat, ap);
1257 sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
1258 sqlite3StrAccumFinish(&acc));
1259 }
1260
1261 /*
1262 ** Format and write a message to the log if logging is enabled.
1263 */
sqlite3_log(int iErrCode,const char * zFormat,...)1264 void sqlite3_log(int iErrCode, const char *zFormat, ...){
1265 va_list ap; /* Vararg list */
1266 if( sqlite3GlobalConfig.xLog ){
1267 va_start(ap, zFormat);
1268 renderLogMsg(iErrCode, zFormat, ap);
1269 va_end(ap);
1270 }
1271 }
1272
1273 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
1274 /*
1275 ** A version of printf() that understands %lld. Used for debugging.
1276 ** The printf() built into some versions of windows does not understand %lld
1277 ** and segfaults if you give it a long long int.
1278 */
sqlite3DebugPrintf(const char * zFormat,...)1279 void sqlite3DebugPrintf(const char *zFormat, ...){
1280 va_list ap;
1281 StrAccum acc;
1282 char zBuf[SQLITE_PRINT_BUF_SIZE*10];
1283 sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
1284 va_start(ap,zFormat);
1285 sqlite3_str_vappendf(&acc, zFormat, ap);
1286 va_end(ap);
1287 sqlite3StrAccumFinish(&acc);
1288 #ifdef SQLITE_OS_TRACE_PROC
1289 {
1290 extern void SQLITE_OS_TRACE_PROC(const char *zBuf, int nBuf);
1291 SQLITE_OS_TRACE_PROC(zBuf, sizeof(zBuf));
1292 }
1293 #else
1294 fprintf(stdout,"%s", zBuf);
1295 fflush(stdout);
1296 #endif
1297 }
1298 #endif
1299
1300
1301 /*
1302 ** variable-argument wrapper around sqlite3_str_vappendf(). The bFlags argument
1303 ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
1304 */
sqlite3_str_appendf(StrAccum * p,const char * zFormat,...)1305 void sqlite3_str_appendf(StrAccum *p, const char *zFormat, ...){
1306 va_list ap;
1307 va_start(ap,zFormat);
1308 sqlite3_str_vappendf(p, zFormat, ap);
1309 va_end(ap);
1310 }
1311