xref: /sqlite-3.40.0/src/printf.c (revision 21b7d2a9)
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   assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
142   p->accError = eError;
143   p->nAlloc = 0;
144 }
145 
146 /*
147 ** Extra argument values from a PrintfArguments object
148 */
149 static sqlite3_int64 getIntArg(PrintfArguments *p){
150   if( p->nArg<=p->nUsed ) return 0;
151   return sqlite3_value_int64(p->apArg[p->nUsed++]);
152 }
153 static double getDoubleArg(PrintfArguments *p){
154   if( p->nArg<=p->nUsed ) return 0.0;
155   return sqlite3_value_double(p->apArg[p->nUsed++]);
156 }
157 static char *getTextArg(PrintfArguments *p){
158   if( p->nArg<=p->nUsed ) return 0;
159   return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
160 }
161 
162 
163 /*
164 ** On machines with a small stack size, you can redefine the
165 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
166 */
167 #ifndef SQLITE_PRINT_BUF_SIZE
168 # define SQLITE_PRINT_BUF_SIZE 70
169 #endif
170 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
171 
172 /*
173 ** Render a string given by "fmt" into the StrAccum object.
174 */
175 void sqlite3VXPrintf(
176   StrAccum *pAccum,          /* Accumulate results here */
177   u32 bFlags,                /* SQLITE_PRINTF_* flags */
178   const char *fmt,           /* Format string */
179   va_list ap                 /* arguments */
180 ){
181   int c;                     /* Next character in the format string */
182   char *bufpt;               /* Pointer to the conversion buffer */
183   int precision;             /* Precision of the current field */
184   int length;                /* Length of the field */
185   int idx;                   /* A general purpose loop counter */
186   int width;                 /* Width of the current field */
187   etByte flag_leftjustify;   /* True if "-" flag is present */
188   etByte flag_plussign;      /* True if "+" flag is present */
189   etByte flag_blanksign;     /* True if " " flag is present */
190   etByte flag_alternateform; /* True if "#" flag is present */
191   etByte flag_altform2;      /* True if "!" flag is present */
192   etByte flag_zeropad;       /* True if field width constant starts with zero */
193   etByte flag_long;          /* True if "l" flag is present */
194   etByte flag_longlong;      /* True if the "ll" flag is present */
195   etByte done;               /* Loop termination flag */
196   etByte xtype = 0;          /* Conversion paradigm */
197   u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */
198   u8 useIntern;              /* Ok to use internal conversions (ex: %T) */
199   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
200   sqlite_uint64 longvalue;   /* Value for integer types */
201   LONGDOUBLE_TYPE realvalue; /* Value for real types */
202   const et_info *infop;      /* Pointer to the appropriate info structure */
203   char *zOut;                /* Rendering buffer */
204   int nOut;                  /* Size of the rendering buffer */
205   char *zExtra = 0;          /* Malloced memory used by some conversion */
206 #ifndef SQLITE_OMIT_FLOATING_POINT
207   int  exp, e2;              /* exponent of real numbers */
208   int nsd;                   /* Number of significant digits returned */
209   double rounder;            /* Used for rounding floating point values */
210   etByte flag_dp;            /* True if decimal point should be shown */
211   etByte flag_rtz;           /* True if trailing zeros should be removed */
212 #endif
213   PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
214   char buf[etBUFSIZE];       /* Conversion buffer */
215 
216   bufpt = 0;
217   if( bFlags ){
218     if( (bArgList = (bFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
219       pArgList = va_arg(ap, PrintfArguments*);
220     }
221     useIntern = bFlags & SQLITE_PRINTF_INTERNAL;
222   }else{
223     bArgList = useIntern = 0;
224   }
225   for(; (c=(*fmt))!=0; ++fmt){
226     if( c!='%' ){
227       bufpt = (char *)fmt;
228 #if HAVE_STRCHRNUL
229       fmt = strchrnul(fmt, '%');
230 #else
231       do{ fmt++; }while( *fmt && *fmt != '%' );
232 #endif
233       sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
234       if( *fmt==0 ) break;
235     }
236     if( (c=(*++fmt))==0 ){
237       sqlite3StrAccumAppend(pAccum, "%", 1);
238       break;
239     }
240     /* Find out what flags are present */
241     flag_leftjustify = flag_plussign = flag_blanksign =
242      flag_alternateform = flag_altform2 = flag_zeropad = 0;
243     done = 0;
244     do{
245       switch( c ){
246         case '-':   flag_leftjustify = 1;     break;
247         case '+':   flag_plussign = 1;        break;
248         case ' ':   flag_blanksign = 1;       break;
249         case '#':   flag_alternateform = 1;   break;
250         case '!':   flag_altform2 = 1;        break;
251         case '0':   flag_zeropad = 1;         break;
252         default:    done = 1;                 break;
253       }
254     }while( !done && (c=(*++fmt))!=0 );
255     /* Get the field width */
256     if( c=='*' ){
257       if( bArgList ){
258         width = (int)getIntArg(pArgList);
259       }else{
260         width = va_arg(ap,int);
261       }
262       if( width<0 ){
263         flag_leftjustify = 1;
264         width = width >= -2147483647 ? -width : 0;
265       }
266       c = *++fmt;
267     }else{
268       unsigned wx = 0;
269       while( c>='0' && c<='9' ){
270         wx = wx*10 + c - '0';
271         c = *++fmt;
272       }
273       testcase( wx>0x7fffffff );
274       width = wx & 0x7fffffff;
275     }
276 
277     /* Get the precision */
278     if( c=='.' ){
279       c = *++fmt;
280       if( c=='*' ){
281         if( bArgList ){
282           precision = (int)getIntArg(pArgList);
283         }else{
284           precision = va_arg(ap,int);
285         }
286         c = *++fmt;
287         if( precision<0 ){
288           precision = precision >= -2147483647 ? -precision : -1;
289         }
290       }else{
291         unsigned px = 0;
292         while( c>='0' && c<='9' ){
293           px = px*10 + c - '0';
294           c = *++fmt;
295         }
296         testcase( px>0x7fffffff );
297         precision = px & 0x7fffffff;
298       }
299     }else{
300       precision = -1;
301     }
302     /* Get the conversion type modifier */
303     if( c=='l' ){
304       flag_long = 1;
305       c = *++fmt;
306       if( c=='l' ){
307         flag_longlong = 1;
308         c = *++fmt;
309       }else{
310         flag_longlong = 0;
311       }
312     }else{
313       flag_long = flag_longlong = 0;
314     }
315     /* Fetch the info entry for the field */
316     infop = &fmtinfo[0];
317     xtype = etINVALID;
318     for(idx=0; idx<ArraySize(fmtinfo); idx++){
319       if( c==fmtinfo[idx].fmttype ){
320         infop = &fmtinfo[idx];
321         if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
322           xtype = infop->type;
323         }else{
324           return;
325         }
326         break;
327       }
328     }
329 
330     /*
331     ** At this point, variables are initialized as follows:
332     **
333     **   flag_alternateform          TRUE if a '#' is present.
334     **   flag_altform2               TRUE if a '!' is present.
335     **   flag_plussign               TRUE if a '+' is present.
336     **   flag_leftjustify            TRUE if a '-' is present or if the
337     **                               field width was negative.
338     **   flag_zeropad                TRUE if the width began with 0.
339     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
340     **                               the conversion character.
341     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
342     **                               the conversion character.
343     **   flag_blanksign              TRUE if a ' ' is present.
344     **   width                       The specified field width.  This is
345     **                               always non-negative.  Zero is the default.
346     **   precision                   The specified precision.  The default
347     **                               is -1.
348     **   xtype                       The class of the conversion.
349     **   infop                       Pointer to the appropriate info struct.
350     */
351     switch( xtype ){
352       case etPOINTER:
353         flag_longlong = sizeof(char*)==sizeof(i64);
354         flag_long = sizeof(char*)==sizeof(long int);
355         /* Fall through into the next case */
356       case etORDINAL:
357       case etRADIX:
358         if( infop->flags & FLAG_SIGNED ){
359           i64 v;
360           if( bArgList ){
361             v = getIntArg(pArgList);
362           }else if( flag_longlong ){
363             v = va_arg(ap,i64);
364           }else if( flag_long ){
365             v = va_arg(ap,long int);
366           }else{
367             v = va_arg(ap,int);
368           }
369           if( v<0 ){
370             if( v==SMALLEST_INT64 ){
371               longvalue = ((u64)1)<<63;
372             }else{
373               longvalue = -v;
374             }
375             prefix = '-';
376           }else{
377             longvalue = v;
378             if( flag_plussign )        prefix = '+';
379             else if( flag_blanksign )  prefix = ' ';
380             else                       prefix = 0;
381           }
382         }else{
383           if( bArgList ){
384             longvalue = (u64)getIntArg(pArgList);
385           }else if( flag_longlong ){
386             longvalue = va_arg(ap,u64);
387           }else if( flag_long ){
388             longvalue = va_arg(ap,unsigned long int);
389           }else{
390             longvalue = va_arg(ap,unsigned int);
391           }
392           prefix = 0;
393         }
394         if( longvalue==0 ) flag_alternateform = 0;
395         if( flag_zeropad && precision<width-(prefix!=0) ){
396           precision = width-(prefix!=0);
397         }
398         if( precision<etBUFSIZE-10 ){
399           nOut = etBUFSIZE;
400           zOut = buf;
401         }else{
402           nOut = precision + 10;
403           zOut = zExtra = sqlite3Malloc( nOut );
404           if( zOut==0 ){
405             setStrAccumError(pAccum, STRACCUM_NOMEM);
406             return;
407           }
408         }
409         bufpt = &zOut[nOut-1];
410         if( xtype==etORDINAL ){
411           static const char zOrd[] = "thstndrd";
412           int x = (int)(longvalue % 10);
413           if( x>=4 || (longvalue/10)%10==1 ){
414             x = 0;
415           }
416           *(--bufpt) = zOrd[x*2+1];
417           *(--bufpt) = zOrd[x*2];
418         }
419         {
420           const char *cset = &aDigits[infop->charset];
421           u8 base = infop->base;
422           do{                                           /* Convert to ascii */
423             *(--bufpt) = cset[longvalue%base];
424             longvalue = longvalue/base;
425           }while( longvalue>0 );
426         }
427         length = (int)(&zOut[nOut-1]-bufpt);
428         for(idx=precision-length; idx>0; idx--){
429           *(--bufpt) = '0';                             /* Zero pad */
430         }
431         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
432         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
433           const char *pre;
434           char x;
435           pre = &aPrefix[infop->prefix];
436           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
437         }
438         length = (int)(&zOut[nOut-1]-bufpt);
439         break;
440       case etFLOAT:
441       case etEXP:
442       case etGENERIC:
443         if( bArgList ){
444           realvalue = getDoubleArg(pArgList);
445         }else{
446           realvalue = va_arg(ap,double);
447         }
448 #ifdef SQLITE_OMIT_FLOATING_POINT
449         length = 0;
450 #else
451         if( precision<0 ) precision = 6;         /* Set default precision */
452         if( realvalue<0.0 ){
453           realvalue = -realvalue;
454           prefix = '-';
455         }else{
456           if( flag_plussign )          prefix = '+';
457           else if( flag_blanksign )    prefix = ' ';
458           else                         prefix = 0;
459         }
460         if( xtype==etGENERIC && precision>0 ) precision--;
461         testcase( precision>0xfff );
462         for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
463         if( xtype==etFLOAT ) realvalue += rounder;
464         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
465         exp = 0;
466         if( sqlite3IsNaN((double)realvalue) ){
467           bufpt = "NaN";
468           length = 3;
469           break;
470         }
471         if( realvalue>0.0 ){
472           LONGDOUBLE_TYPE scale = 1.0;
473           while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
474           while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
475           while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
476           while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
477           realvalue /= scale;
478           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
479           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
480           if( exp>350 ){
481             if( prefix=='-' ){
482               bufpt = "-Inf";
483             }else if( prefix=='+' ){
484               bufpt = "+Inf";
485             }else{
486               bufpt = "Inf";
487             }
488             length = sqlite3Strlen30(bufpt);
489             break;
490           }
491         }
492         bufpt = buf;
493         /*
494         ** If the field type is etGENERIC, then convert to either etEXP
495         ** or etFLOAT, as appropriate.
496         */
497         if( xtype!=etFLOAT ){
498           realvalue += rounder;
499           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
500         }
501         if( xtype==etGENERIC ){
502           flag_rtz = !flag_alternateform;
503           if( exp<-4 || exp>precision ){
504             xtype = etEXP;
505           }else{
506             precision = precision - exp;
507             xtype = etFLOAT;
508           }
509         }else{
510           flag_rtz = flag_altform2;
511         }
512         if( xtype==etEXP ){
513           e2 = 0;
514         }else{
515           e2 = exp;
516         }
517         if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
518           bufpt = zExtra
519               = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
520           if( bufpt==0 ){
521             setStrAccumError(pAccum, STRACCUM_NOMEM);
522             return;
523           }
524         }
525         zOut = bufpt;
526         nsd = 16 + flag_altform2*10;
527         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
528         /* The sign in front of the number */
529         if( prefix ){
530           *(bufpt++) = prefix;
531         }
532         /* Digits prior to the decimal point */
533         if( e2<0 ){
534           *(bufpt++) = '0';
535         }else{
536           for(; e2>=0; e2--){
537             *(bufpt++) = et_getdigit(&realvalue,&nsd);
538           }
539         }
540         /* The decimal point */
541         if( flag_dp ){
542           *(bufpt++) = '.';
543         }
544         /* "0" digits after the decimal point but before the first
545         ** significant digit of the number */
546         for(e2++; e2<0; precision--, e2++){
547           assert( precision>0 );
548           *(bufpt++) = '0';
549         }
550         /* Significant digits after the decimal point */
551         while( (precision--)>0 ){
552           *(bufpt++) = et_getdigit(&realvalue,&nsd);
553         }
554         /* Remove trailing zeros and the "." if no digits follow the "." */
555         if( flag_rtz && flag_dp ){
556           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
557           assert( bufpt>zOut );
558           if( bufpt[-1]=='.' ){
559             if( flag_altform2 ){
560               *(bufpt++) = '0';
561             }else{
562               *(--bufpt) = 0;
563             }
564           }
565         }
566         /* Add the "eNNN" suffix */
567         if( xtype==etEXP ){
568           *(bufpt++) = aDigits[infop->charset];
569           if( exp<0 ){
570             *(bufpt++) = '-'; exp = -exp;
571           }else{
572             *(bufpt++) = '+';
573           }
574           if( exp>=100 ){
575             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
576             exp %= 100;
577           }
578           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
579           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
580         }
581         *bufpt = 0;
582 
583         /* The converted number is in buf[] and zero terminated. Output it.
584         ** Note that the number is in the usual order, not reversed as with
585         ** integer conversions. */
586         length = (int)(bufpt-zOut);
587         bufpt = zOut;
588 
589         /* Special case:  Add leading zeros if the flag_zeropad flag is
590         ** set and we are not left justified */
591         if( flag_zeropad && !flag_leftjustify && length < width){
592           int i;
593           int nPad = width - length;
594           for(i=width; i>=nPad; i--){
595             bufpt[i] = bufpt[i-nPad];
596           }
597           i = prefix!=0;
598           while( nPad-- ) bufpt[i++] = '0';
599           length = width;
600         }
601 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
602         break;
603       case etSIZE:
604         if( !bArgList ){
605           *(va_arg(ap,int*)) = pAccum->nChar;
606         }
607         length = width = 0;
608         break;
609       case etPERCENT:
610         buf[0] = '%';
611         bufpt = buf;
612         length = 1;
613         break;
614       case etCHARX:
615         if( bArgList ){
616           bufpt = getTextArg(pArgList);
617           c = bufpt ? bufpt[0] : 0;
618         }else{
619           c = va_arg(ap,int);
620         }
621         if( precision>1 ){
622           width -= precision-1;
623           if( width>1 && !flag_leftjustify ){
624             sqlite3AppendChar(pAccum, width-1, ' ');
625             width = 0;
626           }
627           sqlite3AppendChar(pAccum, precision-1, c);
628         }
629         length = 1;
630         buf[0] = c;
631         bufpt = buf;
632         break;
633       case etSTRING:
634       case etDYNSTRING:
635         if( bArgList ){
636           bufpt = getTextArg(pArgList);
637         }else{
638           bufpt = va_arg(ap,char*);
639         }
640         if( bufpt==0 ){
641           bufpt = "";
642         }else if( xtype==etDYNSTRING && !bArgList ){
643           zExtra = bufpt;
644         }
645         if( precision>=0 ){
646           for(length=0; length<precision && bufpt[length]; length++){}
647         }else{
648           length = sqlite3Strlen30(bufpt);
649         }
650         break;
651       case etSQLESCAPE:
652       case etSQLESCAPE2:
653       case etSQLESCAPE3: {
654         int i, j, k, n, isnull;
655         int needQuote;
656         char ch;
657         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
658         char *escarg;
659 
660         if( bArgList ){
661           escarg = getTextArg(pArgList);
662         }else{
663           escarg = va_arg(ap,char*);
664         }
665         isnull = escarg==0;
666         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
667         k = precision;
668         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
669           if( ch==q )  n++;
670         }
671         needQuote = !isnull && xtype==etSQLESCAPE2;
672         n += i + 1 + needQuote*2;
673         if( n>etBUFSIZE ){
674           bufpt = zExtra = sqlite3Malloc( n );
675           if( bufpt==0 ){
676             setStrAccumError(pAccum, STRACCUM_NOMEM);
677             return;
678           }
679         }else{
680           bufpt = buf;
681         }
682         j = 0;
683         if( needQuote ) bufpt[j++] = q;
684         k = i;
685         for(i=0; i<k; i++){
686           bufpt[j++] = ch = escarg[i];
687           if( ch==q ) bufpt[j++] = ch;
688         }
689         if( needQuote ) bufpt[j++] = q;
690         bufpt[j] = 0;
691         length = j;
692         /* The precision in %q and %Q means how many input characters to
693         ** consume, not the length of the output...
694         ** if( precision>=0 && precision<length ) length = precision; */
695         break;
696       }
697       case etTOKEN: {
698         Token *pToken = va_arg(ap, Token*);
699         assert( bArgList==0 );
700         if( pToken && pToken->n ){
701           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
702         }
703         length = width = 0;
704         break;
705       }
706       case etSRCLIST: {
707         SrcList *pSrc = va_arg(ap, SrcList*);
708         int k = va_arg(ap, int);
709         struct SrcList_item *pItem = &pSrc->a[k];
710         assert( bArgList==0 );
711         assert( k>=0 && k<pSrc->nSrc );
712         if( pItem->zDatabase ){
713           sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
714           sqlite3StrAccumAppend(pAccum, ".", 1);
715         }
716         sqlite3StrAccumAppendAll(pAccum, pItem->zName);
717         length = width = 0;
718         break;
719       }
720       default: {
721         assert( xtype==etINVALID );
722         return;
723       }
724     }/* End switch over the format type */
725     /*
726     ** The text of the conversion is pointed to by "bufpt" and is
727     ** "length" characters long.  The field width is "width".  Do
728     ** the output.
729     */
730     width -= length;
731     if( width>0 && !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
732     sqlite3StrAccumAppend(pAccum, bufpt, length);
733     if( width>0 && flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
734 
735     if( zExtra ){
736       sqlite3_free(zExtra);
737       zExtra = 0;
738     }
739   }/* End for loop over the format string */
740 } /* End of function */
741 
742 /*
743 ** Enlarge the memory allocation on a StrAccum object so that it is
744 ** able to accept at least N more bytes of text.
745 **
746 ** Return the number of bytes of text that StrAccum is able to accept
747 ** after the attempted enlargement.  The value returned might be zero.
748 */
749 static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
750   char *zNew;
751   assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
752   if( p->accError ){
753     testcase(p->accError==STRACCUM_TOOBIG);
754     testcase(p->accError==STRACCUM_NOMEM);
755     return 0;
756   }
757   if( p->mxAlloc==0 ){
758     N = p->nAlloc - p->nChar - 1;
759     setStrAccumError(p, STRACCUM_TOOBIG);
760     return N;
761   }else{
762     char *zOld = (p->zText==p->zBase ? 0 : p->zText);
763     i64 szNew = p->nChar;
764     szNew += N + 1;
765     if( szNew+p->nChar<=p->mxAlloc ){
766       /* Force exponential buffer size growth as long as it does not overflow,
767       ** to avoid having to call this routine too often */
768       szNew += p->nChar;
769     }
770     if( szNew > p->mxAlloc ){
771       sqlite3StrAccumReset(p);
772       setStrAccumError(p, STRACCUM_TOOBIG);
773       return 0;
774     }else{
775       p->nAlloc = (int)szNew;
776     }
777     if( p->db ){
778       zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
779     }else{
780       zNew = sqlite3_realloc64(zOld, p->nAlloc);
781     }
782     if( zNew ){
783       assert( p->zText!=0 || p->nChar==0 );
784       if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
785       p->zText = zNew;
786       p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
787     }else{
788       sqlite3StrAccumReset(p);
789       setStrAccumError(p, STRACCUM_NOMEM);
790       return 0;
791     }
792   }
793   return N;
794 }
795 
796 /*
797 ** Append N copies of character c to the given string buffer.
798 */
799 void sqlite3AppendChar(StrAccum *p, int N, char c){
800   testcase( p->nChar + (i64)N > 0x7fffffff );
801   if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
802     return;
803   }
804   while( (N--)>0 ) p->zText[p->nChar++] = c;
805 }
806 
807 /*
808 ** The StrAccum "p" is not large enough to accept N new bytes of z[].
809 ** So enlarge if first, then do the append.
810 **
811 ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
812 ** work (enlarging the buffer) using tail recursion, so that the
813 ** sqlite3StrAccumAppend() routine can use fast calling semantics.
814 */
815 static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
816   N = sqlite3StrAccumEnlarge(p, N);
817   if( N>0 ){
818     memcpy(&p->zText[p->nChar], z, N);
819     p->nChar += N;
820   }
821 }
822 
823 /*
824 ** Append N bytes of text from z to the StrAccum object.  Increase the
825 ** size of the memory allocation for StrAccum if necessary.
826 */
827 void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
828   assert( z!=0 || N==0 );
829   assert( p->zText!=0 || p->nChar==0 || p->accError );
830   assert( N>=0 );
831   assert( p->accError==0 || p->nAlloc==0 );
832   if( p->nChar+N >= p->nAlloc ){
833     enlargeAndAppend(p,z,N);
834   }else{
835     assert( p->zText );
836     p->nChar += N;
837     memcpy(&p->zText[p->nChar-N], z, N);
838   }
839 }
840 
841 /*
842 ** Append the complete text of zero-terminated string z[] to the p string.
843 */
844 void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
845   sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
846 }
847 
848 
849 /*
850 ** Finish off a string by making sure it is zero-terminated.
851 ** Return a pointer to the resulting string.  Return a NULL
852 ** pointer if any kind of error was encountered.
853 */
854 char *sqlite3StrAccumFinish(StrAccum *p){
855   if( p->zText ){
856     p->zText[p->nChar] = 0;
857     if( p->mxAlloc>0 && p->zText==p->zBase ){
858       p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
859       if( p->zText ){
860         memcpy(p->zText, p->zBase, p->nChar+1);
861       }else{
862         setStrAccumError(p, STRACCUM_NOMEM);
863       }
864     }
865   }
866   return p->zText;
867 }
868 
869 /*
870 ** Reset an StrAccum string.  Reclaim all malloced memory.
871 */
872 void sqlite3StrAccumReset(StrAccum *p){
873   if( p->zText!=p->zBase ){
874     sqlite3DbFree(p->db, p->zText);
875   }
876   p->zText = 0;
877 }
878 
879 /*
880 ** Initialize a string accumulator.
881 **
882 ** p:     The accumulator to be initialized.
883 ** db:    Pointer to a database connection.  May be NULL.  Lookaside
884 **        memory is used if not NULL. db->mallocFailed is set appropriately
885 **        when not NULL.
886 ** zBase: An initial buffer.  May be NULL in which case the initial buffer
887 **        is malloced.
888 ** n:     Size of zBase in bytes.  If total space requirements never exceed
889 **        n then no memory allocations ever occur.
890 ** mx:    Maximum number of bytes to accumulate.  If mx==0 then no memory
891 **        allocations will ever occur.
892 */
893 void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
894   p->zText = p->zBase = zBase;
895   p->db = db;
896   p->nChar = 0;
897   p->nAlloc = n;
898   p->mxAlloc = mx;
899   p->accError = 0;
900 }
901 
902 /*
903 ** Print into memory obtained from sqliteMalloc().  Use the internal
904 ** %-conversion extensions.
905 */
906 char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
907   char *z;
908   char zBase[SQLITE_PRINT_BUF_SIZE];
909   StrAccum acc;
910   assert( db!=0 );
911   sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
912                       db->aLimit[SQLITE_LIMIT_LENGTH]);
913   sqlite3VXPrintf(&acc, SQLITE_PRINTF_INTERNAL, zFormat, ap);
914   z = sqlite3StrAccumFinish(&acc);
915   if( acc.accError==STRACCUM_NOMEM ){
916     db->mallocFailed = 1;
917   }
918   return z;
919 }
920 
921 /*
922 ** Print into memory obtained from sqliteMalloc().  Use the internal
923 ** %-conversion extensions.
924 */
925 char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
926   va_list ap;
927   char *z;
928   va_start(ap, zFormat);
929   z = sqlite3VMPrintf(db, zFormat, ap);
930   va_end(ap);
931   return z;
932 }
933 
934 /*
935 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
936 ** the string and before returning.  This routine is intended to be used
937 ** to modify an existing string.  For example:
938 **
939 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
940 **
941 */
942 char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
943   va_list ap;
944   char *z;
945   va_start(ap, zFormat);
946   z = sqlite3VMPrintf(db, zFormat, ap);
947   va_end(ap);
948   sqlite3DbFree(db, zStr);
949   return z;
950 }
951 
952 /*
953 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
954 ** %-conversion extensions.
955 */
956 char *sqlite3_vmprintf(const char *zFormat, va_list ap){
957   char *z;
958   char zBase[SQLITE_PRINT_BUF_SIZE];
959   StrAccum acc;
960 
961 #ifdef SQLITE_ENABLE_API_ARMOR
962   if( zFormat==0 ){
963     (void)SQLITE_MISUSE_BKPT;
964     return 0;
965   }
966 #endif
967 #ifndef SQLITE_OMIT_AUTOINIT
968   if( sqlite3_initialize() ) return 0;
969 #endif
970   sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
971   sqlite3VXPrintf(&acc, 0, zFormat, ap);
972   z = sqlite3StrAccumFinish(&acc);
973   return z;
974 }
975 
976 /*
977 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
978 ** %-conversion extensions.
979 */
980 char *sqlite3_mprintf(const char *zFormat, ...){
981   va_list ap;
982   char *z;
983 #ifndef SQLITE_OMIT_AUTOINIT
984   if( sqlite3_initialize() ) return 0;
985 #endif
986   va_start(ap, zFormat);
987   z = sqlite3_vmprintf(zFormat, ap);
988   va_end(ap);
989   return z;
990 }
991 
992 /*
993 ** sqlite3_snprintf() works like snprintf() except that it ignores the
994 ** current locale settings.  This is important for SQLite because we
995 ** are not able to use a "," as the decimal point in place of "." as
996 ** specified by some locales.
997 **
998 ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
999 ** from the snprintf() standard.  Unfortunately, it is too late to change
1000 ** this without breaking compatibility, so we just have to live with the
1001 ** mistake.
1002 **
1003 ** sqlite3_vsnprintf() is the varargs version.
1004 */
1005 char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
1006   StrAccum acc;
1007   if( n<=0 ) return zBuf;
1008 #ifdef SQLITE_ENABLE_API_ARMOR
1009   if( zBuf==0 || zFormat==0 ) {
1010     (void)SQLITE_MISUSE_BKPT;
1011     if( zBuf ) zBuf[0] = 0;
1012     return zBuf;
1013   }
1014 #endif
1015   sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
1016   sqlite3VXPrintf(&acc, 0, zFormat, ap);
1017   return sqlite3StrAccumFinish(&acc);
1018 }
1019 char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
1020   char *z;
1021   va_list ap;
1022   va_start(ap,zFormat);
1023   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
1024   va_end(ap);
1025   return z;
1026 }
1027 
1028 /*
1029 ** This is the routine that actually formats the sqlite3_log() message.
1030 ** We house it in a separate routine from sqlite3_log() to avoid using
1031 ** stack space on small-stack systems when logging is disabled.
1032 **
1033 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
1034 ** allocate memory because it might be called while the memory allocator
1035 ** mutex is held.
1036 */
1037 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
1038   StrAccum acc;                          /* String accumulator */
1039   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
1040 
1041   sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
1042   sqlite3VXPrintf(&acc, 0, zFormat, ap);
1043   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
1044                            sqlite3StrAccumFinish(&acc));
1045 }
1046 
1047 /*
1048 ** Format and write a message to the log if logging is enabled.
1049 */
1050 void sqlite3_log(int iErrCode, const char *zFormat, ...){
1051   va_list ap;                             /* Vararg list */
1052   if( sqlite3GlobalConfig.xLog ){
1053     va_start(ap, zFormat);
1054     renderLogMsg(iErrCode, zFormat, ap);
1055     va_end(ap);
1056   }
1057 }
1058 
1059 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
1060 /*
1061 ** A version of printf() that understands %lld.  Used for debugging.
1062 ** The printf() built into some versions of windows does not understand %lld
1063 ** and segfaults if you give it a long long int.
1064 */
1065 void sqlite3DebugPrintf(const char *zFormat, ...){
1066   va_list ap;
1067   StrAccum acc;
1068   char zBuf[500];
1069   sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
1070   va_start(ap,zFormat);
1071   sqlite3VXPrintf(&acc, 0, zFormat, ap);
1072   va_end(ap);
1073   sqlite3StrAccumFinish(&acc);
1074   fprintf(stdout,"%s", zBuf);
1075   fflush(stdout);
1076 }
1077 #endif
1078 
1079 #ifdef SQLITE_DEBUG
1080 /*************************************************************************
1081 ** Routines for implementing the "TreeView" display of hierarchical
1082 ** data structures for debugging.
1083 **
1084 ** The main entry points (coded elsewhere) are:
1085 **     sqlite3TreeViewExpr(0, pExpr, 0);
1086 **     sqlite3TreeViewExprList(0, pList, 0, 0);
1087 **     sqlite3TreeViewSelect(0, pSelect, 0);
1088 ** Insert calls to those routines while debugging in order to display
1089 ** a diagram of Expr, ExprList, and Select objects.
1090 **
1091 */
1092 /* Add a new subitem to the tree.  The moreToFollow flag indicates that this
1093 ** is not the last item in the tree. */
1094 TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
1095   if( p==0 ){
1096     p = sqlite3_malloc64( sizeof(*p) );
1097     if( p==0 ) return 0;
1098     memset(p, 0, sizeof(*p));
1099   }else{
1100     p->iLevel++;
1101   }
1102   assert( moreToFollow==0 || moreToFollow==1 );
1103   if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
1104   return p;
1105 }
1106 /* Finished with one layer of the tree */
1107 void sqlite3TreeViewPop(TreeView *p){
1108   if( p==0 ) return;
1109   p->iLevel--;
1110   if( p->iLevel<0 ) sqlite3_free(p);
1111 }
1112 /* Generate a single line of output for the tree, with a prefix that contains
1113 ** all the appropriate tree lines */
1114 void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
1115   va_list ap;
1116   int i;
1117   StrAccum acc;
1118   char zBuf[500];
1119   sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
1120   if( p ){
1121     for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
1122       sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|   " : "    ", 4);
1123     }
1124     sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
1125   }
1126   va_start(ap, zFormat);
1127   sqlite3VXPrintf(&acc, 0, zFormat, ap);
1128   va_end(ap);
1129   if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
1130   sqlite3StrAccumFinish(&acc);
1131   fprintf(stdout,"%s", zBuf);
1132   fflush(stdout);
1133 }
1134 /* Shorthand for starting a new tree item that consists of a single label */
1135 void sqlite3TreeViewItem(TreeView *p, const char *zLabel, u8 moreToFollow){
1136   p = sqlite3TreeViewPush(p, moreToFollow);
1137   sqlite3TreeViewLine(p, "%s", zLabel);
1138 }
1139 #endif /* SQLITE_DEBUG */
1140 
1141 /*
1142 ** variable-argument wrapper around sqlite3VXPrintf().
1143 */
1144 void sqlite3XPrintf(StrAccum *p, u32 bFlags, const char *zFormat, ...){
1145   va_list ap;
1146   va_start(ap,zFormat);
1147   sqlite3VXPrintf(p, bFlags, zFormat, ap);
1148   va_end(ap);
1149 }
1150