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