xref: /sqlite-3.40.0/src/printf.c (revision bb05976d)
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 /*
198dd6c33d3Sdrh ** Hard limit on the precision of floating-point conversions.
199dd6c33d3Sdrh */
200dd6c33d3Sdrh #ifndef SQLITE_PRINTF_PRECISION_LIMIT
201dd6c33d3Sdrh # define SQLITE_FP_PRECISION_LIMIT 100000000
202dd6c33d3Sdrh #endif
203dd6c33d3Sdrh 
204dd6c33d3Sdrh /*
205ed1fddf4Sdrh ** Render a string given by "fmt" into the StrAccum object.
206a18c5681Sdrh */
2070cdbe1aeSdrh void sqlite3_str_vappendf(
2080cdbe1aeSdrh   sqlite3_str *pAccum,       /* Accumulate results here */
2095f968436Sdrh   const char *fmt,           /* Format string */
2105f968436Sdrh   va_list ap                 /* arguments */
211a18c5681Sdrh ){
212e84a306bSdrh   int c;                     /* Next character in the format string */
213e84a306bSdrh   char *bufpt;               /* Pointer to the conversion buffer */
214e84a306bSdrh   int precision;             /* Precision of the current field */
215e84a306bSdrh   int length;                /* Length of the field */
216e84a306bSdrh   int idx;                   /* A general purpose loop counter */
217a18c5681Sdrh   int width;                 /* Width of the current field */
218e84a306bSdrh   etByte flag_leftjustify;   /* True if "-" flag is present */
2192c338a9dSdrh   etByte flag_prefix;        /* '+' or ' ' or 0 for prefix */
220e84a306bSdrh   etByte flag_alternateform; /* True if "#" flag is present */
221531fe878Sdrh   etByte flag_altform2;      /* True if "!" flag is present */
222e84a306bSdrh   etByte flag_zeropad;       /* True if field width constant starts with zero */
2232c338a9dSdrh   etByte flag_long;          /* 1 for the "l" flag, 2 for "ll", 0 by default */
2243e9aeec0Sdrh   etByte done;               /* Loop termination flag */
2252c338a9dSdrh   etByte cThousand;          /* Thousands separator for %d and %u */
226ad5a9d71Sdrh   etByte xtype = etINVALID;  /* Conversion paradigm */
227a5c1416dSdrh   u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */
228ed1fddf4Sdrh   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
22927436af7Sdrh   sqlite_uint64 longvalue;   /* Value for integer types */
230384eef32Sdrh   LONGDOUBLE_TYPE realvalue; /* Value for real types */
2315719628aSdrh   const et_info *infop;      /* Pointer to the appropriate info structure */
23259eedf79Sdrh   char *zOut;                /* Rendering buffer */
23359eedf79Sdrh   int nOut;                  /* Size of the rendering buffer */
234af8f513fSdrh   char *zExtra = 0;          /* Malloced memory used by some conversion */
235b37df7b9Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
236557cc60fSdrh   int  exp, e2;              /* exponent of real numbers */
237ed1fddf4Sdrh   int nsd;                   /* Number of significant digits returned */
238a18c5681Sdrh   double rounder;            /* Used for rounding floating point values */
239e84a306bSdrh   etByte flag_dp;            /* True if decimal point should be shown */
240e84a306bSdrh   etByte flag_rtz;           /* True if trailing zeros should be removed */
241a18c5681Sdrh #endif
242a5c1416dSdrh   PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
243ed1fddf4Sdrh   char buf[etBUFSIZE];       /* Conversion buffer */
244a18c5681Sdrh 
245cc398969Sdrh   /* pAccum never starts out with an empty buffer that was obtained from
246cc398969Sdrh   ** malloc().  This precondition is required by the mprintf("%z...")
247cc398969Sdrh   ** optimization. */
248cc398969Sdrh   assert( pAccum->nChar>0 || (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
249cc398969Sdrh 
250a18c5681Sdrh   bufpt = 0;
2518236f688Sdrh   if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
252a5c1416dSdrh     pArgList = va_arg(ap, PrintfArguments*);
2538236f688Sdrh     bArgList = 1;
254a5c1416dSdrh   }else{
2558236f688Sdrh     bArgList = 0;
256a5c1416dSdrh   }
257a18c5681Sdrh   for(; (c=(*fmt))!=0; ++fmt){
258a18c5681Sdrh     if( c!='%' ){
259a18c5681Sdrh       bufpt = (char *)fmt;
260760b1598Sdrh #if HAVE_STRCHRNUL
261760b1598Sdrh       fmt = strchrnul(fmt, '%');
262760b1598Sdrh #else
263760b1598Sdrh       do{ fmt++; }while( *fmt && *fmt != '%' );
264760b1598Sdrh #endif
2650cdbe1aeSdrh       sqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt));
266760b1598Sdrh       if( *fmt==0 ) break;
267a18c5681Sdrh     }
268a18c5681Sdrh     if( (c=(*++fmt))==0 ){
2690cdbe1aeSdrh       sqlite3_str_append(pAccum, "%", 1);
270a18c5681Sdrh       break;
271a18c5681Sdrh     }
272a18c5681Sdrh     /* Find out what flags are present */
2732c338a9dSdrh     flag_leftjustify = flag_prefix = cThousand =
274557cc60fSdrh      flag_alternateform = flag_altform2 = flag_zeropad = 0;
2753e9aeec0Sdrh     done = 0;
2769a6d01bfSdrh     width = 0;
2779a6d01bfSdrh     flag_long = 0;
2789a6d01bfSdrh     precision = -1;
279a18c5681Sdrh     do{
280a18c5681Sdrh       switch( c ){
2813e9aeec0Sdrh         case '-':   flag_leftjustify = 1;     break;
2822c338a9dSdrh         case '+':   flag_prefix = '+';        break;
2832c338a9dSdrh         case ' ':   flag_prefix = ' ';        break;
2843e9aeec0Sdrh         case '#':   flag_alternateform = 1;   break;
2853e9aeec0Sdrh         case '!':   flag_altform2 = 1;        break;
2863e9aeec0Sdrh         case '0':   flag_zeropad = 1;         break;
2872c338a9dSdrh         case ',':   cThousand = ',';          break;
2883e9aeec0Sdrh         default:    done = 1;                 break;
2899a6d01bfSdrh         case 'l': {
2909a6d01bfSdrh           flag_long = 1;
2919a6d01bfSdrh           c = *++fmt;
2929a6d01bfSdrh           if( c=='l' ){
2939a6d01bfSdrh             c = *++fmt;
2949a6d01bfSdrh             flag_long = 2;
295a18c5681Sdrh           }
2969a6d01bfSdrh           done = 1;
2979a6d01bfSdrh           break;
2989a6d01bfSdrh         }
2999a6d01bfSdrh         case '1': case '2': case '3': case '4': case '5':
3009a6d01bfSdrh         case '6': case '7': case '8': case '9': {
3019a6d01bfSdrh           unsigned wx = c - '0';
3029a6d01bfSdrh           while( (c = *++fmt)>='0' && c<='9' ){
3039a6d01bfSdrh             wx = wx*10 + c - '0';
3049a6d01bfSdrh           }
3059a6d01bfSdrh           testcase( wx>0x7fffffff );
3069a6d01bfSdrh           width = wx & 0x7fffffff;
3079a6d01bfSdrh #ifdef SQLITE_PRINTF_PRECISION_LIMIT
3089a6d01bfSdrh           if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
3099a6d01bfSdrh             width = SQLITE_PRINTF_PRECISION_LIMIT;
3109a6d01bfSdrh           }
3119a6d01bfSdrh #endif
3129a6d01bfSdrh           if( c!='.' && c!='l' ){
3139a6d01bfSdrh             done = 1;
3149a6d01bfSdrh           }else{
3159a6d01bfSdrh             fmt--;
3169a6d01bfSdrh           }
3179a6d01bfSdrh           break;
3189a6d01bfSdrh         }
3199a6d01bfSdrh         case '*': {
320a5c1416dSdrh           if( bArgList ){
321a5c1416dSdrh             width = (int)getIntArg(pArgList);
322a5c1416dSdrh           }else{
323a18c5681Sdrh             width = va_arg(ap,int);
324a5c1416dSdrh           }
325a18c5681Sdrh           if( width<0 ){
326a18c5681Sdrh             flag_leftjustify = 1;
327b6f47debSdrh             width = width >= -2147483647 ? -width : 0;
328a18c5681Sdrh           }
329c386ef4fSdrh #ifdef SQLITE_PRINTF_PRECISION_LIMIT
330c386ef4fSdrh           if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
331c386ef4fSdrh             width = SQLITE_PRINTF_PRECISION_LIMIT;
332c386ef4fSdrh           }
333c386ef4fSdrh #endif
3349a6d01bfSdrh           if( (c = fmt[1])!='.' && c!='l' ){
3359a6d01bfSdrh             c = *++fmt;
3369a6d01bfSdrh             done = 1;
3379a6d01bfSdrh           }
3389a6d01bfSdrh           break;
3399a6d01bfSdrh         }
3409a6d01bfSdrh         case '.': {
341a18c5681Sdrh           c = *++fmt;
342a18c5681Sdrh           if( c=='*' ){
343a5c1416dSdrh             if( bArgList ){
344a5c1416dSdrh               precision = (int)getIntArg(pArgList);
345a5c1416dSdrh             }else{
346a18c5681Sdrh               precision = va_arg(ap,int);
347a5c1416dSdrh             }
348b6f47debSdrh             if( precision<0 ){
349b6f47debSdrh               precision = precision >= -2147483647 ? -precision : -1;
350b6f47debSdrh             }
3519a6d01bfSdrh             c = *++fmt;
352a18c5681Sdrh           }else{
353b6f47debSdrh             unsigned px = 0;
35417a68934Sdrh             while( c>='0' && c<='9' ){
355b6f47debSdrh               px = px*10 + c - '0';
356a18c5681Sdrh               c = *++fmt;
357a18c5681Sdrh             }
358b6f47debSdrh             testcase( px>0x7fffffff );
359b6f47debSdrh             precision = px & 0x7fffffff;
360a18c5681Sdrh           }
361c386ef4fSdrh #ifdef SQLITE_PRINTF_PRECISION_LIMIT
362c386ef4fSdrh           if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
363c386ef4fSdrh             precision = SQLITE_PRINTF_PRECISION_LIMIT;
364c386ef4fSdrh           }
365c386ef4fSdrh #endif
366a18c5681Sdrh           if( c=='l' ){
3679a6d01bfSdrh             --fmt;
368a34b6764Sdrh           }else{
3699a6d01bfSdrh             done = 1;
370a18c5681Sdrh           }
3719a6d01bfSdrh           break;
3729a6d01bfSdrh         }
3739a6d01bfSdrh       }
3749a6d01bfSdrh     }while( !done && (c=(*++fmt))!=0 );
3759a6d01bfSdrh 
376a18c5681Sdrh     /* Fetch the info entry for the field */
377874ba04cSdrh     infop = &fmtinfo[0];
378874ba04cSdrh     xtype = etINVALID;
37900e13613Sdanielk1977     for(idx=0; idx<ArraySize(fmtinfo); idx++){
380a18c5681Sdrh       if( c==fmtinfo[idx].fmttype ){
381a18c5681Sdrh         infop = &fmtinfo[idx];
382e84a306bSdrh         xtype = infop->type;
383a18c5681Sdrh         break;
384a18c5681Sdrh       }
385a18c5681Sdrh     }
38643617e9aSdrh 
387a18c5681Sdrh     /*
388a18c5681Sdrh     ** At this point, variables are initialized as follows:
389a18c5681Sdrh     **
390a18c5681Sdrh     **   flag_alternateform          TRUE if a '#' is present.
3913e9aeec0Sdrh     **   flag_altform2               TRUE if a '!' is present.
3922c338a9dSdrh     **   flag_prefix                 '+' or ' ' or zero
393a18c5681Sdrh     **   flag_leftjustify            TRUE if a '-' is present or if the
394a18c5681Sdrh     **                               field width was negative.
395a18c5681Sdrh     **   flag_zeropad                TRUE if the width began with 0.
3962c338a9dSdrh     **   flag_long                   1 for "l", 2 for "ll"
397a18c5681Sdrh     **   width                       The specified field width.  This is
398a18c5681Sdrh     **                               always non-negative.  Zero is the default.
399a18c5681Sdrh     **   precision                   The specified precision.  The default
400a18c5681Sdrh     **                               is -1.
401a18c5681Sdrh     **   xtype                       The class of the conversion.
402a18c5681Sdrh     **   infop                       Pointer to the appropriate info struct.
403a18c5681Sdrh     */
404b6907e29Sdrh     assert( width>=0 );
405b6907e29Sdrh     assert( precision>=(-1) );
406a18c5681Sdrh     switch( xtype ){
407fe63d1c9Sdrh       case etPOINTER:
4082c338a9dSdrh         flag_long = sizeof(char*)==sizeof(i64) ? 2 :
4092c338a9dSdrh                      sizeof(char*)==sizeof(long int) ? 1 : 0;
41008b92086Sdrh         /* no break */ deliberate_fall_through
4119a99334dSdrh       case etORDINAL:
412a18c5681Sdrh       case etRADIX:
4132c338a9dSdrh         cThousand = 0;
41408b92086Sdrh         /* no break */ deliberate_fall_through
4152c338a9dSdrh       case etDECIMAL:
416e84a306bSdrh         if( infop->flags & FLAG_SIGNED ){
417e9707671Sdrh           i64 v;
418a5c1416dSdrh           if( bArgList ){
419a5c1416dSdrh             v = getIntArg(pArgList);
420eeb23a4cSdrh           }else if( flag_long ){
4212c338a9dSdrh             if( flag_long==2 ){
4222c338a9dSdrh               v = va_arg(ap,i64) ;
4232c338a9dSdrh             }else{
424eeb23a4cSdrh               v = va_arg(ap,long int);
4252c338a9dSdrh             }
426eeb23a4cSdrh           }else{
427eeb23a4cSdrh             v = va_arg(ap,int);
428eeb23a4cSdrh           }
429e9707671Sdrh           if( v<0 ){
430e2678b93Sdrh             testcase( v==SMALLEST_INT64 );
431e2678b93Sdrh             testcase( v==(-1) );
432e2678b93Sdrh             longvalue = ~v;
433e2678b93Sdrh             longvalue++;
434cfcdaefeSdanielk1977             prefix = '-';
435cfcdaefeSdanielk1977           }else{
436e9707671Sdrh             longvalue = v;
4372c338a9dSdrh             prefix = flag_prefix;
438cfcdaefeSdanielk1977           }
439e9707671Sdrh         }else{
440a5c1416dSdrh           if( bArgList ){
441a5c1416dSdrh             longvalue = (u64)getIntArg(pArgList);
442eeb23a4cSdrh           }else if( flag_long ){
4432c338a9dSdrh             if( flag_long==2 ){
4442c338a9dSdrh               longvalue = va_arg(ap,u64);
4452c338a9dSdrh             }else{
446eeb23a4cSdrh               longvalue = va_arg(ap,unsigned long int);
4472c338a9dSdrh             }
448eeb23a4cSdrh           }else{
449eeb23a4cSdrh             longvalue = va_arg(ap,unsigned int);
450eeb23a4cSdrh           }
451e9707671Sdrh           prefix = 0;
452e9707671Sdrh         }
453e9707671Sdrh         if( longvalue==0 ) flag_alternateform = 0;
454a18c5681Sdrh         if( flag_zeropad && precision<width-(prefix!=0) ){
455a18c5681Sdrh           precision = width-(prefix!=0);
456a18c5681Sdrh         }
4572c338a9dSdrh         if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
45859eedf79Sdrh           nOut = etBUFSIZE;
45959eedf79Sdrh           zOut = buf;
46059eedf79Sdrh         }else{
4617ba03ea1Sdrh           u64 n;
4627ba03ea1Sdrh           n = (u64)precision + 10;
4637ba03ea1Sdrh           if( cThousand ) n += precision/3;
46429642252Sdrh           zOut = zExtra = printfTempBuf(pAccum, n);
46529642252Sdrh           if( zOut==0 ) return;
4665f42995aSdrh           nOut = (int)n;
46759eedf79Sdrh         }
46859eedf79Sdrh         bufpt = &zOut[nOut-1];
4699a99334dSdrh         if( xtype==etORDINAL ){
47043f6e064Sdrh           static const char zOrd[] = "thstndrd";
471ea678832Sdrh           int x = (int)(longvalue % 10);
47243f6e064Sdrh           if( x>=4 || (longvalue/10)%10==1 ){
47343f6e064Sdrh             x = 0;
47443f6e064Sdrh           }
47559eedf79Sdrh           *(--bufpt) = zOrd[x*2+1];
47659eedf79Sdrh           *(--bufpt) = zOrd[x*2];
4779a99334dSdrh         }
478a18c5681Sdrh         {
4790e682099Sdrh           const char *cset = &aDigits[infop->charset];
4800e682099Sdrh           u8 base = infop->base;
481a18c5681Sdrh           do{                                           /* Convert to ascii */
482a18c5681Sdrh             *(--bufpt) = cset[longvalue%base];
483a18c5681Sdrh             longvalue = longvalue/base;
484a18c5681Sdrh           }while( longvalue>0 );
485a18c5681Sdrh         }
48659eedf79Sdrh         length = (int)(&zOut[nOut-1]-bufpt);
4872c338a9dSdrh         while( precision>length ){
488a18c5681Sdrh           *(--bufpt) = '0';                             /* Zero pad */
4892c338a9dSdrh           length++;
4902c338a9dSdrh         }
4912c338a9dSdrh         if( cThousand ){
4922c338a9dSdrh           int nn = (length - 1)/3;  /* Number of "," to insert */
4932c338a9dSdrh           int ix = (length - 1)%3 + 1;
4942c338a9dSdrh           bufpt -= nn;
4952c338a9dSdrh           for(idx=0; nn>0; idx++){
4962c338a9dSdrh             bufpt[idx] = bufpt[idx+nn];
4972c338a9dSdrh             ix--;
4982c338a9dSdrh             if( ix==0 ){
4992c338a9dSdrh               bufpt[++idx] = cThousand;
5002c338a9dSdrh               nn--;
5012c338a9dSdrh               ix = 3;
5022c338a9dSdrh             }
5032c338a9dSdrh           }
504a18c5681Sdrh         }
505a18c5681Sdrh         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
506a18c5681Sdrh         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
50776ff3a0eSdrh           const char *pre;
50876ff3a0eSdrh           char x;
50976ff3a0eSdrh           pre = &aPrefix[infop->prefix];
51076ff3a0eSdrh           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
511a18c5681Sdrh         }
51259eedf79Sdrh         length = (int)(&zOut[nOut-1]-bufpt);
513a18c5681Sdrh         break;
514a18c5681Sdrh       case etFLOAT:
515a18c5681Sdrh       case etEXP:
516a18c5681Sdrh       case etGENERIC:
517a5c1416dSdrh         if( bArgList ){
518a5c1416dSdrh           realvalue = getDoubleArg(pArgList);
519a5c1416dSdrh         }else{
520a18c5681Sdrh           realvalue = va_arg(ap,double);
521a5c1416dSdrh         }
52269ef7036Sdrh #ifdef SQLITE_OMIT_FLOATING_POINT
52369ef7036Sdrh         length = 0;
52469ef7036Sdrh #else
525a18c5681Sdrh         if( precision<0 ) precision = 6;         /* Set default precision */
526dd6c33d3Sdrh #ifdef SQLITE_FP_PRECISION_LIMIT
527dd6c33d3Sdrh         if( precision>SQLITE_FP_PRECISION_LIMIT ){
528dd6c33d3Sdrh           precision = SQLITE_FP_PRECISION_LIMIT;
529dd6c33d3Sdrh         }
530dd6c33d3Sdrh #endif
531a18c5681Sdrh         if( realvalue<0.0 ){
532a18c5681Sdrh           realvalue = -realvalue;
533a18c5681Sdrh           prefix = '-';
534a18c5681Sdrh         }else{
5352c338a9dSdrh           prefix = flag_prefix;
536a18c5681Sdrh         }
5373e9aeec0Sdrh         if( xtype==etGENERIC && precision>0 ) precision--;
538a30d22a7Sdrh         testcase( precision>0xfff );
539a0ed86bcSdrh         idx = precision & 0xfff;
540a0ed86bcSdrh         rounder = arRound[idx%10];
541a0ed86bcSdrh         while( idx>=10 ){ rounder *= 1.0e-10; idx -= 10; }
542a0ed86bcSdrh         if( xtype==etFLOAT ){
543ef7d5187Sdrh           double rx = (double)realvalue;
544ef7d5187Sdrh           sqlite3_uint64 u;
545ef7d5187Sdrh           int ex;
546ef7d5187Sdrh           memcpy(&u, &rx, sizeof(u));
547ef7d5187Sdrh           ex = -1023 + (int)((u>>52)&0x7ff);
548ef7d5187Sdrh           if( precision+(ex/3) < 15 ) rounder += realvalue*3e-16;
549a0ed86bcSdrh           realvalue += rounder;
550a0ed86bcSdrh         }
551a18c5681Sdrh         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
552a18c5681Sdrh         exp = 0;
553ea678832Sdrh         if( sqlite3IsNaN((double)realvalue) ){
55453c14021Sdrh           bufpt = "NaN";
55553c14021Sdrh           length = 3;
55653c14021Sdrh           break;
55753c14021Sdrh         }
558a18c5681Sdrh         if( realvalue>0.0 ){
55972b3fbc7Sdrh           LONGDOUBLE_TYPE scale = 1.0;
5604ef94130Sdrh           while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
5612a8f6712Sdrh           while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
56272b3fbc7Sdrh           while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
56372b3fbc7Sdrh           realvalue /= scale;
564af005fbcSdrh           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
565af005fbcSdrh           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
566af005fbcSdrh           if( exp>350 ){
5672a8f6712Sdrh             bufpt = buf;
5682a8f6712Sdrh             buf[0] = prefix;
5692a8f6712Sdrh             memcpy(buf+(prefix!=0),"Inf",4);
5702a8f6712Sdrh             length = 3+(prefix!=0);
571a18c5681Sdrh             break;
572a18c5681Sdrh           }
573a18c5681Sdrh         }
574a18c5681Sdrh         bufpt = buf;
575a18c5681Sdrh         /*
576a18c5681Sdrh         ** If the field type is etGENERIC, then convert to either etEXP
577a18c5681Sdrh         ** or etFLOAT, as appropriate.
578a18c5681Sdrh         */
579a18c5681Sdrh         if( xtype!=etFLOAT ){
580a18c5681Sdrh           realvalue += rounder;
581a18c5681Sdrh           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
582a18c5681Sdrh         }
583a18c5681Sdrh         if( xtype==etGENERIC ){
584a18c5681Sdrh           flag_rtz = !flag_alternateform;
585a18c5681Sdrh           if( exp<-4 || exp>precision ){
586a18c5681Sdrh             xtype = etEXP;
587a18c5681Sdrh           }else{
588a18c5681Sdrh             precision = precision - exp;
589a18c5681Sdrh             xtype = etFLOAT;
590a18c5681Sdrh           }
591a18c5681Sdrh         }else{
59272b3fbc7Sdrh           flag_rtz = flag_altform2;
593a18c5681Sdrh         }
594557cc60fSdrh         if( xtype==etEXP ){
595557cc60fSdrh           e2 = 0;
596557cc60fSdrh         }else{
597557cc60fSdrh           e2 = exp;
598557cc60fSdrh         }
59929642252Sdrh         {
60029642252Sdrh           i64 szBufNeeded;           /* Size of a temporary buffer needed */
60129642252Sdrh           szBufNeeded = MAX(e2,0)+(i64)precision+(i64)width+15;
60229642252Sdrh           if( szBufNeeded > etBUFSIZE ){
60329642252Sdrh             bufpt = zExtra = printfTempBuf(pAccum, szBufNeeded);
60429642252Sdrh             if( bufpt==0 ) return;
60559eedf79Sdrh           }
60659eedf79Sdrh         }
60759eedf79Sdrh         zOut = bufpt;
60872b3fbc7Sdrh         nsd = 16 + flag_altform2*10;
609ea678832Sdrh         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
610557cc60fSdrh         /* The sign in front of the number */
611557cc60fSdrh         if( prefix ){
612557cc60fSdrh           *(bufpt++) = prefix;
613557cc60fSdrh         }
614557cc60fSdrh         /* Digits prior to the decimal point */
615557cc60fSdrh         if( e2<0 ){
616557cc60fSdrh           *(bufpt++) = '0';
617557cc60fSdrh         }else{
618557cc60fSdrh           for(; e2>=0; e2--){
619557cc60fSdrh             *(bufpt++) = et_getdigit(&realvalue,&nsd);
620557cc60fSdrh           }
621557cc60fSdrh         }
622557cc60fSdrh         /* The decimal point */
623557cc60fSdrh         if( flag_dp ){
624557cc60fSdrh           *(bufpt++) = '.';
625557cc60fSdrh         }
626557cc60fSdrh         /* "0" digits after the decimal point but before the first
627557cc60fSdrh         ** significant digit of the number */
628af005fbcSdrh         for(e2++; e2<0; precision--, e2++){
629af005fbcSdrh           assert( precision>0 );
630a18c5681Sdrh           *(bufpt++) = '0';
631a18c5681Sdrh         }
632557cc60fSdrh         /* Significant digits after the decimal point */
633557cc60fSdrh         while( (precision--)>0 ){
634557cc60fSdrh           *(bufpt++) = et_getdigit(&realvalue,&nsd);
635a18c5681Sdrh         }
636557cc60fSdrh         /* Remove trailing zeros and the "." if no digits follow the "." */
637557cc60fSdrh         if( flag_rtz && flag_dp ){
6383e9aeec0Sdrh           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
63959eedf79Sdrh           assert( bufpt>zOut );
6403e9aeec0Sdrh           if( bufpt[-1]=='.' ){
641557cc60fSdrh             if( flag_altform2 ){
642557cc60fSdrh               *(bufpt++) = '0';
643557cc60fSdrh             }else{
644557cc60fSdrh               *(--bufpt) = 0;
645a18c5681Sdrh             }
646557cc60fSdrh           }
647557cc60fSdrh         }
648557cc60fSdrh         /* Add the "eNNN" suffix */
64959eedf79Sdrh         if( xtype==etEXP ){
65076ff3a0eSdrh           *(bufpt++) = aDigits[infop->charset];
651557cc60fSdrh           if( exp<0 ){
652557cc60fSdrh             *(bufpt++) = '-'; exp = -exp;
653557cc60fSdrh           }else{
654557cc60fSdrh             *(bufpt++) = '+';
655557cc60fSdrh           }
656a18c5681Sdrh           if( exp>=100 ){
657ea678832Sdrh             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
658a18c5681Sdrh             exp %= 100;
659a18c5681Sdrh           }
660ea678832Sdrh           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
661ea678832Sdrh           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
662a18c5681Sdrh         }
663557cc60fSdrh         *bufpt = 0;
664557cc60fSdrh 
665a18c5681Sdrh         /* The converted number is in buf[] and zero terminated. Output it.
666a18c5681Sdrh         ** Note that the number is in the usual order, not reversed as with
667a18c5681Sdrh         ** integer conversions. */
66859eedf79Sdrh         length = (int)(bufpt-zOut);
66959eedf79Sdrh         bufpt = zOut;
670a18c5681Sdrh 
671a18c5681Sdrh         /* Special case:  Add leading zeros if the flag_zeropad flag is
672a18c5681Sdrh         ** set and we are not left justified */
673a18c5681Sdrh         if( flag_zeropad && !flag_leftjustify && length < width){
674a18c5681Sdrh           int i;
675a18c5681Sdrh           int nPad = width - length;
676a18c5681Sdrh           for(i=width; i>=nPad; i--){
677a18c5681Sdrh             bufpt[i] = bufpt[i-nPad];
678a18c5681Sdrh           }
679a18c5681Sdrh           i = prefix!=0;
680a18c5681Sdrh           while( nPad-- ) bufpt[i++] = '0';
681a18c5681Sdrh           length = width;
682a18c5681Sdrh         }
68369ef7036Sdrh #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
684a18c5681Sdrh         break;
685a18c5681Sdrh       case etSIZE:
686fc6ee9dfSdrh         if( !bArgList ){
687fc6ee9dfSdrh           *(va_arg(ap,int*)) = pAccum->nChar;
688fc6ee9dfSdrh         }
689a18c5681Sdrh         length = width = 0;
690a18c5681Sdrh         break;
691a18c5681Sdrh       case etPERCENT:
692a18c5681Sdrh         buf[0] = '%';
693a18c5681Sdrh         bufpt = buf;
694a18c5681Sdrh         length = 1;
695a18c5681Sdrh         break;
696a18c5681Sdrh       case etCHARX:
697a5c1416dSdrh         if( bArgList ){
698fc6ee9dfSdrh           bufpt = getTextArg(pArgList);
699a15a7c35Sdrh           length = 1;
700136102beSdrh           if( bufpt ){
701136102beSdrh             buf[0] = c = *(bufpt++);
702136102beSdrh             if( (c&0xc0)==0xc0 ){
703136102beSdrh               while( length<4 && (bufpt[0]&0xc0)==0x80 ){
704136102beSdrh                 buf[length++] = *(bufpt++);
705136102beSdrh               }
706136102beSdrh             }
707a15a7c35Sdrh           }else{
708a15a7c35Sdrh             buf[0] = 0;
709136102beSdrh           }
710a5c1416dSdrh         }else{
711136102beSdrh           unsigned int ch = va_arg(ap,unsigned int);
712136102beSdrh           if( ch<0x00080 ){
713136102beSdrh             buf[0] = ch & 0xff;
714136102beSdrh             length = 1;
715136102beSdrh           }else if( ch<0x00800 ){
716136102beSdrh             buf[0] = 0xc0 + (u8)((ch>>6)&0x1f);
717136102beSdrh             buf[1] = 0x80 + (u8)(ch & 0x3f);
718136102beSdrh             length = 2;
719136102beSdrh           }else if( ch<0x10000 ){
720136102beSdrh             buf[0] = 0xe0 + (u8)((ch>>12)&0x0f);
721136102beSdrh             buf[1] = 0x80 + (u8)((ch>>6) & 0x3f);
722136102beSdrh             buf[2] = 0x80 + (u8)(ch & 0x3f);
723136102beSdrh             length = 3;
724136102beSdrh           }else{
725136102beSdrh             buf[0] = 0xf0 + (u8)((ch>>18) & 0x07);
726136102beSdrh             buf[1] = 0x80 + (u8)((ch>>12) & 0x3f);
727136102beSdrh             buf[2] = 0x80 + (u8)((ch>>6) & 0x3f);
728136102beSdrh             buf[3] = 0x80 + (u8)(ch & 0x3f);
729136102beSdrh             length = 4;
730136102beSdrh           }
731a5c1416dSdrh         }
732af8f513fSdrh         if( precision>1 ){
733af8f513fSdrh           width -= precision-1;
734af8f513fSdrh           if( width>1 && !flag_leftjustify ){
7350cdbe1aeSdrh             sqlite3_str_appendchar(pAccum, width-1, ' ');
736af8f513fSdrh             width = 0;
737a18c5681Sdrh           }
738136102beSdrh           while( precision-- > 1 ){
7390cdbe1aeSdrh             sqlite3_str_append(pAccum, buf, length);
740af8f513fSdrh           }
741136102beSdrh         }
742a18c5681Sdrh         bufpt = buf;
743cf7c8370Sdrh         flag_altform2 = 1;
744cf7c8370Sdrh         goto adjust_width_for_utf8;
745a18c5681Sdrh       case etSTRING:
746d93d8a81Sdrh       case etDYNSTRING:
747a5c1416dSdrh         if( bArgList ){
748a5c1416dSdrh           bufpt = getTextArg(pArgList);
7492a8f6712Sdrh           xtype = etSTRING;
750a5c1416dSdrh         }else{
751cb485882Sdrh           bufpt = va_arg(ap,char*);
752a5c1416dSdrh         }
753d93d8a81Sdrh         if( bufpt==0 ){
754d93d8a81Sdrh           bufpt = "";
7552a8f6712Sdrh         }else if( xtype==etDYNSTRING ){
756af524a63Sdrh           if( pAccum->nChar==0
757af524a63Sdrh            && pAccum->mxAlloc
758af524a63Sdrh            && width==0
759af524a63Sdrh            && precision<0
760af524a63Sdrh            && pAccum->accError==0
761af524a63Sdrh           ){
762cc398969Sdrh             /* Special optimization for sqlite3_mprintf("%z..."):
763cc398969Sdrh             ** Extend an existing memory allocation rather than creating
764cc398969Sdrh             ** a new one. */
765cc398969Sdrh             assert( (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
766cc398969Sdrh             pAccum->zText = bufpt;
767cc398969Sdrh             pAccum->nAlloc = sqlite3DbMallocSize(pAccum->db, bufpt);
768cc398969Sdrh             pAccum->nChar = 0x7fffffff & (int)strlen(bufpt);
769cc398969Sdrh             pAccum->printfFlags |= SQLITE_PRINTF_MALLOCED;
770cc398969Sdrh             length = 0;
771cc398969Sdrh             break;
772cc398969Sdrh           }
773d93d8a81Sdrh           zExtra = bufpt;
774d93d8a81Sdrh         }
775e509094bSdrh         if( precision>=0 ){
77662856465Sdrh           if( flag_altform2 ){
77762856465Sdrh             /* Set length to the number of bytes needed in order to display
77862856465Sdrh             ** precision characters */
77962856465Sdrh             unsigned char *z = (unsigned char*)bufpt;
78062856465Sdrh             while( precision-- > 0 && z[0] ){
78162856465Sdrh               SQLITE_SKIP_UTF8(z);
78262856465Sdrh             }
78362856465Sdrh             length = (int)(z - (unsigned char*)bufpt);
78462856465Sdrh           }else{
785e509094bSdrh             for(length=0; length<precision && bufpt[length]; length++){}
78662856465Sdrh           }
787e509094bSdrh         }else{
788c84ddf14Sdrh           length = 0x7fffffff & (int)strlen(bufpt);
789e509094bSdrh         }
79057e3ba76Sdrh       adjust_width_for_utf8:
79162856465Sdrh         if( flag_altform2 && width>0 ){
79262856465Sdrh           /* Adjust width to account for extra bytes in UTF-8 characters */
79362856465Sdrh           int ii = length - 1;
79462856465Sdrh           while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;
79562856465Sdrh         }
796a18c5681Sdrh         break;
79757e3ba76Sdrh       case etSQLESCAPE:           /* %q: Escape ' characters */
79857e3ba76Sdrh       case etSQLESCAPE2:          /* %Q: Escape ' and enclose in '...' */
79957e3ba76Sdrh       case etSQLESCAPE3: {        /* %w: Escape " characters */
8008965b50eSdrh         int i, j, k, n, isnull;
8014794f735Sdrh         int needQuote;
802ea678832Sdrh         char ch;
803f3b863edSdanielk1977         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
804a5c1416dSdrh         char *escarg;
805a5c1416dSdrh 
806a5c1416dSdrh         if( bArgList ){
807a5c1416dSdrh           escarg = getTextArg(pArgList);
808a5c1416dSdrh         }else{
809a5c1416dSdrh           escarg = va_arg(ap,char*);
810a5c1416dSdrh         }
811f0113000Sdanielk1977         isnull = escarg==0;
812f0113000Sdanielk1977         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
813b6907e29Sdrh         /* For %q, %Q, and %w, the precision is the number of bytes (or
81457e3ba76Sdrh         ** characters if the ! flags is present) to use from the input.
81557e3ba76Sdrh         ** Because of the extra quoting characters inserted, the number
81657e3ba76Sdrh         ** of output characters may be larger than the precision.
81757e3ba76Sdrh         */
8188965b50eSdrh         k = precision;
81960d4a304Sdan         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
820f3b863edSdanielk1977           if( ch==q )  n++;
82157e3ba76Sdrh           if( flag_altform2 && (ch&0xc0)==0xc0 ){
82257e3ba76Sdrh             while( (escarg[i+1]&0xc0)==0x80 ){ i++; }
82357e3ba76Sdrh           }
824a18c5681Sdrh         }
8254794f735Sdrh         needQuote = !isnull && xtype==etSQLESCAPE2;
8262a8f6712Sdrh         n += i + 3;
827a18c5681Sdrh         if( n>etBUFSIZE ){
82829642252Sdrh           bufpt = zExtra = printfTempBuf(pAccum, n);
82929642252Sdrh           if( bufpt==0 ) return;
830a18c5681Sdrh         }else{
831a18c5681Sdrh           bufpt = buf;
832a18c5681Sdrh         }
8330cfcf3fbSchw         j = 0;
834f3b863edSdanielk1977         if( needQuote ) bufpt[j++] = q;
8358965b50eSdrh         k = i;
8368965b50eSdrh         for(i=0; i<k; i++){
8378965b50eSdrh           bufpt[j++] = ch = escarg[i];
838f3b863edSdanielk1977           if( ch==q ) bufpt[j++] = ch;
839a18c5681Sdrh         }
840f3b863edSdanielk1977         if( needQuote ) bufpt[j++] = q;
841a18c5681Sdrh         bufpt[j] = 0;
842a18c5681Sdrh         length = j;
84357e3ba76Sdrh         goto adjust_width_for_utf8;
8445eba8c09Sdrh       }
8455f968436Sdrh       case etTOKEN: {
8468236f688Sdrh         Token *pToken;
8478236f688Sdrh         if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
8488236f688Sdrh         pToken = va_arg(ap, Token*);
849a5c1416dSdrh         assert( bArgList==0 );
850a9ab481fSdrh         if( pToken && pToken->n ){
8510cdbe1aeSdrh           sqlite3_str_append(pAccum, (const char*)pToken->z, pToken->n);
852ad6d9460Sdrh         }
8535f968436Sdrh         length = width = 0;
8545f968436Sdrh         break;
8555f968436Sdrh       }
8565f968436Sdrh       case etSRCLIST: {
8578236f688Sdrh         SrcList *pSrc;
8588236f688Sdrh         int k;
8597601294aSdrh         SrcItem *pItem;
8608236f688Sdrh         if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
8618236f688Sdrh         pSrc = va_arg(ap, SrcList*);
8628236f688Sdrh         k = va_arg(ap, int);
8638236f688Sdrh         pItem = &pSrc->a[k];
864a5c1416dSdrh         assert( bArgList==0 );
8655f968436Sdrh         assert( k>=0 && k<pSrc->nSrc );
86693a960a0Sdrh         if( pItem->zDatabase ){
8670cdbe1aeSdrh           sqlite3_str_appendall(pAccum, pItem->zDatabase);
8680cdbe1aeSdrh           sqlite3_str_append(pAccum, ".", 1);
8695f968436Sdrh         }
8700cdbe1aeSdrh         sqlite3_str_appendall(pAccum, pItem->zName);
8715f968436Sdrh         length = width = 0;
8725f968436Sdrh         break;
8735f968436Sdrh       }
874874ba04cSdrh       default: {
875874ba04cSdrh         assert( xtype==etINVALID );
876874ba04cSdrh         return;
877874ba04cSdrh       }
878a18c5681Sdrh     }/* End switch over the format type */
879a18c5681Sdrh     /*
880a18c5681Sdrh     ** The text of the conversion is pointed to by "bufpt" and is
881a18c5681Sdrh     ** "length" characters long.  The field width is "width".  Do
88262856465Sdrh     ** the output.  Both length and width are in bytes, not characters,
88362856465Sdrh     ** at this point.  If the "!" flag was present on string conversions
88462856465Sdrh     ** indicating that width and precision should be expressed in characters,
88562856465Sdrh     ** then the values have been translated prior to reaching this point.
886a18c5681Sdrh     */
887a70a073bSdrh     width -= length;
8888236f688Sdrh     if( width>0 ){
8890cdbe1aeSdrh       if( !flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
8900cdbe1aeSdrh       sqlite3_str_append(pAccum, bufpt, length);
8910cdbe1aeSdrh       if( flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
8928236f688Sdrh     }else{
8930cdbe1aeSdrh       sqlite3_str_append(pAccum, bufpt, length);
8948236f688Sdrh     }
895a70a073bSdrh 
896af8f513fSdrh     if( zExtra ){
89796ceaf86Sdrh       sqlite3DbFree(pAccum->db, zExtra);
898af8f513fSdrh       zExtra = 0;
899af8f513fSdrh     }
900a18c5681Sdrh   }/* End for loop over the format string */
901a18c5681Sdrh } /* End of function */
902a18c5681Sdrh 
903a18c5681Sdrh /*
904a70a073bSdrh ** Enlarge the memory allocation on a StrAccum object so that it is
905a70a073bSdrh ** able to accept at least N more bytes of text.
906a70a073bSdrh **
907a70a073bSdrh ** Return the number of bytes of text that StrAccum is able to accept
908a70a073bSdrh ** after the attempted enlargement.  The value returned might be zero.
909a18c5681Sdrh */
910a70a073bSdrh static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
911a6353a3fSdrh   char *zNew;
912a30d22a7Sdrh   assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
913b49bc86aSdrh   if( p->accError ){
9140cdbe1aeSdrh     testcase(p->accError==SQLITE_TOOBIG);
9150cdbe1aeSdrh     testcase(p->accError==SQLITE_NOMEM);
916a70a073bSdrh     return 0;
917ade86483Sdrh   }
918c0490572Sdrh   if( p->mxAlloc==0 ){
9190cdbe1aeSdrh     setStrAccumError(p, SQLITE_TOOBIG);
920255a81f1Sdrh     return p->nAlloc - p->nChar - 1;
921a18c5681Sdrh   }else{
9225f4a686fSdrh     char *zOld = isMalloced(p) ? p->zText : 0;
92393a960a0Sdrh     i64 szNew = p->nChar;
924*bb05976dSdrh     szNew += (sqlite3_int64)N + 1;
9257b4d780bSdrh     if( szNew+p->nChar<=p->mxAlloc ){
9267b4d780bSdrh       /* Force exponential buffer size growth as long as it does not overflow,
9277b4d780bSdrh       ** to avoid having to call this routine too often */
9287b4d780bSdrh       szNew += p->nChar;
9297b4d780bSdrh     }
930b1a6c3c1Sdrh     if( szNew > p->mxAlloc ){
9310cdbe1aeSdrh       sqlite3_str_reset(p);
9320cdbe1aeSdrh       setStrAccumError(p, SQLITE_TOOBIG);
933a70a073bSdrh       return 0;
934b1a6c3c1Sdrh     }else{
935ea678832Sdrh       p->nAlloc = (int)szNew;
936a18c5681Sdrh     }
937c0490572Sdrh     if( p->db ){
938a9ef7097Sdan       zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
939b975598eSdrh     }else{
940d924e7bcSdrh       zNew = sqlite3Realloc(zOld, p->nAlloc);
941b975598eSdrh     }
94253f733c7Sdrh     if( zNew ){
9437ef4d1c4Sdrh       assert( p->zText!=0 || p->nChar==0 );
9445f4a686fSdrh       if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
945ade86483Sdrh       p->zText = zNew;
9467f5a7ecdSdrh       p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
9475f4a686fSdrh       p->printfFlags |= SQLITE_PRINTF_MALLOCED;
948ade86483Sdrh     }else{
9490cdbe1aeSdrh       sqlite3_str_reset(p);
9500cdbe1aeSdrh       setStrAccumError(p, SQLITE_NOMEM);
951a70a073bSdrh       return 0;
952a70a073bSdrh     }
953a70a073bSdrh   }
954a70a073bSdrh   return N;
955a70a073bSdrh }
956a70a073bSdrh 
957a70a073bSdrh /*
958af8f513fSdrh ** Append N copies of character c to the given string buffer.
959a70a073bSdrh */
9600cdbe1aeSdrh void sqlite3_str_appendchar(sqlite3_str *p, int N, char c){
961a30d22a7Sdrh   testcase( p->nChar + (i64)N > 0x7fffffff );
962a30d22a7Sdrh   if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
963a30d22a7Sdrh     return;
964a30d22a7Sdrh   }
965af8f513fSdrh   while( (N--)>0 ) p->zText[p->nChar++] = c;
966a70a073bSdrh }
967a70a073bSdrh 
968a70a073bSdrh /*
969a70a073bSdrh ** The StrAccum "p" is not large enough to accept N new bytes of z[].
970a70a073bSdrh ** So enlarge if first, then do the append.
971a70a073bSdrh **
9720cdbe1aeSdrh ** This is a helper routine to sqlite3_str_append() that does special-case
973a70a073bSdrh ** work (enlarging the buffer) using tail recursion, so that the
9740cdbe1aeSdrh ** sqlite3_str_append() routine can use fast calling semantics.
975a70a073bSdrh */
976172087fbSdrh static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
977a70a073bSdrh   N = sqlite3StrAccumEnlarge(p, N);
978a70a073bSdrh   if( N>0 ){
979a70a073bSdrh     memcpy(&p->zText[p->nChar], z, N);
980a70a073bSdrh     p->nChar += N;
981a70a073bSdrh   }
982a70a073bSdrh }
983a70a073bSdrh 
984a70a073bSdrh /*
985a70a073bSdrh ** Append N bytes of text from z to the StrAccum object.  Increase the
986a70a073bSdrh ** size of the memory allocation for StrAccum if necessary.
987a70a073bSdrh */
9880cdbe1aeSdrh void sqlite3_str_append(sqlite3_str *p, const char *z, int N){
9893457338cSdrh   assert( z!=0 || N==0 );
990a70a073bSdrh   assert( p->zText!=0 || p->nChar==0 || p->accError );
991a70a073bSdrh   assert( N>=0 );
992255a81f1Sdrh   assert( p->accError==0 || p->nAlloc==0 || p->mxAlloc==0 );
993a70a073bSdrh   if( p->nChar+N >= p->nAlloc ){
994a70a073bSdrh     enlargeAndAppend(p,z,N);
995895decf6Sdan   }else if( N ){
996b07028f7Sdrh     assert( p->zText );
997ade86483Sdrh     p->nChar += N;
998172087fbSdrh     memcpy(&p->zText[p->nChar-N], z, N);
999172087fbSdrh   }
1000483750baSdrh }
1001483750baSdrh 
1002483750baSdrh /*
1003a6353a3fSdrh ** Append the complete text of zero-terminated string z[] to the p string.
1004a6353a3fSdrh */
10050cdbe1aeSdrh void sqlite3_str_appendall(sqlite3_str *p, const char *z){
10060cdbe1aeSdrh   sqlite3_str_append(p, z, sqlite3Strlen30(z));
1007a6353a3fSdrh }
1008a6353a3fSdrh 
1009a6353a3fSdrh 
1010a6353a3fSdrh /*
1011ade86483Sdrh ** Finish off a string by making sure it is zero-terminated.
1012ade86483Sdrh ** Return a pointer to the resulting string.  Return a NULL
1013ade86483Sdrh ** pointer if any kind of error was encountered.
10145f968436Sdrh */
1015043e586eSdrh static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
10163f18e6d7Sdrh   char *zText;
1017043e586eSdrh   assert( p->mxAlloc>0 && !isMalloced(p) );
10183f18e6d7Sdrh   zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
10193f18e6d7Sdrh   if( zText ){
10203f18e6d7Sdrh     memcpy(zText, p->zText, p->nChar+1);
10215f4a686fSdrh     p->printfFlags |= SQLITE_PRINTF_MALLOCED;
1022ade86483Sdrh   }else{
10230cdbe1aeSdrh     setStrAccumError(p, SQLITE_NOMEM);
1024ade86483Sdrh   }
10253f18e6d7Sdrh   p->zText = zText;
10263f18e6d7Sdrh   return zText;
1027043e586eSdrh }
1028043e586eSdrh char *sqlite3StrAccumFinish(StrAccum *p){
1029043e586eSdrh   if( p->zText ){
1030043e586eSdrh     p->zText[p->nChar] = 0;
1031043e586eSdrh     if( p->mxAlloc>0 && !isMalloced(p) ){
1032043e586eSdrh       return strAccumFinishRealloc(p);
1033ade86483Sdrh     }
1034ade86483Sdrh   }
1035ade86483Sdrh   return p->zText;
1036ade86483Sdrh }
1037ade86483Sdrh 
1038f80bba9dSdrh /*
1039f80bba9dSdrh ** This singleton is an sqlite3_str object that is returned if
1040f80bba9dSdrh ** sqlite3_malloc() fails to provide space for a real one.  This
1041f80bba9dSdrh ** sqlite3_str object accepts no new text and always returns
1042f80bba9dSdrh ** an SQLITE_NOMEM error.
1043f80bba9dSdrh */
1044f80bba9dSdrh static sqlite3_str sqlite3OomStr = {
10453e62ddbfSdrh    0, 0, 0, 0, 0, SQLITE_NOMEM, 0
1046f80bba9dSdrh };
1047f80bba9dSdrh 
10480cdbe1aeSdrh /* Finalize a string created using sqlite3_str_new().
10490cdbe1aeSdrh */
10500cdbe1aeSdrh char *sqlite3_str_finish(sqlite3_str *p){
10510cdbe1aeSdrh   char *z;
1052f80bba9dSdrh   if( p!=0 && p!=&sqlite3OomStr ){
10530cdbe1aeSdrh     z = sqlite3StrAccumFinish(p);
1054446135d7Sdrh     sqlite3_free(p);
10550cdbe1aeSdrh   }else{
10560cdbe1aeSdrh     z = 0;
10570cdbe1aeSdrh   }
10580cdbe1aeSdrh   return z;
10590cdbe1aeSdrh }
10600cdbe1aeSdrh 
10610cdbe1aeSdrh /* Return any error code associated with p */
10620cdbe1aeSdrh int sqlite3_str_errcode(sqlite3_str *p){
10630cdbe1aeSdrh   return p ? p->accError : SQLITE_NOMEM;
10640cdbe1aeSdrh }
10650cdbe1aeSdrh 
10660cdbe1aeSdrh /* Return the current length of p in bytes */
10670cdbe1aeSdrh int sqlite3_str_length(sqlite3_str *p){
10680cdbe1aeSdrh   return p ? p->nChar : 0;
10690cdbe1aeSdrh }
10700cdbe1aeSdrh 
10710cdbe1aeSdrh /* Return the current value for p */
10720cdbe1aeSdrh char *sqlite3_str_value(sqlite3_str *p){
1073446135d7Sdrh   if( p==0 || p->nChar==0 ) return 0;
1074446135d7Sdrh   p->zText[p->nChar] = 0;
1075446135d7Sdrh   return p->zText;
10760cdbe1aeSdrh }
10770cdbe1aeSdrh 
1078ade86483Sdrh /*
1079ade86483Sdrh ** Reset an StrAccum string.  Reclaim all malloced memory.
1080ade86483Sdrh */
10810cdbe1aeSdrh void sqlite3_str_reset(StrAccum *p){
10825f4a686fSdrh   if( isMalloced(p) ){
1083633e6d57Sdrh     sqlite3DbFree(p->db, p->zText);
10845f4a686fSdrh     p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
1085ade86483Sdrh   }
1086446135d7Sdrh   p->nAlloc = 0;
1087446135d7Sdrh   p->nChar = 0;
1088f089aa45Sdrh   p->zText = 0;
1089ade86483Sdrh }
1090ade86483Sdrh 
1091ade86483Sdrh /*
1092c0490572Sdrh ** Initialize a string accumulator.
1093c0490572Sdrh **
1094c0490572Sdrh ** p:     The accumulator to be initialized.
1095c0490572Sdrh ** db:    Pointer to a database connection.  May be NULL.  Lookaside
1096c0490572Sdrh **        memory is used if not NULL. db->mallocFailed is set appropriately
1097c0490572Sdrh **        when not NULL.
1098c0490572Sdrh ** zBase: An initial buffer.  May be NULL in which case the initial buffer
1099c0490572Sdrh **        is malloced.
1100c0490572Sdrh ** n:     Size of zBase in bytes.  If total space requirements never exceed
1101c0490572Sdrh **        n then no memory allocations ever occur.
1102c0490572Sdrh ** mx:    Maximum number of bytes to accumulate.  If mx==0 then no memory
1103c0490572Sdrh **        allocations will ever occur.
1104ade86483Sdrh */
1105c0490572Sdrh void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
11063f18e6d7Sdrh   p->zText = zBase;
1107c0490572Sdrh   p->db = db;
1108ade86483Sdrh   p->nAlloc = n;
1109bb4957f8Sdrh   p->mxAlloc = mx;
11103f18e6d7Sdrh   p->nChar = 0;
1111b49bc86aSdrh   p->accError = 0;
11125f4a686fSdrh   p->printfFlags = 0;
11135f968436Sdrh }
11145f968436Sdrh 
11150cdbe1aeSdrh /* Allocate and initialize a new dynamic string object */
11160cdbe1aeSdrh sqlite3_str *sqlite3_str_new(sqlite3 *db){
1117446135d7Sdrh   sqlite3_str *p = sqlite3_malloc64(sizeof(*p));
11180cdbe1aeSdrh   if( p ){
1119446135d7Sdrh     sqlite3StrAccumInit(p, 0, 0, 0,
1120446135d7Sdrh             db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
1121f80bba9dSdrh   }else{
1122f80bba9dSdrh     p = &sqlite3OomStr;
11230cdbe1aeSdrh   }
11240cdbe1aeSdrh   return p;
11250cdbe1aeSdrh }
11260cdbe1aeSdrh 
11275f968436Sdrh /*
11285f968436Sdrh ** Print into memory obtained from sqliteMalloc().  Use the internal
11295f968436Sdrh ** %-conversion extensions.
11305f968436Sdrh */
113117435752Sdrh char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
113217435752Sdrh   char *z;
113379158e18Sdrh   char zBase[SQLITE_PRINT_BUF_SIZE];
1134ade86483Sdrh   StrAccum acc;
1135bc6160b0Sdrh   assert( db!=0 );
1136c0490572Sdrh   sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
1137bc6160b0Sdrh                       db->aLimit[SQLITE_LIMIT_LENGTH]);
11385f4a686fSdrh   acc.printfFlags = SQLITE_PRINTF_INTERNAL;
11390cdbe1aeSdrh   sqlite3_str_vappendf(&acc, zFormat, ap);
1140ade86483Sdrh   z = sqlite3StrAccumFinish(&acc);
11410cdbe1aeSdrh   if( acc.accError==SQLITE_NOMEM ){
11424a642b60Sdrh     sqlite3OomFault(db);
114317435752Sdrh   }
114417435752Sdrh   return z;
11455f968436Sdrh }
11465f968436Sdrh 
11475f968436Sdrh /*
11485f968436Sdrh ** Print into memory obtained from sqliteMalloc().  Use the internal
11495f968436Sdrh ** %-conversion extensions.
11505f968436Sdrh */
115117435752Sdrh char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
11525f968436Sdrh   va_list ap;
11535f968436Sdrh   char *z;
11545f968436Sdrh   va_start(ap, zFormat);
1155ade86483Sdrh   z = sqlite3VMPrintf(db, zFormat, ap);
11565f968436Sdrh   va_end(ap);
11575f968436Sdrh   return z;
11585f968436Sdrh }
11595f968436Sdrh 
11605f968436Sdrh /*
116128dd479cSdrh ** Print into memory obtained from sqlite3_malloc().  Omit the internal
116228dd479cSdrh ** %-conversion extensions.
116328dd479cSdrh */
116428dd479cSdrh char *sqlite3_vmprintf(const char *zFormat, va_list ap){
1165ade86483Sdrh   char *z;
116628dd479cSdrh   char zBase[SQLITE_PRINT_BUF_SIZE];
1167ade86483Sdrh   StrAccum acc;
11689ca95730Sdrh 
11699ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
11709ca95730Sdrh   if( zFormat==0 ){
11719ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
11729ca95730Sdrh     return 0;
11739ca95730Sdrh   }
11749ca95730Sdrh #endif
1175ff1590eeSdrh #ifndef SQLITE_OMIT_AUTOINIT
1176ff1590eeSdrh   if( sqlite3_initialize() ) return 0;
1177ff1590eeSdrh #endif
1178c0490572Sdrh   sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
11790cdbe1aeSdrh   sqlite3_str_vappendf(&acc, zFormat, ap);
1180ade86483Sdrh   z = sqlite3StrAccumFinish(&acc);
1181ade86483Sdrh   return z;
118228dd479cSdrh }
118328dd479cSdrh 
118428dd479cSdrh /*
118528dd479cSdrh ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
118628dd479cSdrh ** %-conversion extensions.
1187483750baSdrh */
11886f8a503dSdanielk1977 char *sqlite3_mprintf(const char *zFormat, ...){
1189a18c5681Sdrh   va_list ap;
11905f968436Sdrh   char *z;
1191ff1590eeSdrh #ifndef SQLITE_OMIT_AUTOINIT
1192ff1590eeSdrh   if( sqlite3_initialize() ) return 0;
1193ff1590eeSdrh #endif
1194a18c5681Sdrh   va_start(ap, zFormat);
1195b3738b6cSdrh   z = sqlite3_vmprintf(zFormat, ap);
1196a18c5681Sdrh   va_end(ap);
11975f968436Sdrh   return z;
1198a18c5681Sdrh }
1199a18c5681Sdrh 
1200a18c5681Sdrh /*
12016f8a503dSdanielk1977 ** sqlite3_snprintf() works like snprintf() except that it ignores the
120293a5c6bdSdrh ** current locale settings.  This is important for SQLite because we
120393a5c6bdSdrh ** are not able to use a "," as the decimal point in place of "." as
120493a5c6bdSdrh ** specified by some locales.
1205db26d4c9Sdrh **
1206db26d4c9Sdrh ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
1207db26d4c9Sdrh ** from the snprintf() standard.  Unfortunately, it is too late to change
1208db26d4c9Sdrh ** this without breaking compatibility, so we just have to live with the
1209db26d4c9Sdrh ** mistake.
1210db26d4c9Sdrh **
1211db26d4c9Sdrh ** sqlite3_vsnprintf() is the varargs version.
121293a5c6bdSdrh */
1213db26d4c9Sdrh char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
1214db26d4c9Sdrh   StrAccum acc;
1215db26d4c9Sdrh   if( n<=0 ) return zBuf;
12169ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
12179ca95730Sdrh   if( zBuf==0 || zFormat==0 ) {
12189ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
121996c707a3Sdrh     if( zBuf ) zBuf[0] = 0;
12209ca95730Sdrh     return zBuf;
12219ca95730Sdrh   }
12229ca95730Sdrh #endif
1223c0490572Sdrh   sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
12240cdbe1aeSdrh   sqlite3_str_vappendf(&acc, zFormat, ap);
1225e9bb5660Sdrh   zBuf[acc.nChar] = 0;
1226e9bb5660Sdrh   return zBuf;
1227db26d4c9Sdrh }
12286f8a503dSdanielk1977 char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
12295f968436Sdrh   char *z;
123093a5c6bdSdrh   va_list ap;
123193a5c6bdSdrh   va_start(ap,zFormat);
1232db26d4c9Sdrh   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
123393a5c6bdSdrh   va_end(ap);
12345f968436Sdrh   return z;
123593a5c6bdSdrh }
123693a5c6bdSdrh 
12373f280701Sdrh /*
12387c0c460fSdrh ** This is the routine that actually formats the sqlite3_log() message.
12397c0c460fSdrh ** We house it in a separate routine from sqlite3_log() to avoid using
12407c0c460fSdrh ** stack space on small-stack systems when logging is disabled.
12417c0c460fSdrh **
12427c0c460fSdrh ** sqlite3_log() must render into a static buffer.  It cannot dynamically
12437c0c460fSdrh ** allocate memory because it might be called while the memory allocator
12447c0c460fSdrh ** mutex is held.
1245a8dbd52aSdrh **
12460cdbe1aeSdrh ** sqlite3_str_vappendf() might ask for *temporary* memory allocations for
1247a8dbd52aSdrh ** certain format characters (%q) or for very large precisions or widths.
1248a8dbd52aSdrh ** Care must be taken that any sqlite3_log() calls that occur while the
1249a8dbd52aSdrh ** memory mutex is held do not use these mechanisms.
12507c0c460fSdrh */
12517c0c460fSdrh static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
12527c0c460fSdrh   StrAccum acc;                          /* String accumulator */
1253a64fa912Sdrh   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
12547c0c460fSdrh 
1255c0490572Sdrh   sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
12560cdbe1aeSdrh   sqlite3_str_vappendf(&acc, zFormat, ap);
12577c0c460fSdrh   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
12587c0c460fSdrh                            sqlite3StrAccumFinish(&acc));
12597c0c460fSdrh }
12607c0c460fSdrh 
12617c0c460fSdrh /*
12623f280701Sdrh ** Format and write a message to the log if logging is enabled.
12633f280701Sdrh */
1264a7564663Sdrh void sqlite3_log(int iErrCode, const char *zFormat, ...){
12653f280701Sdrh   va_list ap;                             /* Vararg list */
12667c0c460fSdrh   if( sqlite3GlobalConfig.xLog ){
12673f280701Sdrh     va_start(ap, zFormat);
12687c0c460fSdrh     renderLogMsg(iErrCode, zFormat, ap);
12693f280701Sdrh     va_end(ap);
12703f280701Sdrh   }
12713f280701Sdrh }
12723f280701Sdrh 
127302b0e267Smistachkin #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
1274e54ca3feSdrh /*
1275e54ca3feSdrh ** A version of printf() that understands %lld.  Used for debugging.
1276e54ca3feSdrh ** The printf() built into some versions of windows does not understand %lld
1277e54ca3feSdrh ** and segfaults if you give it a long long int.
1278e54ca3feSdrh */
1279e54ca3feSdrh void sqlite3DebugPrintf(const char *zFormat, ...){
1280e54ca3feSdrh   va_list ap;
1281ade86483Sdrh   StrAccum acc;
1282a8e41ecaSmistachkin   char zBuf[SQLITE_PRINT_BUF_SIZE*10];
1283c0490572Sdrh   sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
1284e54ca3feSdrh   va_start(ap,zFormat);
12850cdbe1aeSdrh   sqlite3_str_vappendf(&acc, zFormat, ap);
1286e54ca3feSdrh   va_end(ap);
1287bed8e7e5Sdrh   sqlite3StrAccumFinish(&acc);
12884a9ff918Smistachkin #ifdef SQLITE_OS_TRACE_PROC
12894a9ff918Smistachkin   {
12904a9ff918Smistachkin     extern void SQLITE_OS_TRACE_PROC(const char *zBuf, int nBuf);
12914a9ff918Smistachkin     SQLITE_OS_TRACE_PROC(zBuf, sizeof(zBuf));
12924a9ff918Smistachkin   }
12934a9ff918Smistachkin #else
1294485f0039Sdrh   fprintf(stdout,"%s", zBuf);
12952ac3ee97Sdrh   fflush(stdout);
12964a9ff918Smistachkin #endif
1297e54ca3feSdrh }
1298e54ca3feSdrh #endif
1299c7bc4fdeSdrh 
13004fa4a54fSdrh 
1301c7bc4fdeSdrh /*
13020cdbe1aeSdrh ** variable-argument wrapper around sqlite3_str_vappendf(). The bFlags argument
1303d37bea5bSdrh ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
1304c7bc4fdeSdrh */
13050cdbe1aeSdrh void sqlite3_str_appendf(StrAccum *p, const char *zFormat, ...){
1306c7bc4fdeSdrh   va_list ap;
1307c7bc4fdeSdrh   va_start(ap,zFormat);
13080cdbe1aeSdrh   sqlite3_str_vappendf(p, zFormat, ap);
1309c7bc4fdeSdrh   va_end(ap);
1310c7bc4fdeSdrh }
1311