xref: /sqlite-3.40.0/src/printf.c (revision a8e41eca)
1a18c5681Sdrh /*
2a18c5681Sdrh ** The "printf" code that follows dates from the 1980's.  It is in
338b4149cSdrh ** the public domain.
4e84a306bSdrh **
5e84a306bSdrh **************************************************************************
6a18c5681Sdrh **
7ed1fddf4Sdrh ** This file contains code for a set of "printf"-like routines.  These
8ed1fddf4Sdrh ** routines format strings much like the printf() from the standard C
9ed1fddf4Sdrh ** library, though the implementation here has enhancements to support
10f5b5f9b9Smistachkin ** SQLite.
11a18c5681Sdrh */
12a18c5681Sdrh #include "sqliteInt.h"
137c68d60bSdrh 
14a18c5681Sdrh /*
15a18c5681Sdrh ** Conversion types fall into various categories as defined by the
16a18c5681Sdrh ** following enumeration.
17a18c5681Sdrh */
182c338a9dSdrh #define etRADIX       0 /* non-decimal integer types.  %x %o */
19ad5a9d71Sdrh #define etFLOAT       1 /* Floating point.  %f */
20ad5a9d71Sdrh #define etEXP         2 /* Exponentional notation. %e and %E */
21ad5a9d71Sdrh #define etGENERIC     3 /* Floating or exponential, depending on exponent. %g */
22ad5a9d71Sdrh #define etSIZE        4 /* Return number of characters processed so far. %n */
23ad5a9d71Sdrh #define etSTRING      5 /* Strings. %s */
24ad5a9d71Sdrh #define etDYNSTRING   6 /* Dynamically allocated strings. %z */
25ad5a9d71Sdrh #define etPERCENT     7 /* Percent symbol. %% */
26ad5a9d71Sdrh #define etCHARX       8 /* Characters. %c */
27a18c5681Sdrh /* The rest are extensions, not normally found in printf() */
28ad5a9d71Sdrh #define etSQLESCAPE   9 /* Strings with '\'' doubled.  %q */
29ad5a9d71Sdrh #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
300cfcf3fbSchw                           NULL pointers replaced by SQL NULL.  %Q */
31ad5a9d71Sdrh #define etTOKEN      11 /* a pointer to a Token structure */
32ad5a9d71Sdrh #define etSRCLIST    12 /* a pointer to a SrcList */
33ad5a9d71Sdrh #define etPOINTER    13 /* The %p conversion */
34ad5a9d71Sdrh #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
35ad5a9d71Sdrh #define etORDINAL    15 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
362c338a9dSdrh #define etDECIMAL    16 /* %d or %u, but not %x, %o */
37e84a306bSdrh 
382c338a9dSdrh #define etINVALID    17 /* Any unrecognized conversion type */
39874ba04cSdrh 
40e84a306bSdrh 
41e84a306bSdrh /*
42e84a306bSdrh ** An "etByte" is an 8-bit unsigned value.
43e84a306bSdrh */
44e84a306bSdrh typedef unsigned char etByte;
45a18c5681Sdrh 
46a18c5681Sdrh /*
47a18c5681Sdrh ** Each builtin conversion character (ex: the 'd' in "%d") is described
48a18c5681Sdrh ** by an instance of the following structure
49a18c5681Sdrh */
50a18c5681Sdrh typedef struct et_info {   /* Information about each format field */
51e84a306bSdrh   char fmttype;            /* The format field code letter */
52e84a306bSdrh   etByte base;             /* The base for radix conversion */
53e84a306bSdrh   etByte flags;            /* One or more of FLAG_ constants below */
54e84a306bSdrh   etByte type;             /* Conversion paradigm */
5576ff3a0eSdrh   etByte charset;          /* Offset into aDigits[] of the digits string */
5676ff3a0eSdrh   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
57a18c5681Sdrh } et_info;
58a18c5681Sdrh 
59a18c5681Sdrh /*
60e84a306bSdrh ** Allowed values for et_info.flags
61e84a306bSdrh */
62e84a306bSdrh #define FLAG_SIGNED    1     /* True if the value to convert is signed */
632c338a9dSdrh #define FLAG_STRING    4     /* Allow infinite precision */
64e84a306bSdrh 
65e84a306bSdrh 
66e84a306bSdrh /*
67a18c5681Sdrh ** The following table is searched linearly, so it is good to put the
68a18c5681Sdrh ** most frequently used conversion types first.
69a18c5681Sdrh */
7076ff3a0eSdrh static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
7176ff3a0eSdrh static const char aPrefix[] = "-x0\000X0";
725719628aSdrh static const et_info fmtinfo[] = {
732c338a9dSdrh   {  'd', 10, 1, etDECIMAL,    0,  0 },
744794f735Sdrh   {  's',  0, 4, etSTRING,     0,  0 },
75557cc60fSdrh   {  'g',  0, 1, etGENERIC,    30, 0 },
76153c62c4Sdrh   {  'z',  0, 4, etDYNSTRING,  0,  0 },
774794f735Sdrh   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
784794f735Sdrh   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
79f3b863edSdanielk1977   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
80e84a306bSdrh   {  'c',  0, 0, etCHARX,      0,  0 },
8176ff3a0eSdrh   {  'o',  8, 0, etRADIX,      0,  2 },
822c338a9dSdrh   {  'u', 10, 0, etDECIMAL,    0,  0 },
8376ff3a0eSdrh   {  'x', 16, 0, etRADIX,      16, 1 },
8476ff3a0eSdrh   {  'X', 16, 0, etRADIX,      0,  4 },
85b37df7b9Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
86e84a306bSdrh   {  'f',  0, 1, etFLOAT,      0,  0 },
8776ff3a0eSdrh   {  'e',  0, 1, etEXP,        30, 0 },
8876ff3a0eSdrh   {  'E',  0, 1, etEXP,        14, 0 },
8976ff3a0eSdrh   {  'G',  0, 1, etGENERIC,    14, 0 },
90b37df7b9Sdrh #endif
912c338a9dSdrh   {  'i', 10, 1, etDECIMAL,    0,  0 },
92e84a306bSdrh   {  'n',  0, 0, etSIZE,       0,  0 },
93e84a306bSdrh   {  '%',  0, 0, etPERCENT,    0,  0 },
9476ff3a0eSdrh   {  'p', 16, 0, etPOINTER,    0,  1 },
957e3ff5d8Sdrh 
968236f688Sdrh   /* All the rest are undocumented and are for internal use only */
978236f688Sdrh   {  'T',  0, 0, etTOKEN,      0,  0 },
988236f688Sdrh   {  'S',  0, 0, etSRCLIST,    0,  0 },
998236f688Sdrh   {  'r', 10, 1, etORDINAL,    0,  0 },
100a18c5681Sdrh };
101a18c5681Sdrh 
102a0ed86bcSdrh /* Floating point constants used for rounding */
103a0ed86bcSdrh static const double arRound[] = {
104a0ed86bcSdrh   5.0e-01, 5.0e-02, 5.0e-03, 5.0e-04, 5.0e-05,
105a0ed86bcSdrh   5.0e-06, 5.0e-07, 5.0e-08, 5.0e-09, 5.0e-10,
106a0ed86bcSdrh };
107a0ed86bcSdrh 
108a18c5681Sdrh /*
109b37df7b9Sdrh ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
110a18c5681Sdrh ** conversions will work.
111a18c5681Sdrh */
112b37df7b9Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
113a18c5681Sdrh /*
114a18c5681Sdrh ** "*val" is a double such that 0.1 <= *val < 10.0
115a18c5681Sdrh ** Return the ascii code for the leading digit of *val, then
116a18c5681Sdrh ** multiply "*val" by 10.0 to renormalize.
117a18c5681Sdrh **
118a18c5681Sdrh ** Example:
119a18c5681Sdrh **     input:     *val = 3.14159
120a18c5681Sdrh **     output:    *val = 1.4159    function return = '3'
121a18c5681Sdrh **
122a18c5681Sdrh ** The counter *cnt is incremented each time.  After counter exceeds
123a18c5681Sdrh ** 16 (the number of significant digits in a 64-bit float) '0' is
124a18c5681Sdrh ** always returned.
125a18c5681Sdrh */
126ea678832Sdrh static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
127a18c5681Sdrh   int digit;
128384eef32Sdrh   LONGDOUBLE_TYPE d;
12972b3fbc7Sdrh   if( (*cnt)<=0 ) return '0';
13072b3fbc7Sdrh   (*cnt)--;
131a18c5681Sdrh   digit = (int)*val;
132a18c5681Sdrh   d = digit;
133a18c5681Sdrh   digit += '0';
134a18c5681Sdrh   *val = (*val - d)*10.0;
135ea678832Sdrh   return (char)digit;
136a18c5681Sdrh }
137b37df7b9Sdrh #endif /* SQLITE_OMIT_FLOATING_POINT */
138a18c5681Sdrh 
13979158e18Sdrh /*
140a6353a3fSdrh ** Set the StrAccum object to an error mode.
141a6353a3fSdrh */
142a5c1416dSdrh static void setStrAccumError(StrAccum *p, u8 eError){
1430cdbe1aeSdrh   assert( eError==SQLITE_NOMEM || eError==SQLITE_TOOBIG );
144a6353a3fSdrh   p->accError = eError;
145255a81f1Sdrh   if( p->mxAlloc ) sqlite3_str_reset(p);
146c3dcdba3Sdrh   if( eError==SQLITE_TOOBIG ) sqlite3ErrorToParser(p->db, eError);
147a6353a3fSdrh }
148a6353a3fSdrh 
149a6353a3fSdrh /*
150a5c1416dSdrh ** Extra argument values from a PrintfArguments object
151a5c1416dSdrh */
152a5c1416dSdrh static sqlite3_int64 getIntArg(PrintfArguments *p){
153a5c1416dSdrh   if( p->nArg<=p->nUsed ) return 0;
154a5c1416dSdrh   return sqlite3_value_int64(p->apArg[p->nUsed++]);
155a5c1416dSdrh }
156a5c1416dSdrh static double getDoubleArg(PrintfArguments *p){
157a5c1416dSdrh   if( p->nArg<=p->nUsed ) return 0.0;
158a5c1416dSdrh   return sqlite3_value_double(p->apArg[p->nUsed++]);
159a5c1416dSdrh }
160a5c1416dSdrh static char *getTextArg(PrintfArguments *p){
161a5c1416dSdrh   if( p->nArg<=p->nUsed ) return 0;
162a5c1416dSdrh   return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
163a5c1416dSdrh }
164a5c1416dSdrh 
16529642252Sdrh /*
16629642252Sdrh ** Allocate memory for a temporary buffer needed for printf rendering.
16729642252Sdrh **
16829642252Sdrh ** If the requested size of the temp buffer is larger than the size
16929642252Sdrh ** of the output buffer in pAccum, then cause an SQLITE_TOOBIG error.
17029642252Sdrh ** Do the size check before the memory allocation to prevent rogue
17129642252Sdrh ** SQL from requesting large allocations using the precision or width
17229642252Sdrh ** field of the printf() function.
17329642252Sdrh */
17429642252Sdrh static char *printfTempBuf(sqlite3_str *pAccum, sqlite3_int64 n){
17529642252Sdrh   char *z;
176255a81f1Sdrh   if( pAccum->accError ) return 0;
17729642252Sdrh   if( n>pAccum->nAlloc && n>pAccum->mxAlloc ){
17829642252Sdrh     setStrAccumError(pAccum, SQLITE_TOOBIG);
17929642252Sdrh     return 0;
18029642252Sdrh   }
18129642252Sdrh   z = sqlite3DbMallocRaw(pAccum->db, n);
18229642252Sdrh   if( z==0 ){
18329642252Sdrh     setStrAccumError(pAccum, SQLITE_NOMEM);
18429642252Sdrh   }
18529642252Sdrh   return z;
18629642252Sdrh }
187a5c1416dSdrh 
188a5c1416dSdrh /*
18979158e18Sdrh ** On machines with a small stack size, you can redefine the
190ed1fddf4Sdrh ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
19179158e18Sdrh */
19279158e18Sdrh #ifndef SQLITE_PRINT_BUF_SIZE
19359eedf79Sdrh # define SQLITE_PRINT_BUF_SIZE 70
19450d654daSdrh #endif
19579158e18Sdrh #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
196a18c5681Sdrh 
197a18c5681Sdrh /*
198ed1fddf4Sdrh ** Render a string given by "fmt" into the StrAccum object.
199a18c5681Sdrh */
2000cdbe1aeSdrh void sqlite3_str_vappendf(
2010cdbe1aeSdrh   sqlite3_str *pAccum,       /* Accumulate results here */
2025f968436Sdrh   const char *fmt,           /* Format string */
2035f968436Sdrh   va_list ap                 /* arguments */
204a18c5681Sdrh ){
205e84a306bSdrh   int c;                     /* Next character in the format string */
206e84a306bSdrh   char *bufpt;               /* Pointer to the conversion buffer */
207e84a306bSdrh   int precision;             /* Precision of the current field */
208e84a306bSdrh   int length;                /* Length of the field */
209e84a306bSdrh   int idx;                   /* A general purpose loop counter */
210a18c5681Sdrh   int width;                 /* Width of the current field */
211e84a306bSdrh   etByte flag_leftjustify;   /* True if "-" flag is present */
2122c338a9dSdrh   etByte flag_prefix;        /* '+' or ' ' or 0 for prefix */
213e84a306bSdrh   etByte flag_alternateform; /* True if "#" flag is present */
214531fe878Sdrh   etByte flag_altform2;      /* True if "!" flag is present */
215e84a306bSdrh   etByte flag_zeropad;       /* True if field width constant starts with zero */
2162c338a9dSdrh   etByte flag_long;          /* 1 for the "l" flag, 2 for "ll", 0 by default */
2173e9aeec0Sdrh   etByte done;               /* Loop termination flag */
2182c338a9dSdrh   etByte cThousand;          /* Thousands separator for %d and %u */
219ad5a9d71Sdrh   etByte xtype = etINVALID;  /* Conversion paradigm */
220a5c1416dSdrh   u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */
221ed1fddf4Sdrh   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
22227436af7Sdrh   sqlite_uint64 longvalue;   /* Value for integer types */
223384eef32Sdrh   LONGDOUBLE_TYPE realvalue; /* Value for real types */
2245719628aSdrh   const et_info *infop;      /* Pointer to the appropriate info structure */
22559eedf79Sdrh   char *zOut;                /* Rendering buffer */
22659eedf79Sdrh   int nOut;                  /* Size of the rendering buffer */
227af8f513fSdrh   char *zExtra = 0;          /* Malloced memory used by some conversion */
228b37df7b9Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
229557cc60fSdrh   int  exp, e2;              /* exponent of real numbers */
230ed1fddf4Sdrh   int nsd;                   /* Number of significant digits returned */
231a18c5681Sdrh   double rounder;            /* Used for rounding floating point values */
232e84a306bSdrh   etByte flag_dp;            /* True if decimal point should be shown */
233e84a306bSdrh   etByte flag_rtz;           /* True if trailing zeros should be removed */
234a18c5681Sdrh #endif
235a5c1416dSdrh   PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
236ed1fddf4Sdrh   char buf[etBUFSIZE];       /* Conversion buffer */
237a18c5681Sdrh 
238cc398969Sdrh   /* pAccum never starts out with an empty buffer that was obtained from
239cc398969Sdrh   ** malloc().  This precondition is required by the mprintf("%z...")
240cc398969Sdrh   ** optimization. */
241cc398969Sdrh   assert( pAccum->nChar>0 || (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
242cc398969Sdrh 
243a18c5681Sdrh   bufpt = 0;
2448236f688Sdrh   if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
245a5c1416dSdrh     pArgList = va_arg(ap, PrintfArguments*);
2468236f688Sdrh     bArgList = 1;
247a5c1416dSdrh   }else{
2488236f688Sdrh     bArgList = 0;
249a5c1416dSdrh   }
250a18c5681Sdrh   for(; (c=(*fmt))!=0; ++fmt){
251a18c5681Sdrh     if( c!='%' ){
252a18c5681Sdrh       bufpt = (char *)fmt;
253760b1598Sdrh #if HAVE_STRCHRNUL
254760b1598Sdrh       fmt = strchrnul(fmt, '%');
255760b1598Sdrh #else
256760b1598Sdrh       do{ fmt++; }while( *fmt && *fmt != '%' );
257760b1598Sdrh #endif
2580cdbe1aeSdrh       sqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt));
259760b1598Sdrh       if( *fmt==0 ) break;
260a18c5681Sdrh     }
261a18c5681Sdrh     if( (c=(*++fmt))==0 ){
2620cdbe1aeSdrh       sqlite3_str_append(pAccum, "%", 1);
263a18c5681Sdrh       break;
264a18c5681Sdrh     }
265a18c5681Sdrh     /* Find out what flags are present */
2662c338a9dSdrh     flag_leftjustify = flag_prefix = cThousand =
267557cc60fSdrh      flag_alternateform = flag_altform2 = flag_zeropad = 0;
2683e9aeec0Sdrh     done = 0;
2699a6d01bfSdrh     width = 0;
2709a6d01bfSdrh     flag_long = 0;
2719a6d01bfSdrh     precision = -1;
272a18c5681Sdrh     do{
273a18c5681Sdrh       switch( c ){
2743e9aeec0Sdrh         case '-':   flag_leftjustify = 1;     break;
2752c338a9dSdrh         case '+':   flag_prefix = '+';        break;
2762c338a9dSdrh         case ' ':   flag_prefix = ' ';        break;
2773e9aeec0Sdrh         case '#':   flag_alternateform = 1;   break;
2783e9aeec0Sdrh         case '!':   flag_altform2 = 1;        break;
2793e9aeec0Sdrh         case '0':   flag_zeropad = 1;         break;
2802c338a9dSdrh         case ',':   cThousand = ',';          break;
2813e9aeec0Sdrh         default:    done = 1;                 break;
2829a6d01bfSdrh         case 'l': {
2839a6d01bfSdrh           flag_long = 1;
2849a6d01bfSdrh           c = *++fmt;
2859a6d01bfSdrh           if( c=='l' ){
2869a6d01bfSdrh             c = *++fmt;
2879a6d01bfSdrh             flag_long = 2;
288a18c5681Sdrh           }
2899a6d01bfSdrh           done = 1;
2909a6d01bfSdrh           break;
2919a6d01bfSdrh         }
2929a6d01bfSdrh         case '1': case '2': case '3': case '4': case '5':
2939a6d01bfSdrh         case '6': case '7': case '8': case '9': {
2949a6d01bfSdrh           unsigned wx = c - '0';
2959a6d01bfSdrh           while( (c = *++fmt)>='0' && c<='9' ){
2969a6d01bfSdrh             wx = wx*10 + c - '0';
2979a6d01bfSdrh           }
2989a6d01bfSdrh           testcase( wx>0x7fffffff );
2999a6d01bfSdrh           width = wx & 0x7fffffff;
3009a6d01bfSdrh #ifdef SQLITE_PRINTF_PRECISION_LIMIT
3019a6d01bfSdrh           if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
3029a6d01bfSdrh             width = SQLITE_PRINTF_PRECISION_LIMIT;
3039a6d01bfSdrh           }
3049a6d01bfSdrh #endif
3059a6d01bfSdrh           if( c!='.' && c!='l' ){
3069a6d01bfSdrh             done = 1;
3079a6d01bfSdrh           }else{
3089a6d01bfSdrh             fmt--;
3099a6d01bfSdrh           }
3109a6d01bfSdrh           break;
3119a6d01bfSdrh         }
3129a6d01bfSdrh         case '*': {
313a5c1416dSdrh           if( bArgList ){
314a5c1416dSdrh             width = (int)getIntArg(pArgList);
315a5c1416dSdrh           }else{
316a18c5681Sdrh             width = va_arg(ap,int);
317a5c1416dSdrh           }
318a18c5681Sdrh           if( width<0 ){
319a18c5681Sdrh             flag_leftjustify = 1;
320b6f47debSdrh             width = width >= -2147483647 ? -width : 0;
321a18c5681Sdrh           }
322c386ef4fSdrh #ifdef SQLITE_PRINTF_PRECISION_LIMIT
323c386ef4fSdrh           if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
324c386ef4fSdrh             width = SQLITE_PRINTF_PRECISION_LIMIT;
325c386ef4fSdrh           }
326c386ef4fSdrh #endif
3279a6d01bfSdrh           if( (c = fmt[1])!='.' && c!='l' ){
3289a6d01bfSdrh             c = *++fmt;
3299a6d01bfSdrh             done = 1;
3309a6d01bfSdrh           }
3319a6d01bfSdrh           break;
3329a6d01bfSdrh         }
3339a6d01bfSdrh         case '.': {
334a18c5681Sdrh           c = *++fmt;
335a18c5681Sdrh           if( c=='*' ){
336a5c1416dSdrh             if( bArgList ){
337a5c1416dSdrh               precision = (int)getIntArg(pArgList);
338a5c1416dSdrh             }else{
339a18c5681Sdrh               precision = va_arg(ap,int);
340a5c1416dSdrh             }
341b6f47debSdrh             if( precision<0 ){
342b6f47debSdrh               precision = precision >= -2147483647 ? -precision : -1;
343b6f47debSdrh             }
3449a6d01bfSdrh             c = *++fmt;
345a18c5681Sdrh           }else{
346b6f47debSdrh             unsigned px = 0;
34717a68934Sdrh             while( c>='0' && c<='9' ){
348b6f47debSdrh               px = px*10 + c - '0';
349a18c5681Sdrh               c = *++fmt;
350a18c5681Sdrh             }
351b6f47debSdrh             testcase( px>0x7fffffff );
352b6f47debSdrh             precision = px & 0x7fffffff;
353a18c5681Sdrh           }
354c386ef4fSdrh #ifdef SQLITE_PRINTF_PRECISION_LIMIT
355c386ef4fSdrh           if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
356c386ef4fSdrh             precision = SQLITE_PRINTF_PRECISION_LIMIT;
357c386ef4fSdrh           }
358c386ef4fSdrh #endif
359a18c5681Sdrh           if( c=='l' ){
3609a6d01bfSdrh             --fmt;
361a34b6764Sdrh           }else{
3629a6d01bfSdrh             done = 1;
363a18c5681Sdrh           }
3649a6d01bfSdrh           break;
3659a6d01bfSdrh         }
3669a6d01bfSdrh       }
3679a6d01bfSdrh     }while( !done && (c=(*++fmt))!=0 );
3689a6d01bfSdrh 
369a18c5681Sdrh     /* Fetch the info entry for the field */
370874ba04cSdrh     infop = &fmtinfo[0];
371874ba04cSdrh     xtype = etINVALID;
37200e13613Sdanielk1977     for(idx=0; idx<ArraySize(fmtinfo); idx++){
373a18c5681Sdrh       if( c==fmtinfo[idx].fmttype ){
374a18c5681Sdrh         infop = &fmtinfo[idx];
375e84a306bSdrh         xtype = infop->type;
376a18c5681Sdrh         break;
377a18c5681Sdrh       }
378a18c5681Sdrh     }
37943617e9aSdrh 
380a18c5681Sdrh     /*
381a18c5681Sdrh     ** At this point, variables are initialized as follows:
382a18c5681Sdrh     **
383a18c5681Sdrh     **   flag_alternateform          TRUE if a '#' is present.
3843e9aeec0Sdrh     **   flag_altform2               TRUE if a '!' is present.
3852c338a9dSdrh     **   flag_prefix                 '+' or ' ' or zero
386a18c5681Sdrh     **   flag_leftjustify            TRUE if a '-' is present or if the
387a18c5681Sdrh     **                               field width was negative.
388a18c5681Sdrh     **   flag_zeropad                TRUE if the width began with 0.
3892c338a9dSdrh     **   flag_long                   1 for "l", 2 for "ll"
390a18c5681Sdrh     **   width                       The specified field width.  This is
391a18c5681Sdrh     **                               always non-negative.  Zero is the default.
392a18c5681Sdrh     **   precision                   The specified precision.  The default
393a18c5681Sdrh     **                               is -1.
394a18c5681Sdrh     **   xtype                       The class of the conversion.
395a18c5681Sdrh     **   infop                       Pointer to the appropriate info struct.
396a18c5681Sdrh     */
397a18c5681Sdrh     switch( xtype ){
398fe63d1c9Sdrh       case etPOINTER:
3992c338a9dSdrh         flag_long = sizeof(char*)==sizeof(i64) ? 2 :
4002c338a9dSdrh                      sizeof(char*)==sizeof(long int) ? 1 : 0;
401fe63d1c9Sdrh         /* Fall through into the next case */
4029a99334dSdrh       case etORDINAL:
403a18c5681Sdrh       case etRADIX:
4042c338a9dSdrh         cThousand = 0;
4052c338a9dSdrh         /* Fall through into the next case */
4062c338a9dSdrh       case etDECIMAL:
407e84a306bSdrh         if( infop->flags & FLAG_SIGNED ){
408e9707671Sdrh           i64 v;
409a5c1416dSdrh           if( bArgList ){
410a5c1416dSdrh             v = getIntArg(pArgList);
411eeb23a4cSdrh           }else if( flag_long ){
4122c338a9dSdrh             if( flag_long==2 ){
4132c338a9dSdrh               v = va_arg(ap,i64) ;
4142c338a9dSdrh             }else{
415eeb23a4cSdrh               v = va_arg(ap,long int);
4162c338a9dSdrh             }
417eeb23a4cSdrh           }else{
418eeb23a4cSdrh             v = va_arg(ap,int);
419eeb23a4cSdrh           }
420e9707671Sdrh           if( v<0 ){
421158b9cb9Sdrh             if( v==SMALLEST_INT64 ){
422158b9cb9Sdrh               longvalue = ((u64)1)<<63;
423158b9cb9Sdrh             }else{
424158b9cb9Sdrh               longvalue = -v;
425158b9cb9Sdrh             }
426cfcdaefeSdanielk1977             prefix = '-';
427cfcdaefeSdanielk1977           }else{
428e9707671Sdrh             longvalue = v;
4292c338a9dSdrh             prefix = flag_prefix;
430cfcdaefeSdanielk1977           }
431e9707671Sdrh         }else{
432a5c1416dSdrh           if( bArgList ){
433a5c1416dSdrh             longvalue = (u64)getIntArg(pArgList);
434eeb23a4cSdrh           }else if( flag_long ){
4352c338a9dSdrh             if( flag_long==2 ){
4362c338a9dSdrh               longvalue = va_arg(ap,u64);
4372c338a9dSdrh             }else{
438eeb23a4cSdrh               longvalue = va_arg(ap,unsigned long int);
4392c338a9dSdrh             }
440eeb23a4cSdrh           }else{
441eeb23a4cSdrh             longvalue = va_arg(ap,unsigned int);
442eeb23a4cSdrh           }
443e9707671Sdrh           prefix = 0;
444e9707671Sdrh         }
445e9707671Sdrh         if( longvalue==0 ) flag_alternateform = 0;
446a18c5681Sdrh         if( flag_zeropad && precision<width-(prefix!=0) ){
447a18c5681Sdrh           precision = width-(prefix!=0);
448a18c5681Sdrh         }
4492c338a9dSdrh         if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
45059eedf79Sdrh           nOut = etBUFSIZE;
45159eedf79Sdrh           zOut = buf;
45259eedf79Sdrh         }else{
4537ba03ea1Sdrh           u64 n;
4547ba03ea1Sdrh           n = (u64)precision + 10;
4557ba03ea1Sdrh           if( cThousand ) n += precision/3;
45629642252Sdrh           zOut = zExtra = printfTempBuf(pAccum, n);
45729642252Sdrh           if( zOut==0 ) return;
4585f42995aSdrh           nOut = (int)n;
45959eedf79Sdrh         }
46059eedf79Sdrh         bufpt = &zOut[nOut-1];
4619a99334dSdrh         if( xtype==etORDINAL ){
46243f6e064Sdrh           static const char zOrd[] = "thstndrd";
463ea678832Sdrh           int x = (int)(longvalue % 10);
46443f6e064Sdrh           if( x>=4 || (longvalue/10)%10==1 ){
46543f6e064Sdrh             x = 0;
46643f6e064Sdrh           }
46759eedf79Sdrh           *(--bufpt) = zOrd[x*2+1];
46859eedf79Sdrh           *(--bufpt) = zOrd[x*2];
4699a99334dSdrh         }
470a18c5681Sdrh         {
4710e682099Sdrh           const char *cset = &aDigits[infop->charset];
4720e682099Sdrh           u8 base = infop->base;
473a18c5681Sdrh           do{                                           /* Convert to ascii */
474a18c5681Sdrh             *(--bufpt) = cset[longvalue%base];
475a18c5681Sdrh             longvalue = longvalue/base;
476a18c5681Sdrh           }while( longvalue>0 );
477a18c5681Sdrh         }
47859eedf79Sdrh         length = (int)(&zOut[nOut-1]-bufpt);
4792c338a9dSdrh         while( precision>length ){
480a18c5681Sdrh           *(--bufpt) = '0';                             /* Zero pad */
4812c338a9dSdrh           length++;
4822c338a9dSdrh         }
4832c338a9dSdrh         if( cThousand ){
4842c338a9dSdrh           int nn = (length - 1)/3;  /* Number of "," to insert */
4852c338a9dSdrh           int ix = (length - 1)%3 + 1;
4862c338a9dSdrh           bufpt -= nn;
4872c338a9dSdrh           for(idx=0; nn>0; idx++){
4882c338a9dSdrh             bufpt[idx] = bufpt[idx+nn];
4892c338a9dSdrh             ix--;
4902c338a9dSdrh             if( ix==0 ){
4912c338a9dSdrh               bufpt[++idx] = cThousand;
4922c338a9dSdrh               nn--;
4932c338a9dSdrh               ix = 3;
4942c338a9dSdrh             }
4952c338a9dSdrh           }
496a18c5681Sdrh         }
497a18c5681Sdrh         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
498a18c5681Sdrh         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
49976ff3a0eSdrh           const char *pre;
50076ff3a0eSdrh           char x;
50176ff3a0eSdrh           pre = &aPrefix[infop->prefix];
50276ff3a0eSdrh           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
503a18c5681Sdrh         }
50459eedf79Sdrh         length = (int)(&zOut[nOut-1]-bufpt);
505a18c5681Sdrh         break;
506a18c5681Sdrh       case etFLOAT:
507a18c5681Sdrh       case etEXP:
508a18c5681Sdrh       case etGENERIC:
509a5c1416dSdrh         if( bArgList ){
510a5c1416dSdrh           realvalue = getDoubleArg(pArgList);
511a5c1416dSdrh         }else{
512a18c5681Sdrh           realvalue = va_arg(ap,double);
513a5c1416dSdrh         }
51469ef7036Sdrh #ifdef SQLITE_OMIT_FLOATING_POINT
51569ef7036Sdrh         length = 0;
51669ef7036Sdrh #else
517a18c5681Sdrh         if( precision<0 ) precision = 6;         /* Set default precision */
518a18c5681Sdrh         if( realvalue<0.0 ){
519a18c5681Sdrh           realvalue = -realvalue;
520a18c5681Sdrh           prefix = '-';
521a18c5681Sdrh         }else{
5222c338a9dSdrh           prefix = flag_prefix;
523a18c5681Sdrh         }
5243e9aeec0Sdrh         if( xtype==etGENERIC && precision>0 ) precision--;
525a30d22a7Sdrh         testcase( precision>0xfff );
526a0ed86bcSdrh         idx = precision & 0xfff;
527a0ed86bcSdrh         rounder = arRound[idx%10];
528a0ed86bcSdrh         while( idx>=10 ){ rounder *= 1.0e-10; idx -= 10; }
529a0ed86bcSdrh         if( xtype==etFLOAT ){
530ef7d5187Sdrh           double rx = (double)realvalue;
531ef7d5187Sdrh           sqlite3_uint64 u;
532ef7d5187Sdrh           int ex;
533ef7d5187Sdrh           memcpy(&u, &rx, sizeof(u));
534ef7d5187Sdrh           ex = -1023 + (int)((u>>52)&0x7ff);
535ef7d5187Sdrh           if( precision+(ex/3) < 15 ) rounder += realvalue*3e-16;
536a0ed86bcSdrh           realvalue += rounder;
537a0ed86bcSdrh         }
538a18c5681Sdrh         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
539a18c5681Sdrh         exp = 0;
540ea678832Sdrh         if( sqlite3IsNaN((double)realvalue) ){
54153c14021Sdrh           bufpt = "NaN";
54253c14021Sdrh           length = 3;
54353c14021Sdrh           break;
54453c14021Sdrh         }
545a18c5681Sdrh         if( realvalue>0.0 ){
54672b3fbc7Sdrh           LONGDOUBLE_TYPE scale = 1.0;
5474ef94130Sdrh           while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
5482a8f6712Sdrh           while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
54972b3fbc7Sdrh           while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
55072b3fbc7Sdrh           realvalue /= scale;
551af005fbcSdrh           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
552af005fbcSdrh           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
553af005fbcSdrh           if( exp>350 ){
5542a8f6712Sdrh             bufpt = buf;
5552a8f6712Sdrh             buf[0] = prefix;
5562a8f6712Sdrh             memcpy(buf+(prefix!=0),"Inf",4);
5572a8f6712Sdrh             length = 3+(prefix!=0);
558a18c5681Sdrh             break;
559a18c5681Sdrh           }
560a18c5681Sdrh         }
561a18c5681Sdrh         bufpt = buf;
562a18c5681Sdrh         /*
563a18c5681Sdrh         ** If the field type is etGENERIC, then convert to either etEXP
564a18c5681Sdrh         ** or etFLOAT, as appropriate.
565a18c5681Sdrh         */
566a18c5681Sdrh         if( xtype!=etFLOAT ){
567a18c5681Sdrh           realvalue += rounder;
568a18c5681Sdrh           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
569a18c5681Sdrh         }
570a18c5681Sdrh         if( xtype==etGENERIC ){
571a18c5681Sdrh           flag_rtz = !flag_alternateform;
572a18c5681Sdrh           if( exp<-4 || exp>precision ){
573a18c5681Sdrh             xtype = etEXP;
574a18c5681Sdrh           }else{
575a18c5681Sdrh             precision = precision - exp;
576a18c5681Sdrh             xtype = etFLOAT;
577a18c5681Sdrh           }
578a18c5681Sdrh         }else{
57972b3fbc7Sdrh           flag_rtz = flag_altform2;
580a18c5681Sdrh         }
581557cc60fSdrh         if( xtype==etEXP ){
582557cc60fSdrh           e2 = 0;
583557cc60fSdrh         }else{
584557cc60fSdrh           e2 = exp;
585557cc60fSdrh         }
58629642252Sdrh         {
58729642252Sdrh           i64 szBufNeeded;           /* Size of a temporary buffer needed */
58829642252Sdrh           szBufNeeded = MAX(e2,0)+(i64)precision+(i64)width+15;
58929642252Sdrh           if( szBufNeeded > etBUFSIZE ){
59029642252Sdrh             bufpt = zExtra = printfTempBuf(pAccum, szBufNeeded);
59129642252Sdrh             if( bufpt==0 ) return;
59259eedf79Sdrh           }
59359eedf79Sdrh         }
59459eedf79Sdrh         zOut = bufpt;
59572b3fbc7Sdrh         nsd = 16 + flag_altform2*10;
596ea678832Sdrh         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
597557cc60fSdrh         /* The sign in front of the number */
598557cc60fSdrh         if( prefix ){
599557cc60fSdrh           *(bufpt++) = prefix;
600557cc60fSdrh         }
601557cc60fSdrh         /* Digits prior to the decimal point */
602557cc60fSdrh         if( e2<0 ){
603557cc60fSdrh           *(bufpt++) = '0';
604557cc60fSdrh         }else{
605557cc60fSdrh           for(; e2>=0; e2--){
606557cc60fSdrh             *(bufpt++) = et_getdigit(&realvalue,&nsd);
607557cc60fSdrh           }
608557cc60fSdrh         }
609557cc60fSdrh         /* The decimal point */
610557cc60fSdrh         if( flag_dp ){
611557cc60fSdrh           *(bufpt++) = '.';
612557cc60fSdrh         }
613557cc60fSdrh         /* "0" digits after the decimal point but before the first
614557cc60fSdrh         ** significant digit of the number */
615af005fbcSdrh         for(e2++; e2<0; precision--, e2++){
616af005fbcSdrh           assert( precision>0 );
617a18c5681Sdrh           *(bufpt++) = '0';
618a18c5681Sdrh         }
619557cc60fSdrh         /* Significant digits after the decimal point */
620557cc60fSdrh         while( (precision--)>0 ){
621557cc60fSdrh           *(bufpt++) = et_getdigit(&realvalue,&nsd);
622a18c5681Sdrh         }
623557cc60fSdrh         /* Remove trailing zeros and the "." if no digits follow the "." */
624557cc60fSdrh         if( flag_rtz && flag_dp ){
6253e9aeec0Sdrh           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
62659eedf79Sdrh           assert( bufpt>zOut );
6273e9aeec0Sdrh           if( bufpt[-1]=='.' ){
628557cc60fSdrh             if( flag_altform2 ){
629557cc60fSdrh               *(bufpt++) = '0';
630557cc60fSdrh             }else{
631557cc60fSdrh               *(--bufpt) = 0;
632a18c5681Sdrh             }
633557cc60fSdrh           }
634557cc60fSdrh         }
635557cc60fSdrh         /* Add the "eNNN" suffix */
63659eedf79Sdrh         if( xtype==etEXP ){
63776ff3a0eSdrh           *(bufpt++) = aDigits[infop->charset];
638557cc60fSdrh           if( exp<0 ){
639557cc60fSdrh             *(bufpt++) = '-'; exp = -exp;
640557cc60fSdrh           }else{
641557cc60fSdrh             *(bufpt++) = '+';
642557cc60fSdrh           }
643a18c5681Sdrh           if( exp>=100 ){
644ea678832Sdrh             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
645a18c5681Sdrh             exp %= 100;
646a18c5681Sdrh           }
647ea678832Sdrh           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
648ea678832Sdrh           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
649a18c5681Sdrh         }
650557cc60fSdrh         *bufpt = 0;
651557cc60fSdrh 
652a18c5681Sdrh         /* The converted number is in buf[] and zero terminated. Output it.
653a18c5681Sdrh         ** Note that the number is in the usual order, not reversed as with
654a18c5681Sdrh         ** integer conversions. */
65559eedf79Sdrh         length = (int)(bufpt-zOut);
65659eedf79Sdrh         bufpt = zOut;
657a18c5681Sdrh 
658a18c5681Sdrh         /* Special case:  Add leading zeros if the flag_zeropad flag is
659a18c5681Sdrh         ** set and we are not left justified */
660a18c5681Sdrh         if( flag_zeropad && !flag_leftjustify && length < width){
661a18c5681Sdrh           int i;
662a18c5681Sdrh           int nPad = width - length;
663a18c5681Sdrh           for(i=width; i>=nPad; i--){
664a18c5681Sdrh             bufpt[i] = bufpt[i-nPad];
665a18c5681Sdrh           }
666a18c5681Sdrh           i = prefix!=0;
667a18c5681Sdrh           while( nPad-- ) bufpt[i++] = '0';
668a18c5681Sdrh           length = width;
669a18c5681Sdrh         }
67069ef7036Sdrh #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
671a18c5681Sdrh         break;
672a18c5681Sdrh       case etSIZE:
673fc6ee9dfSdrh         if( !bArgList ){
674fc6ee9dfSdrh           *(va_arg(ap,int*)) = pAccum->nChar;
675fc6ee9dfSdrh         }
676a18c5681Sdrh         length = width = 0;
677a18c5681Sdrh         break;
678a18c5681Sdrh       case etPERCENT:
679a18c5681Sdrh         buf[0] = '%';
680a18c5681Sdrh         bufpt = buf;
681a18c5681Sdrh         length = 1;
682a18c5681Sdrh         break;
683a18c5681Sdrh       case etCHARX:
684a5c1416dSdrh         if( bArgList ){
685fc6ee9dfSdrh           bufpt = getTextArg(pArgList);
686a15a7c35Sdrh           length = 1;
687136102beSdrh           if( bufpt ){
688136102beSdrh             buf[0] = c = *(bufpt++);
689136102beSdrh             if( (c&0xc0)==0xc0 ){
690136102beSdrh               while( length<4 && (bufpt[0]&0xc0)==0x80 ){
691136102beSdrh                 buf[length++] = *(bufpt++);
692136102beSdrh               }
693136102beSdrh             }
694a15a7c35Sdrh           }else{
695a15a7c35Sdrh             buf[0] = 0;
696136102beSdrh           }
697a5c1416dSdrh         }else{
698136102beSdrh           unsigned int ch = va_arg(ap,unsigned int);
699136102beSdrh           if( ch<0x00080 ){
700136102beSdrh             buf[0] = ch & 0xff;
701136102beSdrh             length = 1;
702136102beSdrh           }else if( ch<0x00800 ){
703136102beSdrh             buf[0] = 0xc0 + (u8)((ch>>6)&0x1f);
704136102beSdrh             buf[1] = 0x80 + (u8)(ch & 0x3f);
705136102beSdrh             length = 2;
706136102beSdrh           }else if( ch<0x10000 ){
707136102beSdrh             buf[0] = 0xe0 + (u8)((ch>>12)&0x0f);
708136102beSdrh             buf[1] = 0x80 + (u8)((ch>>6) & 0x3f);
709136102beSdrh             buf[2] = 0x80 + (u8)(ch & 0x3f);
710136102beSdrh             length = 3;
711136102beSdrh           }else{
712136102beSdrh             buf[0] = 0xf0 + (u8)((ch>>18) & 0x07);
713136102beSdrh             buf[1] = 0x80 + (u8)((ch>>12) & 0x3f);
714136102beSdrh             buf[2] = 0x80 + (u8)((ch>>6) & 0x3f);
715136102beSdrh             buf[3] = 0x80 + (u8)(ch & 0x3f);
716136102beSdrh             length = 4;
717136102beSdrh           }
718a5c1416dSdrh         }
719af8f513fSdrh         if( precision>1 ){
720af8f513fSdrh           width -= precision-1;
721af8f513fSdrh           if( width>1 && !flag_leftjustify ){
7220cdbe1aeSdrh             sqlite3_str_appendchar(pAccum, width-1, ' ');
723af8f513fSdrh             width = 0;
724a18c5681Sdrh           }
725136102beSdrh           while( precision-- > 1 ){
7260cdbe1aeSdrh             sqlite3_str_append(pAccum, buf, length);
727af8f513fSdrh           }
728136102beSdrh         }
729a18c5681Sdrh         bufpt = buf;
730cf7c8370Sdrh         flag_altform2 = 1;
731cf7c8370Sdrh         goto adjust_width_for_utf8;
732a18c5681Sdrh       case etSTRING:
733d93d8a81Sdrh       case etDYNSTRING:
734a5c1416dSdrh         if( bArgList ){
735a5c1416dSdrh           bufpt = getTextArg(pArgList);
7362a8f6712Sdrh           xtype = etSTRING;
737a5c1416dSdrh         }else{
738cb485882Sdrh           bufpt = va_arg(ap,char*);
739a5c1416dSdrh         }
740d93d8a81Sdrh         if( bufpt==0 ){
741d93d8a81Sdrh           bufpt = "";
7422a8f6712Sdrh         }else if( xtype==etDYNSTRING ){
743af524a63Sdrh           if( pAccum->nChar==0
744af524a63Sdrh            && pAccum->mxAlloc
745af524a63Sdrh            && width==0
746af524a63Sdrh            && precision<0
747af524a63Sdrh            && pAccum->accError==0
748af524a63Sdrh           ){
749cc398969Sdrh             /* Special optimization for sqlite3_mprintf("%z..."):
750cc398969Sdrh             ** Extend an existing memory allocation rather than creating
751cc398969Sdrh             ** a new one. */
752cc398969Sdrh             assert( (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
753cc398969Sdrh             pAccum->zText = bufpt;
754cc398969Sdrh             pAccum->nAlloc = sqlite3DbMallocSize(pAccum->db, bufpt);
755cc398969Sdrh             pAccum->nChar = 0x7fffffff & (int)strlen(bufpt);
756cc398969Sdrh             pAccum->printfFlags |= SQLITE_PRINTF_MALLOCED;
757cc398969Sdrh             length = 0;
758cc398969Sdrh             break;
759cc398969Sdrh           }
760d93d8a81Sdrh           zExtra = bufpt;
761d93d8a81Sdrh         }
762e509094bSdrh         if( precision>=0 ){
76362856465Sdrh           if( flag_altform2 ){
76462856465Sdrh             /* Set length to the number of bytes needed in order to display
76562856465Sdrh             ** precision characters */
76662856465Sdrh             unsigned char *z = (unsigned char*)bufpt;
76762856465Sdrh             while( precision-- > 0 && z[0] ){
76862856465Sdrh               SQLITE_SKIP_UTF8(z);
76962856465Sdrh             }
77062856465Sdrh             length = (int)(z - (unsigned char*)bufpt);
77162856465Sdrh           }else{
772e509094bSdrh             for(length=0; length<precision && bufpt[length]; length++){}
77362856465Sdrh           }
774e509094bSdrh         }else{
775c84ddf14Sdrh           length = 0x7fffffff & (int)strlen(bufpt);
776e509094bSdrh         }
77757e3ba76Sdrh       adjust_width_for_utf8:
77862856465Sdrh         if( flag_altform2 && width>0 ){
77962856465Sdrh           /* Adjust width to account for extra bytes in UTF-8 characters */
78062856465Sdrh           int ii = length - 1;
78162856465Sdrh           while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;
78262856465Sdrh         }
783a18c5681Sdrh         break;
78457e3ba76Sdrh       case etSQLESCAPE:           /* %q: Escape ' characters */
78557e3ba76Sdrh       case etSQLESCAPE2:          /* %Q: Escape ' and enclose in '...' */
78657e3ba76Sdrh       case etSQLESCAPE3: {        /* %w: Escape " characters */
7878965b50eSdrh         int i, j, k, n, isnull;
7884794f735Sdrh         int needQuote;
789ea678832Sdrh         char ch;
790f3b863edSdanielk1977         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
791a5c1416dSdrh         char *escarg;
792a5c1416dSdrh 
793a5c1416dSdrh         if( bArgList ){
794a5c1416dSdrh           escarg = getTextArg(pArgList);
795a5c1416dSdrh         }else{
796a5c1416dSdrh           escarg = va_arg(ap,char*);
797a5c1416dSdrh         }
798f0113000Sdanielk1977         isnull = escarg==0;
799f0113000Sdanielk1977         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
80057e3ba76Sdrh         /* For %q, %Q, and %w, the precision is the number of byte (or
80157e3ba76Sdrh         ** characters if the ! flags is present) to use from the input.
80257e3ba76Sdrh         ** Because of the extra quoting characters inserted, the number
80357e3ba76Sdrh         ** of output characters may be larger than the precision.
80457e3ba76Sdrh         */
8058965b50eSdrh         k = precision;
80660d4a304Sdan         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
807f3b863edSdanielk1977           if( ch==q )  n++;
80857e3ba76Sdrh           if( flag_altform2 && (ch&0xc0)==0xc0 ){
80957e3ba76Sdrh             while( (escarg[i+1]&0xc0)==0x80 ){ i++; }
81057e3ba76Sdrh           }
811a18c5681Sdrh         }
8124794f735Sdrh         needQuote = !isnull && xtype==etSQLESCAPE2;
8132a8f6712Sdrh         n += i + 3;
814a18c5681Sdrh         if( n>etBUFSIZE ){
81529642252Sdrh           bufpt = zExtra = printfTempBuf(pAccum, n);
81629642252Sdrh           if( bufpt==0 ) return;
817a18c5681Sdrh         }else{
818a18c5681Sdrh           bufpt = buf;
819a18c5681Sdrh         }
8200cfcf3fbSchw         j = 0;
821f3b863edSdanielk1977         if( needQuote ) bufpt[j++] = q;
8228965b50eSdrh         k = i;
8238965b50eSdrh         for(i=0; i<k; i++){
8248965b50eSdrh           bufpt[j++] = ch = escarg[i];
825f3b863edSdanielk1977           if( ch==q ) bufpt[j++] = ch;
826a18c5681Sdrh         }
827f3b863edSdanielk1977         if( needQuote ) bufpt[j++] = q;
828a18c5681Sdrh         bufpt[j] = 0;
829a18c5681Sdrh         length = j;
83057e3ba76Sdrh         goto adjust_width_for_utf8;
8315eba8c09Sdrh       }
8325f968436Sdrh       case etTOKEN: {
8338236f688Sdrh         Token *pToken;
8348236f688Sdrh         if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
8358236f688Sdrh         pToken = va_arg(ap, Token*);
836a5c1416dSdrh         assert( bArgList==0 );
837a9ab481fSdrh         if( pToken && pToken->n ){
8380cdbe1aeSdrh           sqlite3_str_append(pAccum, (const char*)pToken->z, pToken->n);
839ad6d9460Sdrh         }
8405f968436Sdrh         length = width = 0;
8415f968436Sdrh         break;
8425f968436Sdrh       }
8435f968436Sdrh       case etSRCLIST: {
8448236f688Sdrh         SrcList *pSrc;
8458236f688Sdrh         int k;
8468236f688Sdrh         struct SrcList_item *pItem;
8478236f688Sdrh         if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
8488236f688Sdrh         pSrc = va_arg(ap, SrcList*);
8498236f688Sdrh         k = va_arg(ap, int);
8508236f688Sdrh         pItem = &pSrc->a[k];
851a5c1416dSdrh         assert( bArgList==0 );
8525f968436Sdrh         assert( k>=0 && k<pSrc->nSrc );
85393a960a0Sdrh         if( pItem->zDatabase ){
8540cdbe1aeSdrh           sqlite3_str_appendall(pAccum, pItem->zDatabase);
8550cdbe1aeSdrh           sqlite3_str_append(pAccum, ".", 1);
8565f968436Sdrh         }
8570cdbe1aeSdrh         sqlite3_str_appendall(pAccum, pItem->zName);
8585f968436Sdrh         length = width = 0;
8595f968436Sdrh         break;
8605f968436Sdrh       }
861874ba04cSdrh       default: {
862874ba04cSdrh         assert( xtype==etINVALID );
863874ba04cSdrh         return;
864874ba04cSdrh       }
865a18c5681Sdrh     }/* End switch over the format type */
866a18c5681Sdrh     /*
867a18c5681Sdrh     ** The text of the conversion is pointed to by "bufpt" and is
868a18c5681Sdrh     ** "length" characters long.  The field width is "width".  Do
86962856465Sdrh     ** the output.  Both length and width are in bytes, not characters,
87062856465Sdrh     ** at this point.  If the "!" flag was present on string conversions
87162856465Sdrh     ** indicating that width and precision should be expressed in characters,
87262856465Sdrh     ** then the values have been translated prior to reaching this point.
873a18c5681Sdrh     */
874a70a073bSdrh     width -= length;
8758236f688Sdrh     if( width>0 ){
8760cdbe1aeSdrh       if( !flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
8770cdbe1aeSdrh       sqlite3_str_append(pAccum, bufpt, length);
8780cdbe1aeSdrh       if( flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
8798236f688Sdrh     }else{
8800cdbe1aeSdrh       sqlite3_str_append(pAccum, bufpt, length);
8818236f688Sdrh     }
882a70a073bSdrh 
883af8f513fSdrh     if( zExtra ){
88496ceaf86Sdrh       sqlite3DbFree(pAccum->db, zExtra);
885af8f513fSdrh       zExtra = 0;
886af8f513fSdrh     }
887a18c5681Sdrh   }/* End for loop over the format string */
888a18c5681Sdrh } /* End of function */
889a18c5681Sdrh 
890a18c5681Sdrh /*
891a70a073bSdrh ** Enlarge the memory allocation on a StrAccum object so that it is
892a70a073bSdrh ** able to accept at least N more bytes of text.
893a70a073bSdrh **
894a70a073bSdrh ** Return the number of bytes of text that StrAccum is able to accept
895a70a073bSdrh ** after the attempted enlargement.  The value returned might be zero.
896a18c5681Sdrh */
897a70a073bSdrh static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
898a6353a3fSdrh   char *zNew;
899a30d22a7Sdrh   assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
900b49bc86aSdrh   if( p->accError ){
9010cdbe1aeSdrh     testcase(p->accError==SQLITE_TOOBIG);
9020cdbe1aeSdrh     testcase(p->accError==SQLITE_NOMEM);
903a70a073bSdrh     return 0;
904ade86483Sdrh   }
905c0490572Sdrh   if( p->mxAlloc==0 ){
9060cdbe1aeSdrh     setStrAccumError(p, SQLITE_TOOBIG);
907255a81f1Sdrh     return p->nAlloc - p->nChar - 1;
908a18c5681Sdrh   }else{
9095f4a686fSdrh     char *zOld = isMalloced(p) ? p->zText : 0;
91093a960a0Sdrh     i64 szNew = p->nChar;
911b1a6c3c1Sdrh     szNew += N + 1;
9127b4d780bSdrh     if( szNew+p->nChar<=p->mxAlloc ){
9137b4d780bSdrh       /* Force exponential buffer size growth as long as it does not overflow,
9147b4d780bSdrh       ** to avoid having to call this routine too often */
9157b4d780bSdrh       szNew += p->nChar;
9167b4d780bSdrh     }
917b1a6c3c1Sdrh     if( szNew > p->mxAlloc ){
9180cdbe1aeSdrh       sqlite3_str_reset(p);
9190cdbe1aeSdrh       setStrAccumError(p, SQLITE_TOOBIG);
920a70a073bSdrh       return 0;
921b1a6c3c1Sdrh     }else{
922ea678832Sdrh       p->nAlloc = (int)szNew;
923a18c5681Sdrh     }
924c0490572Sdrh     if( p->db ){
925a9ef7097Sdan       zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
926b975598eSdrh     }else{
927f3cdcdccSdrh       zNew = sqlite3_realloc64(zOld, p->nAlloc);
928b975598eSdrh     }
92953f733c7Sdrh     if( zNew ){
9307ef4d1c4Sdrh       assert( p->zText!=0 || p->nChar==0 );
9315f4a686fSdrh       if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
932ade86483Sdrh       p->zText = zNew;
9337f5a7ecdSdrh       p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
9345f4a686fSdrh       p->printfFlags |= SQLITE_PRINTF_MALLOCED;
935ade86483Sdrh     }else{
9360cdbe1aeSdrh       sqlite3_str_reset(p);
9370cdbe1aeSdrh       setStrAccumError(p, SQLITE_NOMEM);
938a70a073bSdrh       return 0;
939a70a073bSdrh     }
940a70a073bSdrh   }
941a70a073bSdrh   return N;
942a70a073bSdrh }
943a70a073bSdrh 
944a70a073bSdrh /*
945af8f513fSdrh ** Append N copies of character c to the given string buffer.
946a70a073bSdrh */
9470cdbe1aeSdrh void sqlite3_str_appendchar(sqlite3_str *p, int N, char c){
948a30d22a7Sdrh   testcase( p->nChar + (i64)N > 0x7fffffff );
949a30d22a7Sdrh   if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
950a30d22a7Sdrh     return;
951a30d22a7Sdrh   }
952af8f513fSdrh   while( (N--)>0 ) p->zText[p->nChar++] = c;
953a70a073bSdrh }
954a70a073bSdrh 
955a70a073bSdrh /*
956a70a073bSdrh ** The StrAccum "p" is not large enough to accept N new bytes of z[].
957a70a073bSdrh ** So enlarge if first, then do the append.
958a70a073bSdrh **
9590cdbe1aeSdrh ** This is a helper routine to sqlite3_str_append() that does special-case
960a70a073bSdrh ** work (enlarging the buffer) using tail recursion, so that the
9610cdbe1aeSdrh ** sqlite3_str_append() routine can use fast calling semantics.
962a70a073bSdrh */
963172087fbSdrh static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
964a70a073bSdrh   N = sqlite3StrAccumEnlarge(p, N);
965a70a073bSdrh   if( N>0 ){
966a70a073bSdrh     memcpy(&p->zText[p->nChar], z, N);
967a70a073bSdrh     p->nChar += N;
968a70a073bSdrh   }
969a70a073bSdrh }
970a70a073bSdrh 
971a70a073bSdrh /*
972a70a073bSdrh ** Append N bytes of text from z to the StrAccum object.  Increase the
973a70a073bSdrh ** size of the memory allocation for StrAccum if necessary.
974a70a073bSdrh */
9750cdbe1aeSdrh void sqlite3_str_append(sqlite3_str *p, const char *z, int N){
9763457338cSdrh   assert( z!=0 || N==0 );
977a70a073bSdrh   assert( p->zText!=0 || p->nChar==0 || p->accError );
978a70a073bSdrh   assert( N>=0 );
979255a81f1Sdrh   assert( p->accError==0 || p->nAlloc==0 || p->mxAlloc==0 );
980a70a073bSdrh   if( p->nChar+N >= p->nAlloc ){
981a70a073bSdrh     enlargeAndAppend(p,z,N);
982895decf6Sdan   }else if( N ){
983b07028f7Sdrh     assert( p->zText );
984ade86483Sdrh     p->nChar += N;
985172087fbSdrh     memcpy(&p->zText[p->nChar-N], z, N);
986172087fbSdrh   }
987483750baSdrh }
988483750baSdrh 
989483750baSdrh /*
990a6353a3fSdrh ** Append the complete text of zero-terminated string z[] to the p string.
991a6353a3fSdrh */
9920cdbe1aeSdrh void sqlite3_str_appendall(sqlite3_str *p, const char *z){
9930cdbe1aeSdrh   sqlite3_str_append(p, z, sqlite3Strlen30(z));
994a6353a3fSdrh }
995a6353a3fSdrh 
996a6353a3fSdrh 
997a6353a3fSdrh /*
998ade86483Sdrh ** Finish off a string by making sure it is zero-terminated.
999ade86483Sdrh ** Return a pointer to the resulting string.  Return a NULL
1000ade86483Sdrh ** pointer if any kind of error was encountered.
10015f968436Sdrh */
1002043e586eSdrh static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
10033f18e6d7Sdrh   char *zText;
1004043e586eSdrh   assert( p->mxAlloc>0 && !isMalloced(p) );
10053f18e6d7Sdrh   zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
10063f18e6d7Sdrh   if( zText ){
10073f18e6d7Sdrh     memcpy(zText, p->zText, p->nChar+1);
10085f4a686fSdrh     p->printfFlags |= SQLITE_PRINTF_MALLOCED;
1009ade86483Sdrh   }else{
10100cdbe1aeSdrh     setStrAccumError(p, SQLITE_NOMEM);
1011ade86483Sdrh   }
10123f18e6d7Sdrh   p->zText = zText;
10133f18e6d7Sdrh   return zText;
1014043e586eSdrh }
1015043e586eSdrh char *sqlite3StrAccumFinish(StrAccum *p){
1016043e586eSdrh   if( p->zText ){
1017043e586eSdrh     p->zText[p->nChar] = 0;
1018043e586eSdrh     if( p->mxAlloc>0 && !isMalloced(p) ){
1019043e586eSdrh       return strAccumFinishRealloc(p);
1020ade86483Sdrh     }
1021ade86483Sdrh   }
1022ade86483Sdrh   return p->zText;
1023ade86483Sdrh }
1024ade86483Sdrh 
1025f80bba9dSdrh /*
1026f80bba9dSdrh ** This singleton is an sqlite3_str object that is returned if
1027f80bba9dSdrh ** sqlite3_malloc() fails to provide space for a real one.  This
1028f80bba9dSdrh ** sqlite3_str object accepts no new text and always returns
1029f80bba9dSdrh ** an SQLITE_NOMEM error.
1030f80bba9dSdrh */
1031f80bba9dSdrh static sqlite3_str sqlite3OomStr = {
10323e62ddbfSdrh    0, 0, 0, 0, 0, SQLITE_NOMEM, 0
1033f80bba9dSdrh };
1034f80bba9dSdrh 
10350cdbe1aeSdrh /* Finalize a string created using sqlite3_str_new().
10360cdbe1aeSdrh */
10370cdbe1aeSdrh char *sqlite3_str_finish(sqlite3_str *p){
10380cdbe1aeSdrh   char *z;
1039f80bba9dSdrh   if( p!=0 && p!=&sqlite3OomStr ){
10400cdbe1aeSdrh     z = sqlite3StrAccumFinish(p);
1041446135d7Sdrh     sqlite3_free(p);
10420cdbe1aeSdrh   }else{
10430cdbe1aeSdrh     z = 0;
10440cdbe1aeSdrh   }
10450cdbe1aeSdrh   return z;
10460cdbe1aeSdrh }
10470cdbe1aeSdrh 
10480cdbe1aeSdrh /* Return any error code associated with p */
10490cdbe1aeSdrh int sqlite3_str_errcode(sqlite3_str *p){
10500cdbe1aeSdrh   return p ? p->accError : SQLITE_NOMEM;
10510cdbe1aeSdrh }
10520cdbe1aeSdrh 
10530cdbe1aeSdrh /* Return the current length of p in bytes */
10540cdbe1aeSdrh int sqlite3_str_length(sqlite3_str *p){
10550cdbe1aeSdrh   return p ? p->nChar : 0;
10560cdbe1aeSdrh }
10570cdbe1aeSdrh 
10580cdbe1aeSdrh /* Return the current value for p */
10590cdbe1aeSdrh char *sqlite3_str_value(sqlite3_str *p){
1060446135d7Sdrh   if( p==0 || p->nChar==0 ) return 0;
1061446135d7Sdrh   p->zText[p->nChar] = 0;
1062446135d7Sdrh   return p->zText;
10630cdbe1aeSdrh }
10640cdbe1aeSdrh 
1065ade86483Sdrh /*
1066ade86483Sdrh ** Reset an StrAccum string.  Reclaim all malloced memory.
1067ade86483Sdrh */
10680cdbe1aeSdrh void sqlite3_str_reset(StrAccum *p){
10695f4a686fSdrh   if( isMalloced(p) ){
1070633e6d57Sdrh     sqlite3DbFree(p->db, p->zText);
10715f4a686fSdrh     p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
1072ade86483Sdrh   }
1073446135d7Sdrh   p->nAlloc = 0;
1074446135d7Sdrh   p->nChar = 0;
1075f089aa45Sdrh   p->zText = 0;
1076ade86483Sdrh }
1077ade86483Sdrh 
1078ade86483Sdrh /*
1079c0490572Sdrh ** Initialize a string accumulator.
1080c0490572Sdrh **
1081c0490572Sdrh ** p:     The accumulator to be initialized.
1082c0490572Sdrh ** db:    Pointer to a database connection.  May be NULL.  Lookaside
1083c0490572Sdrh **        memory is used if not NULL. db->mallocFailed is set appropriately
1084c0490572Sdrh **        when not NULL.
1085c0490572Sdrh ** zBase: An initial buffer.  May be NULL in which case the initial buffer
1086c0490572Sdrh **        is malloced.
1087c0490572Sdrh ** n:     Size of zBase in bytes.  If total space requirements never exceed
1088c0490572Sdrh **        n then no memory allocations ever occur.
1089c0490572Sdrh ** mx:    Maximum number of bytes to accumulate.  If mx==0 then no memory
1090c0490572Sdrh **        allocations will ever occur.
1091ade86483Sdrh */
1092c0490572Sdrh void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
10933f18e6d7Sdrh   p->zText = zBase;
1094c0490572Sdrh   p->db = db;
1095ade86483Sdrh   p->nAlloc = n;
1096bb4957f8Sdrh   p->mxAlloc = mx;
10973f18e6d7Sdrh   p->nChar = 0;
1098b49bc86aSdrh   p->accError = 0;
10995f4a686fSdrh   p->printfFlags = 0;
11005f968436Sdrh }
11015f968436Sdrh 
11020cdbe1aeSdrh /* Allocate and initialize a new dynamic string object */
11030cdbe1aeSdrh sqlite3_str *sqlite3_str_new(sqlite3 *db){
1104446135d7Sdrh   sqlite3_str *p = sqlite3_malloc64(sizeof(*p));
11050cdbe1aeSdrh   if( p ){
1106446135d7Sdrh     sqlite3StrAccumInit(p, 0, 0, 0,
1107446135d7Sdrh             db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
1108f80bba9dSdrh   }else{
1109f80bba9dSdrh     p = &sqlite3OomStr;
11100cdbe1aeSdrh   }
11110cdbe1aeSdrh   return p;
11120cdbe1aeSdrh }
11130cdbe1aeSdrh 
11145f968436Sdrh /*
11155f968436Sdrh ** Print into memory obtained from sqliteMalloc().  Use the internal
11165f968436Sdrh ** %-conversion extensions.
11175f968436Sdrh */
111817435752Sdrh char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
111917435752Sdrh   char *z;
112079158e18Sdrh   char zBase[SQLITE_PRINT_BUF_SIZE];
1121ade86483Sdrh   StrAccum acc;
1122bc6160b0Sdrh   assert( db!=0 );
1123c0490572Sdrh   sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
1124bc6160b0Sdrh                       db->aLimit[SQLITE_LIMIT_LENGTH]);
11255f4a686fSdrh   acc.printfFlags = SQLITE_PRINTF_INTERNAL;
11260cdbe1aeSdrh   sqlite3_str_vappendf(&acc, zFormat, ap);
1127ade86483Sdrh   z = sqlite3StrAccumFinish(&acc);
11280cdbe1aeSdrh   if( acc.accError==SQLITE_NOMEM ){
11294a642b60Sdrh     sqlite3OomFault(db);
113017435752Sdrh   }
113117435752Sdrh   return z;
11325f968436Sdrh }
11335f968436Sdrh 
11345f968436Sdrh /*
11355f968436Sdrh ** Print into memory obtained from sqliteMalloc().  Use the internal
11365f968436Sdrh ** %-conversion extensions.
11375f968436Sdrh */
113817435752Sdrh char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
11395f968436Sdrh   va_list ap;
11405f968436Sdrh   char *z;
11415f968436Sdrh   va_start(ap, zFormat);
1142ade86483Sdrh   z = sqlite3VMPrintf(db, zFormat, ap);
11435f968436Sdrh   va_end(ap);
11445f968436Sdrh   return z;
11455f968436Sdrh }
11465f968436Sdrh 
11475f968436Sdrh /*
114828dd479cSdrh ** Print into memory obtained from sqlite3_malloc().  Omit the internal
114928dd479cSdrh ** %-conversion extensions.
115028dd479cSdrh */
115128dd479cSdrh char *sqlite3_vmprintf(const char *zFormat, va_list ap){
1152ade86483Sdrh   char *z;
115328dd479cSdrh   char zBase[SQLITE_PRINT_BUF_SIZE];
1154ade86483Sdrh   StrAccum acc;
11559ca95730Sdrh 
11569ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
11579ca95730Sdrh   if( zFormat==0 ){
11589ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
11599ca95730Sdrh     return 0;
11609ca95730Sdrh   }
11619ca95730Sdrh #endif
1162ff1590eeSdrh #ifndef SQLITE_OMIT_AUTOINIT
1163ff1590eeSdrh   if( sqlite3_initialize() ) return 0;
1164ff1590eeSdrh #endif
1165c0490572Sdrh   sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
11660cdbe1aeSdrh   sqlite3_str_vappendf(&acc, zFormat, ap);
1167ade86483Sdrh   z = sqlite3StrAccumFinish(&acc);
1168ade86483Sdrh   return z;
116928dd479cSdrh }
117028dd479cSdrh 
117128dd479cSdrh /*
117228dd479cSdrh ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
117328dd479cSdrh ** %-conversion extensions.
1174483750baSdrh */
11756f8a503dSdanielk1977 char *sqlite3_mprintf(const char *zFormat, ...){
1176a18c5681Sdrh   va_list ap;
11775f968436Sdrh   char *z;
1178ff1590eeSdrh #ifndef SQLITE_OMIT_AUTOINIT
1179ff1590eeSdrh   if( sqlite3_initialize() ) return 0;
1180ff1590eeSdrh #endif
1181a18c5681Sdrh   va_start(ap, zFormat);
1182b3738b6cSdrh   z = sqlite3_vmprintf(zFormat, ap);
1183a18c5681Sdrh   va_end(ap);
11845f968436Sdrh   return z;
1185a18c5681Sdrh }
1186a18c5681Sdrh 
1187a18c5681Sdrh /*
11886f8a503dSdanielk1977 ** sqlite3_snprintf() works like snprintf() except that it ignores the
118993a5c6bdSdrh ** current locale settings.  This is important for SQLite because we
119093a5c6bdSdrh ** are not able to use a "," as the decimal point in place of "." as
119193a5c6bdSdrh ** specified by some locales.
1192db26d4c9Sdrh **
1193db26d4c9Sdrh ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
1194db26d4c9Sdrh ** from the snprintf() standard.  Unfortunately, it is too late to change
1195db26d4c9Sdrh ** this without breaking compatibility, so we just have to live with the
1196db26d4c9Sdrh ** mistake.
1197db26d4c9Sdrh **
1198db26d4c9Sdrh ** sqlite3_vsnprintf() is the varargs version.
119993a5c6bdSdrh */
1200db26d4c9Sdrh char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
1201db26d4c9Sdrh   StrAccum acc;
1202db26d4c9Sdrh   if( n<=0 ) return zBuf;
12039ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
12049ca95730Sdrh   if( zBuf==0 || zFormat==0 ) {
12059ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
120696c707a3Sdrh     if( zBuf ) zBuf[0] = 0;
12079ca95730Sdrh     return zBuf;
12089ca95730Sdrh   }
12099ca95730Sdrh #endif
1210c0490572Sdrh   sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
12110cdbe1aeSdrh   sqlite3_str_vappendf(&acc, zFormat, ap);
1212e9bb5660Sdrh   zBuf[acc.nChar] = 0;
1213e9bb5660Sdrh   return zBuf;
1214db26d4c9Sdrh }
12156f8a503dSdanielk1977 char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
12165f968436Sdrh   char *z;
121793a5c6bdSdrh   va_list ap;
121893a5c6bdSdrh   va_start(ap,zFormat);
1219db26d4c9Sdrh   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
122093a5c6bdSdrh   va_end(ap);
12215f968436Sdrh   return z;
122293a5c6bdSdrh }
122393a5c6bdSdrh 
12243f280701Sdrh /*
12257c0c460fSdrh ** This is the routine that actually formats the sqlite3_log() message.
12267c0c460fSdrh ** We house it in a separate routine from sqlite3_log() to avoid using
12277c0c460fSdrh ** stack space on small-stack systems when logging is disabled.
12287c0c460fSdrh **
12297c0c460fSdrh ** sqlite3_log() must render into a static buffer.  It cannot dynamically
12307c0c460fSdrh ** allocate memory because it might be called while the memory allocator
12317c0c460fSdrh ** mutex is held.
1232a8dbd52aSdrh **
12330cdbe1aeSdrh ** sqlite3_str_vappendf() might ask for *temporary* memory allocations for
1234a8dbd52aSdrh ** certain format characters (%q) or for very large precisions or widths.
1235a8dbd52aSdrh ** Care must be taken that any sqlite3_log() calls that occur while the
1236a8dbd52aSdrh ** memory mutex is held do not use these mechanisms.
12377c0c460fSdrh */
12387c0c460fSdrh static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
12397c0c460fSdrh   StrAccum acc;                          /* String accumulator */
1240a64fa912Sdrh   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
12417c0c460fSdrh 
1242c0490572Sdrh   sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
12430cdbe1aeSdrh   sqlite3_str_vappendf(&acc, zFormat, ap);
12447c0c460fSdrh   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
12457c0c460fSdrh                            sqlite3StrAccumFinish(&acc));
12467c0c460fSdrh }
12477c0c460fSdrh 
12487c0c460fSdrh /*
12493f280701Sdrh ** Format and write a message to the log if logging is enabled.
12503f280701Sdrh */
1251a7564663Sdrh void sqlite3_log(int iErrCode, const char *zFormat, ...){
12523f280701Sdrh   va_list ap;                             /* Vararg list */
12537c0c460fSdrh   if( sqlite3GlobalConfig.xLog ){
12543f280701Sdrh     va_start(ap, zFormat);
12557c0c460fSdrh     renderLogMsg(iErrCode, zFormat, ap);
12563f280701Sdrh     va_end(ap);
12573f280701Sdrh   }
12583f280701Sdrh }
12593f280701Sdrh 
126002b0e267Smistachkin #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
1261e54ca3feSdrh /*
1262e54ca3feSdrh ** A version of printf() that understands %lld.  Used for debugging.
1263e54ca3feSdrh ** The printf() built into some versions of windows does not understand %lld
1264e54ca3feSdrh ** and segfaults if you give it a long long int.
1265e54ca3feSdrh */
1266e54ca3feSdrh void sqlite3DebugPrintf(const char *zFormat, ...){
1267e54ca3feSdrh   va_list ap;
1268ade86483Sdrh   StrAccum acc;
1269*a8e41ecaSmistachkin   char zBuf[SQLITE_PRINT_BUF_SIZE*10];
1270c0490572Sdrh   sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
1271e54ca3feSdrh   va_start(ap,zFormat);
12720cdbe1aeSdrh   sqlite3_str_vappendf(&acc, zFormat, ap);
1273e54ca3feSdrh   va_end(ap);
1274bed8e7e5Sdrh   sqlite3StrAccumFinish(&acc);
12754a9ff918Smistachkin #ifdef SQLITE_OS_TRACE_PROC
12764a9ff918Smistachkin   {
12774a9ff918Smistachkin     extern void SQLITE_OS_TRACE_PROC(const char *zBuf, int nBuf);
12784a9ff918Smistachkin     SQLITE_OS_TRACE_PROC(zBuf, sizeof(zBuf));
12794a9ff918Smistachkin   }
12804a9ff918Smistachkin #else
1281485f0039Sdrh   fprintf(stdout,"%s", zBuf);
12822ac3ee97Sdrh   fflush(stdout);
12834a9ff918Smistachkin #endif
1284e54ca3feSdrh }
1285e54ca3feSdrh #endif
1286c7bc4fdeSdrh 
12874fa4a54fSdrh 
1288c7bc4fdeSdrh /*
12890cdbe1aeSdrh ** variable-argument wrapper around sqlite3_str_vappendf(). The bFlags argument
1290d37bea5bSdrh ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
1291c7bc4fdeSdrh */
12920cdbe1aeSdrh void sqlite3_str_appendf(StrAccum *p, const char *zFormat, ...){
1293c7bc4fdeSdrh   va_list ap;
1294c7bc4fdeSdrh   va_start(ap,zFormat);
12950cdbe1aeSdrh   sqlite3_str_vappendf(p, zFormat, ap);
1296c7bc4fdeSdrh   va_end(ap);
1297c7bc4fdeSdrh }
1298