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