xref: /sqlite-3.40.0/src/printf.c (revision 077e17b5)
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 */
32a979993bSdrh #define etSRCITEM    12 /* a pointer to a SrcItem */
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 },
98a979993bSdrh   {  'S',  0, 0, etSRCITEM,    0,  0 },
998236f688Sdrh   {  'r', 10, 1, etORDINAL,    0,  0 },
100a18c5681Sdrh };
101a18c5681Sdrh 
102a979993bSdrh /* Notes:
103a979993bSdrh **
104a979993bSdrh **    %S    Takes a pointer to SrcItem.  Shows name or database.name
1052f2091b1Sdrh **    %!S   Like %S but prefer the zName over the zAlias
106a979993bSdrh */
107a979993bSdrh 
108a0ed86bcSdrh /* Floating point constants used for rounding */
109a0ed86bcSdrh static const double arRound[] = {
110a0ed86bcSdrh   5.0e-01, 5.0e-02, 5.0e-03, 5.0e-04, 5.0e-05,
111a0ed86bcSdrh   5.0e-06, 5.0e-07, 5.0e-08, 5.0e-09, 5.0e-10,
112a0ed86bcSdrh };
113a0ed86bcSdrh 
114a18c5681Sdrh /*
115b37df7b9Sdrh ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
116a18c5681Sdrh ** conversions will work.
117a18c5681Sdrh */
118b37df7b9Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
119a18c5681Sdrh /*
120a18c5681Sdrh ** "*val" is a double such that 0.1 <= *val < 10.0
121a18c5681Sdrh ** Return the ascii code for the leading digit of *val, then
122a18c5681Sdrh ** multiply "*val" by 10.0 to renormalize.
123a18c5681Sdrh **
124a18c5681Sdrh ** Example:
125a18c5681Sdrh **     input:     *val = 3.14159
126a18c5681Sdrh **     output:    *val = 1.4159    function return = '3'
127a18c5681Sdrh **
128a18c5681Sdrh ** The counter *cnt is incremented each time.  After counter exceeds
129a18c5681Sdrh ** 16 (the number of significant digits in a 64-bit float) '0' is
130a18c5681Sdrh ** always returned.
131a18c5681Sdrh */
et_getdigit(LONGDOUBLE_TYPE * val,int * cnt)132ea678832Sdrh static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
133a18c5681Sdrh   int digit;
134384eef32Sdrh   LONGDOUBLE_TYPE d;
13572b3fbc7Sdrh   if( (*cnt)<=0 ) return '0';
13672b3fbc7Sdrh   (*cnt)--;
137a18c5681Sdrh   digit = (int)*val;
138a18c5681Sdrh   d = digit;
139a18c5681Sdrh   digit += '0';
140a18c5681Sdrh   *val = (*val - d)*10.0;
141ea678832Sdrh   return (char)digit;
142a18c5681Sdrh }
143b37df7b9Sdrh #endif /* SQLITE_OMIT_FLOATING_POINT */
144a18c5681Sdrh 
14579158e18Sdrh /*
146a6353a3fSdrh ** Set the StrAccum object to an error mode.
147a6353a3fSdrh */
sqlite3StrAccumSetError(StrAccum * p,u8 eError)148f06db3e8Sdrh void sqlite3StrAccumSetError(StrAccum *p, u8 eError){
1490cdbe1aeSdrh   assert( eError==SQLITE_NOMEM || eError==SQLITE_TOOBIG );
150a6353a3fSdrh   p->accError = eError;
151255a81f1Sdrh   if( p->mxAlloc ) sqlite3_str_reset(p);
152c3dcdba3Sdrh   if( eError==SQLITE_TOOBIG ) sqlite3ErrorToParser(p->db, eError);
153a6353a3fSdrh }
154a6353a3fSdrh 
155a6353a3fSdrh /*
156a5c1416dSdrh ** Extra argument values from a PrintfArguments object
157a5c1416dSdrh */
getIntArg(PrintfArguments * p)158a5c1416dSdrh static sqlite3_int64 getIntArg(PrintfArguments *p){
159a5c1416dSdrh   if( p->nArg<=p->nUsed ) return 0;
160a5c1416dSdrh   return sqlite3_value_int64(p->apArg[p->nUsed++]);
161a5c1416dSdrh }
getDoubleArg(PrintfArguments * p)162a5c1416dSdrh static double getDoubleArg(PrintfArguments *p){
163a5c1416dSdrh   if( p->nArg<=p->nUsed ) return 0.0;
164a5c1416dSdrh   return sqlite3_value_double(p->apArg[p->nUsed++]);
165a5c1416dSdrh }
getTextArg(PrintfArguments * p)166a5c1416dSdrh static char *getTextArg(PrintfArguments *p){
167a5c1416dSdrh   if( p->nArg<=p->nUsed ) return 0;
168a5c1416dSdrh   return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
169a5c1416dSdrh }
170a5c1416dSdrh 
17129642252Sdrh /*
17229642252Sdrh ** Allocate memory for a temporary buffer needed for printf rendering.
17329642252Sdrh **
17429642252Sdrh ** If the requested size of the temp buffer is larger than the size
17529642252Sdrh ** of the output buffer in pAccum, then cause an SQLITE_TOOBIG error.
17629642252Sdrh ** Do the size check before the memory allocation to prevent rogue
17729642252Sdrh ** SQL from requesting large allocations using the precision or width
17829642252Sdrh ** field of the printf() function.
17929642252Sdrh */
printfTempBuf(sqlite3_str * pAccum,sqlite3_int64 n)18029642252Sdrh static char *printfTempBuf(sqlite3_str *pAccum, sqlite3_int64 n){
18129642252Sdrh   char *z;
182255a81f1Sdrh   if( pAccum->accError ) return 0;
18329642252Sdrh   if( n>pAccum->nAlloc && n>pAccum->mxAlloc ){
184f06db3e8Sdrh     sqlite3StrAccumSetError(pAccum, SQLITE_TOOBIG);
18529642252Sdrh     return 0;
18629642252Sdrh   }
18729642252Sdrh   z = sqlite3DbMallocRaw(pAccum->db, n);
18829642252Sdrh   if( z==0 ){
189f06db3e8Sdrh     sqlite3StrAccumSetError(pAccum, SQLITE_NOMEM);
19029642252Sdrh   }
19129642252Sdrh   return z;
19229642252Sdrh }
193a5c1416dSdrh 
194a5c1416dSdrh /*
19579158e18Sdrh ** On machines with a small stack size, you can redefine the
196ed1fddf4Sdrh ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
19779158e18Sdrh */
19879158e18Sdrh #ifndef SQLITE_PRINT_BUF_SIZE
19959eedf79Sdrh # define SQLITE_PRINT_BUF_SIZE 70
20050d654daSdrh #endif
20179158e18Sdrh #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
202a18c5681Sdrh 
203a18c5681Sdrh /*
204dd6c33d3Sdrh ** Hard limit on the precision of floating-point conversions.
205dd6c33d3Sdrh */
206dd6c33d3Sdrh #ifndef SQLITE_PRINTF_PRECISION_LIMIT
207dd6c33d3Sdrh # define SQLITE_FP_PRECISION_LIMIT 100000000
208dd6c33d3Sdrh #endif
209dd6c33d3Sdrh 
210dd6c33d3Sdrh /*
211ed1fddf4Sdrh ** Render a string given by "fmt" into the StrAccum object.
212a18c5681Sdrh */
sqlite3_str_vappendf(sqlite3_str * pAccum,const char * fmt,va_list ap)2130cdbe1aeSdrh void sqlite3_str_vappendf(
2140cdbe1aeSdrh   sqlite3_str *pAccum,       /* Accumulate results here */
2155f968436Sdrh   const char *fmt,           /* Format string */
2165f968436Sdrh   va_list ap                 /* arguments */
217a18c5681Sdrh ){
218e84a306bSdrh   int c;                     /* Next character in the format string */
219e84a306bSdrh   char *bufpt;               /* Pointer to the conversion buffer */
220e84a306bSdrh   int precision;             /* Precision of the current field */
221e84a306bSdrh   int length;                /* Length of the field */
222e84a306bSdrh   int idx;                   /* A general purpose loop counter */
223a18c5681Sdrh   int width;                 /* Width of the current field */
224e84a306bSdrh   etByte flag_leftjustify;   /* True if "-" flag is present */
2252c338a9dSdrh   etByte flag_prefix;        /* '+' or ' ' or 0 for prefix */
226e84a306bSdrh   etByte flag_alternateform; /* True if "#" flag is present */
227531fe878Sdrh   etByte flag_altform2;      /* True if "!" flag is present */
228e84a306bSdrh   etByte flag_zeropad;       /* True if field width constant starts with zero */
2292c338a9dSdrh   etByte flag_long;          /* 1 for the "l" flag, 2 for "ll", 0 by default */
2303e9aeec0Sdrh   etByte done;               /* Loop termination flag */
2312c338a9dSdrh   etByte cThousand;          /* Thousands separator for %d and %u */
232ad5a9d71Sdrh   etByte xtype = etINVALID;  /* Conversion paradigm */
233a5c1416dSdrh   u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */
234ed1fddf4Sdrh   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
23527436af7Sdrh   sqlite_uint64 longvalue;   /* Value for integer types */
236384eef32Sdrh   LONGDOUBLE_TYPE realvalue; /* Value for real types */
2375719628aSdrh   const et_info *infop;      /* Pointer to the appropriate info structure */
23859eedf79Sdrh   char *zOut;                /* Rendering buffer */
23959eedf79Sdrh   int nOut;                  /* Size of the rendering buffer */
240af8f513fSdrh   char *zExtra = 0;          /* Malloced memory used by some conversion */
241b37df7b9Sdrh #ifndef SQLITE_OMIT_FLOATING_POINT
242557cc60fSdrh   int  exp, e2;              /* exponent of real numbers */
243ed1fddf4Sdrh   int nsd;                   /* Number of significant digits returned */
244a18c5681Sdrh   double rounder;            /* Used for rounding floating point values */
245e84a306bSdrh   etByte flag_dp;            /* True if decimal point should be shown */
246e84a306bSdrh   etByte flag_rtz;           /* True if trailing zeros should be removed */
247a18c5681Sdrh #endif
248a5c1416dSdrh   PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
249ed1fddf4Sdrh   char buf[etBUFSIZE];       /* Conversion buffer */
250a18c5681Sdrh 
251cc398969Sdrh   /* pAccum never starts out with an empty buffer that was obtained from
252cc398969Sdrh   ** malloc().  This precondition is required by the mprintf("%z...")
253cc398969Sdrh   ** optimization. */
254cc398969Sdrh   assert( pAccum->nChar>0 || (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
255cc398969Sdrh 
256a18c5681Sdrh   bufpt = 0;
2578236f688Sdrh   if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
258a5c1416dSdrh     pArgList = va_arg(ap, PrintfArguments*);
2598236f688Sdrh     bArgList = 1;
260a5c1416dSdrh   }else{
2618236f688Sdrh     bArgList = 0;
262a5c1416dSdrh   }
263a18c5681Sdrh   for(; (c=(*fmt))!=0; ++fmt){
264a18c5681Sdrh     if( c!='%' ){
265a18c5681Sdrh       bufpt = (char *)fmt;
266760b1598Sdrh #if HAVE_STRCHRNUL
267760b1598Sdrh       fmt = strchrnul(fmt, '%');
268760b1598Sdrh #else
269760b1598Sdrh       do{ fmt++; }while( *fmt && *fmt != '%' );
270760b1598Sdrh #endif
2710cdbe1aeSdrh       sqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt));
272760b1598Sdrh       if( *fmt==0 ) break;
273a18c5681Sdrh     }
274a18c5681Sdrh     if( (c=(*++fmt))==0 ){
2750cdbe1aeSdrh       sqlite3_str_append(pAccum, "%", 1);
276a18c5681Sdrh       break;
277a18c5681Sdrh     }
278a18c5681Sdrh     /* Find out what flags are present */
2792c338a9dSdrh     flag_leftjustify = flag_prefix = cThousand =
280557cc60fSdrh      flag_alternateform = flag_altform2 = flag_zeropad = 0;
2813e9aeec0Sdrh     done = 0;
2829a6d01bfSdrh     width = 0;
2839a6d01bfSdrh     flag_long = 0;
2849a6d01bfSdrh     precision = -1;
285a18c5681Sdrh     do{
286a18c5681Sdrh       switch( c ){
2873e9aeec0Sdrh         case '-':   flag_leftjustify = 1;     break;
2882c338a9dSdrh         case '+':   flag_prefix = '+';        break;
2892c338a9dSdrh         case ' ':   flag_prefix = ' ';        break;
2903e9aeec0Sdrh         case '#':   flag_alternateform = 1;   break;
2913e9aeec0Sdrh         case '!':   flag_altform2 = 1;        break;
2923e9aeec0Sdrh         case '0':   flag_zeropad = 1;         break;
2932c338a9dSdrh         case ',':   cThousand = ',';          break;
2943e9aeec0Sdrh         default:    done = 1;                 break;
2959a6d01bfSdrh         case 'l': {
2969a6d01bfSdrh           flag_long = 1;
2979a6d01bfSdrh           c = *++fmt;
2989a6d01bfSdrh           if( c=='l' ){
2999a6d01bfSdrh             c = *++fmt;
3009a6d01bfSdrh             flag_long = 2;
301a18c5681Sdrh           }
3029a6d01bfSdrh           done = 1;
3039a6d01bfSdrh           break;
3049a6d01bfSdrh         }
3059a6d01bfSdrh         case '1': case '2': case '3': case '4': case '5':
3069a6d01bfSdrh         case '6': case '7': case '8': case '9': {
3079a6d01bfSdrh           unsigned wx = c - '0';
3089a6d01bfSdrh           while( (c = *++fmt)>='0' && c<='9' ){
3099a6d01bfSdrh             wx = wx*10 + c - '0';
3109a6d01bfSdrh           }
3119a6d01bfSdrh           testcase( wx>0x7fffffff );
3129a6d01bfSdrh           width = wx & 0x7fffffff;
3139a6d01bfSdrh #ifdef SQLITE_PRINTF_PRECISION_LIMIT
3149a6d01bfSdrh           if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
3159a6d01bfSdrh             width = SQLITE_PRINTF_PRECISION_LIMIT;
3169a6d01bfSdrh           }
3179a6d01bfSdrh #endif
3189a6d01bfSdrh           if( c!='.' && c!='l' ){
3199a6d01bfSdrh             done = 1;
3209a6d01bfSdrh           }else{
3219a6d01bfSdrh             fmt--;
3229a6d01bfSdrh           }
3239a6d01bfSdrh           break;
3249a6d01bfSdrh         }
3259a6d01bfSdrh         case '*': {
326a5c1416dSdrh           if( bArgList ){
327a5c1416dSdrh             width = (int)getIntArg(pArgList);
328a5c1416dSdrh           }else{
329a18c5681Sdrh             width = va_arg(ap,int);
330a5c1416dSdrh           }
331a18c5681Sdrh           if( width<0 ){
332a18c5681Sdrh             flag_leftjustify = 1;
333b6f47debSdrh             width = width >= -2147483647 ? -width : 0;
334a18c5681Sdrh           }
335c386ef4fSdrh #ifdef SQLITE_PRINTF_PRECISION_LIMIT
336c386ef4fSdrh           if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
337c386ef4fSdrh             width = SQLITE_PRINTF_PRECISION_LIMIT;
338c386ef4fSdrh           }
339c386ef4fSdrh #endif
3409a6d01bfSdrh           if( (c = fmt[1])!='.' && c!='l' ){
3419a6d01bfSdrh             c = *++fmt;
3429a6d01bfSdrh             done = 1;
3439a6d01bfSdrh           }
3449a6d01bfSdrh           break;
3459a6d01bfSdrh         }
3469a6d01bfSdrh         case '.': {
347a18c5681Sdrh           c = *++fmt;
348a18c5681Sdrh           if( c=='*' ){
349a5c1416dSdrh             if( bArgList ){
350a5c1416dSdrh               precision = (int)getIntArg(pArgList);
351a5c1416dSdrh             }else{
352a18c5681Sdrh               precision = va_arg(ap,int);
353a5c1416dSdrh             }
354b6f47debSdrh             if( precision<0 ){
355b6f47debSdrh               precision = precision >= -2147483647 ? -precision : -1;
356b6f47debSdrh             }
3579a6d01bfSdrh             c = *++fmt;
358a18c5681Sdrh           }else{
359b6f47debSdrh             unsigned px = 0;
36017a68934Sdrh             while( c>='0' && c<='9' ){
361b6f47debSdrh               px = px*10 + c - '0';
362a18c5681Sdrh               c = *++fmt;
363a18c5681Sdrh             }
364b6f47debSdrh             testcase( px>0x7fffffff );
365b6f47debSdrh             precision = px & 0x7fffffff;
366a18c5681Sdrh           }
367c386ef4fSdrh #ifdef SQLITE_PRINTF_PRECISION_LIMIT
368c386ef4fSdrh           if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
369c386ef4fSdrh             precision = SQLITE_PRINTF_PRECISION_LIMIT;
370c386ef4fSdrh           }
371c386ef4fSdrh #endif
372a18c5681Sdrh           if( c=='l' ){
3739a6d01bfSdrh             --fmt;
374a34b6764Sdrh           }else{
3759a6d01bfSdrh             done = 1;
376a18c5681Sdrh           }
3779a6d01bfSdrh           break;
3789a6d01bfSdrh         }
3799a6d01bfSdrh       }
3809a6d01bfSdrh     }while( !done && (c=(*++fmt))!=0 );
3819a6d01bfSdrh 
382a18c5681Sdrh     /* Fetch the info entry for the field */
383874ba04cSdrh     infop = &fmtinfo[0];
384874ba04cSdrh     xtype = etINVALID;
38500e13613Sdanielk1977     for(idx=0; idx<ArraySize(fmtinfo); idx++){
386a18c5681Sdrh       if( c==fmtinfo[idx].fmttype ){
387a18c5681Sdrh         infop = &fmtinfo[idx];
388e84a306bSdrh         xtype = infop->type;
389a18c5681Sdrh         break;
390a18c5681Sdrh       }
391a18c5681Sdrh     }
39243617e9aSdrh 
393a18c5681Sdrh     /*
394a18c5681Sdrh     ** At this point, variables are initialized as follows:
395a18c5681Sdrh     **
396a18c5681Sdrh     **   flag_alternateform          TRUE if a '#' is present.
3973e9aeec0Sdrh     **   flag_altform2               TRUE if a '!' is present.
3982c338a9dSdrh     **   flag_prefix                 '+' or ' ' or zero
399a18c5681Sdrh     **   flag_leftjustify            TRUE if a '-' is present or if the
400a18c5681Sdrh     **                               field width was negative.
401a18c5681Sdrh     **   flag_zeropad                TRUE if the width began with 0.
4022c338a9dSdrh     **   flag_long                   1 for "l", 2 for "ll"
403a18c5681Sdrh     **   width                       The specified field width.  This is
404a18c5681Sdrh     **                               always non-negative.  Zero is the default.
405a18c5681Sdrh     **   precision                   The specified precision.  The default
406a18c5681Sdrh     **                               is -1.
407a18c5681Sdrh     **   xtype                       The class of the conversion.
408a18c5681Sdrh     **   infop                       Pointer to the appropriate info struct.
409a18c5681Sdrh     */
410b6907e29Sdrh     assert( width>=0 );
411b6907e29Sdrh     assert( precision>=(-1) );
412a18c5681Sdrh     switch( xtype ){
413fe63d1c9Sdrh       case etPOINTER:
4142c338a9dSdrh         flag_long = sizeof(char*)==sizeof(i64) ? 2 :
4152c338a9dSdrh                      sizeof(char*)==sizeof(long int) ? 1 : 0;
41608b92086Sdrh         /* no break */ deliberate_fall_through
4179a99334dSdrh       case etORDINAL:
418a18c5681Sdrh       case etRADIX:
4192c338a9dSdrh         cThousand = 0;
42008b92086Sdrh         /* no break */ deliberate_fall_through
4212c338a9dSdrh       case etDECIMAL:
422e84a306bSdrh         if( infop->flags & FLAG_SIGNED ){
423e9707671Sdrh           i64 v;
424a5c1416dSdrh           if( bArgList ){
425a5c1416dSdrh             v = getIntArg(pArgList);
426eeb23a4cSdrh           }else if( flag_long ){
4272c338a9dSdrh             if( flag_long==2 ){
4282c338a9dSdrh               v = va_arg(ap,i64) ;
4292c338a9dSdrh             }else{
430eeb23a4cSdrh               v = va_arg(ap,long int);
4312c338a9dSdrh             }
432eeb23a4cSdrh           }else{
433eeb23a4cSdrh             v = va_arg(ap,int);
434eeb23a4cSdrh           }
435e9707671Sdrh           if( v<0 ){
436e2678b93Sdrh             testcase( v==SMALLEST_INT64 );
437e2678b93Sdrh             testcase( v==(-1) );
438e2678b93Sdrh             longvalue = ~v;
439e2678b93Sdrh             longvalue++;
440cfcdaefeSdanielk1977             prefix = '-';
441cfcdaefeSdanielk1977           }else{
442e9707671Sdrh             longvalue = v;
4432c338a9dSdrh             prefix = flag_prefix;
444cfcdaefeSdanielk1977           }
445e9707671Sdrh         }else{
446a5c1416dSdrh           if( bArgList ){
447a5c1416dSdrh             longvalue = (u64)getIntArg(pArgList);
448eeb23a4cSdrh           }else if( flag_long ){
4492c338a9dSdrh             if( flag_long==2 ){
4502c338a9dSdrh               longvalue = va_arg(ap,u64);
4512c338a9dSdrh             }else{
452eeb23a4cSdrh               longvalue = va_arg(ap,unsigned long int);
4532c338a9dSdrh             }
454eeb23a4cSdrh           }else{
455eeb23a4cSdrh             longvalue = va_arg(ap,unsigned int);
456eeb23a4cSdrh           }
457e9707671Sdrh           prefix = 0;
458e9707671Sdrh         }
459e9707671Sdrh         if( longvalue==0 ) flag_alternateform = 0;
460a18c5681Sdrh         if( flag_zeropad && precision<width-(prefix!=0) ){
461a18c5681Sdrh           precision = width-(prefix!=0);
462a18c5681Sdrh         }
4632c338a9dSdrh         if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
46459eedf79Sdrh           nOut = etBUFSIZE;
46559eedf79Sdrh           zOut = buf;
46659eedf79Sdrh         }else{
4677ba03ea1Sdrh           u64 n;
4687ba03ea1Sdrh           n = (u64)precision + 10;
4697ba03ea1Sdrh           if( cThousand ) n += precision/3;
47029642252Sdrh           zOut = zExtra = printfTempBuf(pAccum, n);
47129642252Sdrh           if( zOut==0 ) return;
4725f42995aSdrh           nOut = (int)n;
47359eedf79Sdrh         }
47459eedf79Sdrh         bufpt = &zOut[nOut-1];
4759a99334dSdrh         if( xtype==etORDINAL ){
47643f6e064Sdrh           static const char zOrd[] = "thstndrd";
477ea678832Sdrh           int x = (int)(longvalue % 10);
47843f6e064Sdrh           if( x>=4 || (longvalue/10)%10==1 ){
47943f6e064Sdrh             x = 0;
48043f6e064Sdrh           }
48159eedf79Sdrh           *(--bufpt) = zOrd[x*2+1];
48259eedf79Sdrh           *(--bufpt) = zOrd[x*2];
4839a99334dSdrh         }
484a18c5681Sdrh         {
4850e682099Sdrh           const char *cset = &aDigits[infop->charset];
4860e682099Sdrh           u8 base = infop->base;
487a18c5681Sdrh           do{                                           /* Convert to ascii */
488a18c5681Sdrh             *(--bufpt) = cset[longvalue%base];
489a18c5681Sdrh             longvalue = longvalue/base;
490a18c5681Sdrh           }while( longvalue>0 );
491a18c5681Sdrh         }
49259eedf79Sdrh         length = (int)(&zOut[nOut-1]-bufpt);
4932c338a9dSdrh         while( precision>length ){
494a18c5681Sdrh           *(--bufpt) = '0';                             /* Zero pad */
4952c338a9dSdrh           length++;
4962c338a9dSdrh         }
4972c338a9dSdrh         if( cThousand ){
4982c338a9dSdrh           int nn = (length - 1)/3;  /* Number of "," to insert */
4992c338a9dSdrh           int ix = (length - 1)%3 + 1;
5002c338a9dSdrh           bufpt -= nn;
5012c338a9dSdrh           for(idx=0; nn>0; idx++){
5022c338a9dSdrh             bufpt[idx] = bufpt[idx+nn];
5032c338a9dSdrh             ix--;
5042c338a9dSdrh             if( ix==0 ){
5052c338a9dSdrh               bufpt[++idx] = cThousand;
5062c338a9dSdrh               nn--;
5072c338a9dSdrh               ix = 3;
5082c338a9dSdrh             }
5092c338a9dSdrh           }
510a18c5681Sdrh         }
511a18c5681Sdrh         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
512a18c5681Sdrh         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
51376ff3a0eSdrh           const char *pre;
51476ff3a0eSdrh           char x;
51576ff3a0eSdrh           pre = &aPrefix[infop->prefix];
51676ff3a0eSdrh           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
517a18c5681Sdrh         }
51859eedf79Sdrh         length = (int)(&zOut[nOut-1]-bufpt);
519a18c5681Sdrh         break;
520a18c5681Sdrh       case etFLOAT:
521a18c5681Sdrh       case etEXP:
522a18c5681Sdrh       case etGENERIC:
523a5c1416dSdrh         if( bArgList ){
524a5c1416dSdrh           realvalue = getDoubleArg(pArgList);
525a5c1416dSdrh         }else{
526a18c5681Sdrh           realvalue = va_arg(ap,double);
527a5c1416dSdrh         }
52869ef7036Sdrh #ifdef SQLITE_OMIT_FLOATING_POINT
52969ef7036Sdrh         length = 0;
53069ef7036Sdrh #else
531a18c5681Sdrh         if( precision<0 ) precision = 6;         /* Set default precision */
532dd6c33d3Sdrh #ifdef SQLITE_FP_PRECISION_LIMIT
533dd6c33d3Sdrh         if( precision>SQLITE_FP_PRECISION_LIMIT ){
534dd6c33d3Sdrh           precision = SQLITE_FP_PRECISION_LIMIT;
535dd6c33d3Sdrh         }
536dd6c33d3Sdrh #endif
537a18c5681Sdrh         if( realvalue<0.0 ){
538a18c5681Sdrh           realvalue = -realvalue;
539a18c5681Sdrh           prefix = '-';
540a18c5681Sdrh         }else{
5412c338a9dSdrh           prefix = flag_prefix;
542a18c5681Sdrh         }
5433e9aeec0Sdrh         if( xtype==etGENERIC && precision>0 ) precision--;
544a30d22a7Sdrh         testcase( precision>0xfff );
545a0ed86bcSdrh         idx = precision & 0xfff;
546a0ed86bcSdrh         rounder = arRound[idx%10];
547a0ed86bcSdrh         while( idx>=10 ){ rounder *= 1.0e-10; idx -= 10; }
548a0ed86bcSdrh         if( xtype==etFLOAT ){
549ef7d5187Sdrh           double rx = (double)realvalue;
550ef7d5187Sdrh           sqlite3_uint64 u;
551ef7d5187Sdrh           int ex;
552ef7d5187Sdrh           memcpy(&u, &rx, sizeof(u));
553ef7d5187Sdrh           ex = -1023 + (int)((u>>52)&0x7ff);
554ef7d5187Sdrh           if( precision+(ex/3) < 15 ) rounder += realvalue*3e-16;
555a0ed86bcSdrh           realvalue += rounder;
556a0ed86bcSdrh         }
557a18c5681Sdrh         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
558a18c5681Sdrh         exp = 0;
559ea678832Sdrh         if( sqlite3IsNaN((double)realvalue) ){
56053c14021Sdrh           bufpt = "NaN";
56153c14021Sdrh           length = 3;
56253c14021Sdrh           break;
56353c14021Sdrh         }
564a18c5681Sdrh         if( realvalue>0.0 ){
56572b3fbc7Sdrh           LONGDOUBLE_TYPE scale = 1.0;
5664ef94130Sdrh           while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
5672a8f6712Sdrh           while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
56872b3fbc7Sdrh           while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
56972b3fbc7Sdrh           realvalue /= scale;
570af005fbcSdrh           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
571af005fbcSdrh           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
572af005fbcSdrh           if( exp>350 ){
5732a8f6712Sdrh             bufpt = buf;
5742a8f6712Sdrh             buf[0] = prefix;
5752a8f6712Sdrh             memcpy(buf+(prefix!=0),"Inf",4);
5762a8f6712Sdrh             length = 3+(prefix!=0);
577a18c5681Sdrh             break;
578a18c5681Sdrh           }
579a18c5681Sdrh         }
580a18c5681Sdrh         bufpt = buf;
581a18c5681Sdrh         /*
582a18c5681Sdrh         ** If the field type is etGENERIC, then convert to either etEXP
583a18c5681Sdrh         ** or etFLOAT, as appropriate.
584a18c5681Sdrh         */
585a18c5681Sdrh         if( xtype!=etFLOAT ){
586a18c5681Sdrh           realvalue += rounder;
587a18c5681Sdrh           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
588a18c5681Sdrh         }
589a18c5681Sdrh         if( xtype==etGENERIC ){
590a18c5681Sdrh           flag_rtz = !flag_alternateform;
591a18c5681Sdrh           if( exp<-4 || exp>precision ){
592a18c5681Sdrh             xtype = etEXP;
593a18c5681Sdrh           }else{
594a18c5681Sdrh             precision = precision - exp;
595a18c5681Sdrh             xtype = etFLOAT;
596a18c5681Sdrh           }
597a18c5681Sdrh         }else{
59872b3fbc7Sdrh           flag_rtz = flag_altform2;
599a18c5681Sdrh         }
600557cc60fSdrh         if( xtype==etEXP ){
601557cc60fSdrh           e2 = 0;
602557cc60fSdrh         }else{
603557cc60fSdrh           e2 = exp;
604557cc60fSdrh         }
60529642252Sdrh         {
60629642252Sdrh           i64 szBufNeeded;           /* Size of a temporary buffer needed */
60729642252Sdrh           szBufNeeded = MAX(e2,0)+(i64)precision+(i64)width+15;
60829642252Sdrh           if( szBufNeeded > etBUFSIZE ){
60929642252Sdrh             bufpt = zExtra = printfTempBuf(pAccum, szBufNeeded);
61029642252Sdrh             if( bufpt==0 ) return;
61159eedf79Sdrh           }
61259eedf79Sdrh         }
61359eedf79Sdrh         zOut = bufpt;
61472b3fbc7Sdrh         nsd = 16 + flag_altform2*10;
615ea678832Sdrh         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
616557cc60fSdrh         /* The sign in front of the number */
617557cc60fSdrh         if( prefix ){
618557cc60fSdrh           *(bufpt++) = prefix;
619557cc60fSdrh         }
620557cc60fSdrh         /* Digits prior to the decimal point */
621557cc60fSdrh         if( e2<0 ){
622557cc60fSdrh           *(bufpt++) = '0';
623557cc60fSdrh         }else{
624557cc60fSdrh           for(; e2>=0; e2--){
625557cc60fSdrh             *(bufpt++) = et_getdigit(&realvalue,&nsd);
626557cc60fSdrh           }
627557cc60fSdrh         }
628557cc60fSdrh         /* The decimal point */
629557cc60fSdrh         if( flag_dp ){
630557cc60fSdrh           *(bufpt++) = '.';
631557cc60fSdrh         }
632557cc60fSdrh         /* "0" digits after the decimal point but before the first
633557cc60fSdrh         ** significant digit of the number */
634af005fbcSdrh         for(e2++; e2<0; precision--, e2++){
635af005fbcSdrh           assert( precision>0 );
636a18c5681Sdrh           *(bufpt++) = '0';
637a18c5681Sdrh         }
638557cc60fSdrh         /* Significant digits after the decimal point */
639557cc60fSdrh         while( (precision--)>0 ){
640557cc60fSdrh           *(bufpt++) = et_getdigit(&realvalue,&nsd);
641a18c5681Sdrh         }
642557cc60fSdrh         /* Remove trailing zeros and the "." if no digits follow the "." */
643557cc60fSdrh         if( flag_rtz && flag_dp ){
6443e9aeec0Sdrh           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
64559eedf79Sdrh           assert( bufpt>zOut );
6463e9aeec0Sdrh           if( bufpt[-1]=='.' ){
647557cc60fSdrh             if( flag_altform2 ){
648557cc60fSdrh               *(bufpt++) = '0';
649557cc60fSdrh             }else{
650557cc60fSdrh               *(--bufpt) = 0;
651a18c5681Sdrh             }
652557cc60fSdrh           }
653557cc60fSdrh         }
654557cc60fSdrh         /* Add the "eNNN" suffix */
65559eedf79Sdrh         if( xtype==etEXP ){
65676ff3a0eSdrh           *(bufpt++) = aDigits[infop->charset];
657557cc60fSdrh           if( exp<0 ){
658557cc60fSdrh             *(bufpt++) = '-'; exp = -exp;
659557cc60fSdrh           }else{
660557cc60fSdrh             *(bufpt++) = '+';
661557cc60fSdrh           }
662a18c5681Sdrh           if( exp>=100 ){
663ea678832Sdrh             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
664a18c5681Sdrh             exp %= 100;
665a18c5681Sdrh           }
666ea678832Sdrh           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
667ea678832Sdrh           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
668a18c5681Sdrh         }
669557cc60fSdrh         *bufpt = 0;
670557cc60fSdrh 
671a18c5681Sdrh         /* The converted number is in buf[] and zero terminated. Output it.
672a18c5681Sdrh         ** Note that the number is in the usual order, not reversed as with
673a18c5681Sdrh         ** integer conversions. */
67459eedf79Sdrh         length = (int)(bufpt-zOut);
67559eedf79Sdrh         bufpt = zOut;
676a18c5681Sdrh 
677a18c5681Sdrh         /* Special case:  Add leading zeros if the flag_zeropad flag is
678a18c5681Sdrh         ** set and we are not left justified */
679a18c5681Sdrh         if( flag_zeropad && !flag_leftjustify && length < width){
680a18c5681Sdrh           int i;
681a18c5681Sdrh           int nPad = width - length;
682a18c5681Sdrh           for(i=width; i>=nPad; i--){
683a18c5681Sdrh             bufpt[i] = bufpt[i-nPad];
684a18c5681Sdrh           }
685a18c5681Sdrh           i = prefix!=0;
686a18c5681Sdrh           while( nPad-- ) bufpt[i++] = '0';
687a18c5681Sdrh           length = width;
688a18c5681Sdrh         }
68969ef7036Sdrh #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
690a18c5681Sdrh         break;
691a18c5681Sdrh       case etSIZE:
692fc6ee9dfSdrh         if( !bArgList ){
693fc6ee9dfSdrh           *(va_arg(ap,int*)) = pAccum->nChar;
694fc6ee9dfSdrh         }
695a18c5681Sdrh         length = width = 0;
696a18c5681Sdrh         break;
697a18c5681Sdrh       case etPERCENT:
698a18c5681Sdrh         buf[0] = '%';
699a18c5681Sdrh         bufpt = buf;
700a18c5681Sdrh         length = 1;
701a18c5681Sdrh         break;
702a18c5681Sdrh       case etCHARX:
703a5c1416dSdrh         if( bArgList ){
704fc6ee9dfSdrh           bufpt = getTextArg(pArgList);
705a15a7c35Sdrh           length = 1;
706136102beSdrh           if( bufpt ){
707136102beSdrh             buf[0] = c = *(bufpt++);
708136102beSdrh             if( (c&0xc0)==0xc0 ){
709136102beSdrh               while( length<4 && (bufpt[0]&0xc0)==0x80 ){
710136102beSdrh                 buf[length++] = *(bufpt++);
711136102beSdrh               }
712136102beSdrh             }
713a15a7c35Sdrh           }else{
714a15a7c35Sdrh             buf[0] = 0;
715136102beSdrh           }
716a5c1416dSdrh         }else{
717136102beSdrh           unsigned int ch = va_arg(ap,unsigned int);
718136102beSdrh           if( ch<0x00080 ){
719136102beSdrh             buf[0] = ch & 0xff;
720136102beSdrh             length = 1;
721136102beSdrh           }else if( ch<0x00800 ){
722136102beSdrh             buf[0] = 0xc0 + (u8)((ch>>6)&0x1f);
723136102beSdrh             buf[1] = 0x80 + (u8)(ch & 0x3f);
724136102beSdrh             length = 2;
725136102beSdrh           }else if( ch<0x10000 ){
726136102beSdrh             buf[0] = 0xe0 + (u8)((ch>>12)&0x0f);
727136102beSdrh             buf[1] = 0x80 + (u8)((ch>>6) & 0x3f);
728136102beSdrh             buf[2] = 0x80 + (u8)(ch & 0x3f);
729136102beSdrh             length = 3;
730136102beSdrh           }else{
731136102beSdrh             buf[0] = 0xf0 + (u8)((ch>>18) & 0x07);
732136102beSdrh             buf[1] = 0x80 + (u8)((ch>>12) & 0x3f);
733136102beSdrh             buf[2] = 0x80 + (u8)((ch>>6) & 0x3f);
734136102beSdrh             buf[3] = 0x80 + (u8)(ch & 0x3f);
735136102beSdrh             length = 4;
736136102beSdrh           }
737a5c1416dSdrh         }
738af8f513fSdrh         if( precision>1 ){
739af8f513fSdrh           width -= precision-1;
740af8f513fSdrh           if( width>1 && !flag_leftjustify ){
7410cdbe1aeSdrh             sqlite3_str_appendchar(pAccum, width-1, ' ');
742af8f513fSdrh             width = 0;
743a18c5681Sdrh           }
744136102beSdrh           while( precision-- > 1 ){
7450cdbe1aeSdrh             sqlite3_str_append(pAccum, buf, length);
746af8f513fSdrh           }
747136102beSdrh         }
748a18c5681Sdrh         bufpt = buf;
749cf7c8370Sdrh         flag_altform2 = 1;
750cf7c8370Sdrh         goto adjust_width_for_utf8;
751a18c5681Sdrh       case etSTRING:
752d93d8a81Sdrh       case etDYNSTRING:
753a5c1416dSdrh         if( bArgList ){
754a5c1416dSdrh           bufpt = getTextArg(pArgList);
7552a8f6712Sdrh           xtype = etSTRING;
756a5c1416dSdrh         }else{
757cb485882Sdrh           bufpt = va_arg(ap,char*);
758a5c1416dSdrh         }
759d93d8a81Sdrh         if( bufpt==0 ){
760d93d8a81Sdrh           bufpt = "";
7612a8f6712Sdrh         }else if( xtype==etDYNSTRING ){
762af524a63Sdrh           if( pAccum->nChar==0
763af524a63Sdrh            && pAccum->mxAlloc
764af524a63Sdrh            && width==0
765af524a63Sdrh            && precision<0
766af524a63Sdrh            && pAccum->accError==0
767af524a63Sdrh           ){
768cc398969Sdrh             /* Special optimization for sqlite3_mprintf("%z..."):
769cc398969Sdrh             ** Extend an existing memory allocation rather than creating
770cc398969Sdrh             ** a new one. */
771cc398969Sdrh             assert( (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
772cc398969Sdrh             pAccum->zText = bufpt;
773cc398969Sdrh             pAccum->nAlloc = sqlite3DbMallocSize(pAccum->db, bufpt);
774cc398969Sdrh             pAccum->nChar = 0x7fffffff & (int)strlen(bufpt);
775cc398969Sdrh             pAccum->printfFlags |= SQLITE_PRINTF_MALLOCED;
776cc398969Sdrh             length = 0;
777cc398969Sdrh             break;
778cc398969Sdrh           }
779d93d8a81Sdrh           zExtra = bufpt;
780d93d8a81Sdrh         }
781e509094bSdrh         if( precision>=0 ){
78262856465Sdrh           if( flag_altform2 ){
78362856465Sdrh             /* Set length to the number of bytes needed in order to display
78462856465Sdrh             ** precision characters */
78562856465Sdrh             unsigned char *z = (unsigned char*)bufpt;
78662856465Sdrh             while( precision-- > 0 && z[0] ){
78762856465Sdrh               SQLITE_SKIP_UTF8(z);
78862856465Sdrh             }
78962856465Sdrh             length = (int)(z - (unsigned char*)bufpt);
79062856465Sdrh           }else{
791e509094bSdrh             for(length=0; length<precision && bufpt[length]; length++){}
79262856465Sdrh           }
793e509094bSdrh         }else{
794c84ddf14Sdrh           length = 0x7fffffff & (int)strlen(bufpt);
795e509094bSdrh         }
79657e3ba76Sdrh       adjust_width_for_utf8:
79762856465Sdrh         if( flag_altform2 && width>0 ){
79862856465Sdrh           /* Adjust width to account for extra bytes in UTF-8 characters */
79962856465Sdrh           int ii = length - 1;
80062856465Sdrh           while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;
80162856465Sdrh         }
802a18c5681Sdrh         break;
80357e3ba76Sdrh       case etSQLESCAPE:           /* %q: Escape ' characters */
80457e3ba76Sdrh       case etSQLESCAPE2:          /* %Q: Escape ' and enclose in '...' */
80557e3ba76Sdrh       case etSQLESCAPE3: {        /* %w: Escape " characters */
806*077e17b5Sdrh         i64 i, j, k, n;
807*077e17b5Sdrh         int needQuote, isnull;
808ea678832Sdrh         char ch;
809f3b863edSdanielk1977         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
810a5c1416dSdrh         char *escarg;
811a5c1416dSdrh 
812a5c1416dSdrh         if( bArgList ){
813a5c1416dSdrh           escarg = getTextArg(pArgList);
814a5c1416dSdrh         }else{
815a5c1416dSdrh           escarg = va_arg(ap,char*);
816a5c1416dSdrh         }
817f0113000Sdanielk1977         isnull = escarg==0;
818f0113000Sdanielk1977         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
819b6907e29Sdrh         /* For %q, %Q, and %w, the precision is the number of bytes (or
82057e3ba76Sdrh         ** characters if the ! flags is present) to use from the input.
82157e3ba76Sdrh         ** Because of the extra quoting characters inserted, the number
82257e3ba76Sdrh         ** of output characters may be larger than the precision.
82357e3ba76Sdrh         */
8248965b50eSdrh         k = precision;
82560d4a304Sdan         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
826f3b863edSdanielk1977           if( ch==q )  n++;
82757e3ba76Sdrh           if( flag_altform2 && (ch&0xc0)==0xc0 ){
82857e3ba76Sdrh             while( (escarg[i+1]&0xc0)==0x80 ){ i++; }
82957e3ba76Sdrh           }
830a18c5681Sdrh         }
8314794f735Sdrh         needQuote = !isnull && xtype==etSQLESCAPE2;
8322a8f6712Sdrh         n += i + 3;
833a18c5681Sdrh         if( n>etBUFSIZE ){
83429642252Sdrh           bufpt = zExtra = printfTempBuf(pAccum, n);
83529642252Sdrh           if( bufpt==0 ) return;
836a18c5681Sdrh         }else{
837a18c5681Sdrh           bufpt = buf;
838a18c5681Sdrh         }
8390cfcf3fbSchw         j = 0;
840f3b863edSdanielk1977         if( needQuote ) bufpt[j++] = q;
8418965b50eSdrh         k = i;
8428965b50eSdrh         for(i=0; i<k; i++){
8438965b50eSdrh           bufpt[j++] = ch = escarg[i];
844f3b863edSdanielk1977           if( ch==q ) bufpt[j++] = ch;
845a18c5681Sdrh         }
846f3b863edSdanielk1977         if( needQuote ) bufpt[j++] = q;
847a18c5681Sdrh         bufpt[j] = 0;
848a18c5681Sdrh         length = j;
84957e3ba76Sdrh         goto adjust_width_for_utf8;
8505eba8c09Sdrh       }
8515f968436Sdrh       case etTOKEN: {
8528236f688Sdrh         if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
85362fc069eSdrh         if( flag_alternateform ){
85462fc069eSdrh           /* %#T means an Expr pointer that uses Expr.u.zToken */
85562fc069eSdrh           Expr *pExpr = va_arg(ap,Expr*);
8565d20a218Sdrh           if( ALWAYS(pExpr) && ALWAYS(!ExprHasProperty(pExpr,EP_IntValue)) ){
85762fc069eSdrh             sqlite3_str_appendall(pAccum, (const char*)pExpr->u.zToken);
85862fc069eSdrh             sqlite3RecordErrorOffsetOfExpr(pAccum->db, pExpr);
85962fc069eSdrh           }
86062fc069eSdrh         }else{
86162fc069eSdrh           /* %T means a Token pointer */
86262fc069eSdrh           Token *pToken = va_arg(ap, Token*);
863a5c1416dSdrh           assert( bArgList==0 );
864a9ab481fSdrh           if( pToken && pToken->n ){
8650cdbe1aeSdrh             sqlite3_str_append(pAccum, (const char*)pToken->z, pToken->n);
866f62641e9Sdrh             sqlite3RecordErrorByteOffset(pAccum->db, pToken->z);
867ad6d9460Sdrh           }
86862fc069eSdrh         }
8695f968436Sdrh         length = width = 0;
8705f968436Sdrh         break;
8715f968436Sdrh       }
872a979993bSdrh       case etSRCITEM: {
8737601294aSdrh         SrcItem *pItem;
8748236f688Sdrh         if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
875a979993bSdrh         pItem = va_arg(ap, SrcItem*);
876a5c1416dSdrh         assert( bArgList==0 );
8772f2091b1Sdrh         if( pItem->zAlias && !flag_altform2 ){
8788210233cSdrh           sqlite3_str_appendall(pAccum, pItem->zAlias);
8798210233cSdrh         }else if( pItem->zName ){
88093a960a0Sdrh           if( pItem->zDatabase ){
8810cdbe1aeSdrh             sqlite3_str_appendall(pAccum, pItem->zDatabase);
8820cdbe1aeSdrh             sqlite3_str_append(pAccum, ".", 1);
8835f968436Sdrh           }
8840cdbe1aeSdrh           sqlite3_str_appendall(pAccum, pItem->zName);
8852f2091b1Sdrh         }else if( pItem->zAlias ){
8862f2091b1Sdrh           sqlite3_str_appendall(pAccum, pItem->zAlias);
887da653b89Sdrh         }else{
888da653b89Sdrh           Select *pSel = pItem->pSelect;
889da653b89Sdrh           assert( pSel!=0 );
890da653b89Sdrh           if( pSel->selFlags & SF_NestedFrom ){
891da653b89Sdrh             sqlite3_str_appendf(pAccum, "(join-%u)", pSel->selId);
892da653b89Sdrh           }else{
893da653b89Sdrh             sqlite3_str_appendf(pAccum, "(subquery-%u)", pSel->selId);
894da653b89Sdrh           }
895a979993bSdrh         }
8965f968436Sdrh         length = width = 0;
8975f968436Sdrh         break;
8985f968436Sdrh       }
899874ba04cSdrh       default: {
900874ba04cSdrh         assert( xtype==etINVALID );
901874ba04cSdrh         return;
902874ba04cSdrh       }
903a18c5681Sdrh     }/* End switch over the format type */
904a18c5681Sdrh     /*
905a18c5681Sdrh     ** The text of the conversion is pointed to by "bufpt" and is
906a18c5681Sdrh     ** "length" characters long.  The field width is "width".  Do
90762856465Sdrh     ** the output.  Both length and width are in bytes, not characters,
90862856465Sdrh     ** at this point.  If the "!" flag was present on string conversions
90962856465Sdrh     ** indicating that width and precision should be expressed in characters,
91062856465Sdrh     ** then the values have been translated prior to reaching this point.
911a18c5681Sdrh     */
912a70a073bSdrh     width -= length;
9138236f688Sdrh     if( width>0 ){
9140cdbe1aeSdrh       if( !flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
9150cdbe1aeSdrh       sqlite3_str_append(pAccum, bufpt, length);
9160cdbe1aeSdrh       if( flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
9178236f688Sdrh     }else{
9180cdbe1aeSdrh       sqlite3_str_append(pAccum, bufpt, length);
9198236f688Sdrh     }
920a70a073bSdrh 
921af8f513fSdrh     if( zExtra ){
92296ceaf86Sdrh       sqlite3DbFree(pAccum->db, zExtra);
923af8f513fSdrh       zExtra = 0;
924af8f513fSdrh     }
925a18c5681Sdrh   }/* End for loop over the format string */
926a18c5681Sdrh } /* End of function */
927a18c5681Sdrh 
928f62641e9Sdrh 
929f62641e9Sdrh /*
930f62641e9Sdrh ** The z string points to the first character of a token that is
931f62641e9Sdrh ** associated with an error.  If db does not already have an error
932f62641e9Sdrh ** byte offset recorded, try to compute the error byte offset for
933f62641e9Sdrh ** z and set the error byte offset in db.
934f62641e9Sdrh */
sqlite3RecordErrorByteOffset(sqlite3 * db,const char * z)935f62641e9Sdrh void sqlite3RecordErrorByteOffset(sqlite3 *db, const char *z){
936f62641e9Sdrh   const Parse *pParse;
937f62641e9Sdrh   const char *zText;
938f62641e9Sdrh   const char *zEnd;
939f62641e9Sdrh   assert( z!=0 );
940f62641e9Sdrh   if( NEVER(db==0) ) return;
941f62641e9Sdrh   if( db->errByteOffset!=(-2) ) return;
942f62641e9Sdrh   pParse = db->pParse;
943f62641e9Sdrh   if( NEVER(pParse==0) ) return;
944f62641e9Sdrh   zText =pParse->zTail;
945f62641e9Sdrh   if( NEVER(zText==0) ) return;
946f62641e9Sdrh   zEnd = &zText[strlen(zText)];
947f62641e9Sdrh   if( SQLITE_WITHIN(z,zText,zEnd) ){
948f62641e9Sdrh     db->errByteOffset = (int)(z-zText);
949f62641e9Sdrh   }
950f62641e9Sdrh }
951f62641e9Sdrh 
952a18c5681Sdrh /*
9534f77c920Sdrh ** If pExpr has a byte offset for the start of a token, record that as
9544f77c920Sdrh ** as the error offset.
9554f77c920Sdrh */
sqlite3RecordErrorOffsetOfExpr(sqlite3 * db,const Expr * pExpr)9564f77c920Sdrh void sqlite3RecordErrorOffsetOfExpr(sqlite3 *db, const Expr *pExpr){
957a6e8ee12Sdrh   while( pExpr
958a6e8ee12Sdrh      && (ExprHasProperty(pExpr,EP_OuterON|EP_InnerON) || pExpr->w.iOfst<=0)
959a6e8ee12Sdrh   ){
9604f77c920Sdrh     pExpr = pExpr->pLeft;
9614f77c920Sdrh   }
9624f77c920Sdrh   if( pExpr==0 ) return;
9634f77c920Sdrh   db->errByteOffset = pExpr->w.iOfst;
9644f77c920Sdrh }
9654f77c920Sdrh 
9664f77c920Sdrh /*
967a70a073bSdrh ** Enlarge the memory allocation on a StrAccum object so that it is
968a70a073bSdrh ** able to accept at least N more bytes of text.
969a70a073bSdrh **
970a70a073bSdrh ** Return the number of bytes of text that StrAccum is able to accept
971a70a073bSdrh ** after the attempted enlargement.  The value returned might be zero.
972a18c5681Sdrh */
sqlite3StrAccumEnlarge(StrAccum * p,int N)973ef95d558Sdrh int sqlite3StrAccumEnlarge(StrAccum *p, int N){
974a6353a3fSdrh   char *zNew;
975a30d22a7Sdrh   assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
976b49bc86aSdrh   if( p->accError ){
9770cdbe1aeSdrh     testcase(p->accError==SQLITE_TOOBIG);
9780cdbe1aeSdrh     testcase(p->accError==SQLITE_NOMEM);
979a70a073bSdrh     return 0;
980ade86483Sdrh   }
981c0490572Sdrh   if( p->mxAlloc==0 ){
982f06db3e8Sdrh     sqlite3StrAccumSetError(p, SQLITE_TOOBIG);
983255a81f1Sdrh     return p->nAlloc - p->nChar - 1;
984a18c5681Sdrh   }else{
9855f4a686fSdrh     char *zOld = isMalloced(p) ? p->zText : 0;
98693a960a0Sdrh     i64 szNew = p->nChar;
987bb05976dSdrh     szNew += (sqlite3_int64)N + 1;
9887b4d780bSdrh     if( szNew+p->nChar<=p->mxAlloc ){
9897b4d780bSdrh       /* Force exponential buffer size growth as long as it does not overflow,
9907b4d780bSdrh       ** to avoid having to call this routine too often */
9917b4d780bSdrh       szNew += p->nChar;
9927b4d780bSdrh     }
993b1a6c3c1Sdrh     if( szNew > p->mxAlloc ){
9940cdbe1aeSdrh       sqlite3_str_reset(p);
995f06db3e8Sdrh       sqlite3StrAccumSetError(p, SQLITE_TOOBIG);
996a70a073bSdrh       return 0;
997b1a6c3c1Sdrh     }else{
998ea678832Sdrh       p->nAlloc = (int)szNew;
999a18c5681Sdrh     }
1000c0490572Sdrh     if( p->db ){
1001a9ef7097Sdan       zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
1002b975598eSdrh     }else{
1003d924e7bcSdrh       zNew = sqlite3Realloc(zOld, p->nAlloc);
1004b975598eSdrh     }
100553f733c7Sdrh     if( zNew ){
10067ef4d1c4Sdrh       assert( p->zText!=0 || p->nChar==0 );
10075f4a686fSdrh       if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
1008ade86483Sdrh       p->zText = zNew;
10097f5a7ecdSdrh       p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
10105f4a686fSdrh       p->printfFlags |= SQLITE_PRINTF_MALLOCED;
1011ade86483Sdrh     }else{
10120cdbe1aeSdrh       sqlite3_str_reset(p);
1013f06db3e8Sdrh       sqlite3StrAccumSetError(p, SQLITE_NOMEM);
1014a70a073bSdrh       return 0;
1015a70a073bSdrh     }
1016a70a073bSdrh   }
1017a70a073bSdrh   return N;
1018a70a073bSdrh }
1019a70a073bSdrh 
1020a70a073bSdrh /*
1021af8f513fSdrh ** Append N copies of character c to the given string buffer.
1022a70a073bSdrh */
sqlite3_str_appendchar(sqlite3_str * p,int N,char c)10230cdbe1aeSdrh void sqlite3_str_appendchar(sqlite3_str *p, int N, char c){
1024a30d22a7Sdrh   testcase( p->nChar + (i64)N > 0x7fffffff );
1025a30d22a7Sdrh   if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
1026a30d22a7Sdrh     return;
1027a30d22a7Sdrh   }
1028af8f513fSdrh   while( (N--)>0 ) p->zText[p->nChar++] = c;
1029a70a073bSdrh }
1030a70a073bSdrh 
1031a70a073bSdrh /*
1032a70a073bSdrh ** The StrAccum "p" is not large enough to accept N new bytes of z[].
1033a70a073bSdrh ** So enlarge if first, then do the append.
1034a70a073bSdrh **
10350cdbe1aeSdrh ** This is a helper routine to sqlite3_str_append() that does special-case
1036a70a073bSdrh ** work (enlarging the buffer) using tail recursion, so that the
10370cdbe1aeSdrh ** sqlite3_str_append() routine can use fast calling semantics.
1038a70a073bSdrh */
enlargeAndAppend(StrAccum * p,const char * z,int N)1039172087fbSdrh static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
1040a70a073bSdrh   N = sqlite3StrAccumEnlarge(p, N);
1041a70a073bSdrh   if( N>0 ){
1042a70a073bSdrh     memcpy(&p->zText[p->nChar], z, N);
1043a70a073bSdrh     p->nChar += N;
1044a70a073bSdrh   }
1045a70a073bSdrh }
1046a70a073bSdrh 
1047a70a073bSdrh /*
1048a70a073bSdrh ** Append N bytes of text from z to the StrAccum object.  Increase the
1049a70a073bSdrh ** size of the memory allocation for StrAccum if necessary.
1050a70a073bSdrh */
sqlite3_str_append(sqlite3_str * p,const char * z,int N)10510cdbe1aeSdrh void sqlite3_str_append(sqlite3_str *p, const char *z, int N){
10523457338cSdrh   assert( z!=0 || N==0 );
1053a70a073bSdrh   assert( p->zText!=0 || p->nChar==0 || p->accError );
1054a70a073bSdrh   assert( N>=0 );
1055255a81f1Sdrh   assert( p->accError==0 || p->nAlloc==0 || p->mxAlloc==0 );
1056a70a073bSdrh   if( p->nChar+N >= p->nAlloc ){
1057a70a073bSdrh     enlargeAndAppend(p,z,N);
1058895decf6Sdan   }else if( N ){
1059b07028f7Sdrh     assert( p->zText );
1060ade86483Sdrh     p->nChar += N;
1061172087fbSdrh     memcpy(&p->zText[p->nChar-N], z, N);
1062172087fbSdrh   }
1063483750baSdrh }
1064483750baSdrh 
1065483750baSdrh /*
1066a6353a3fSdrh ** Append the complete text of zero-terminated string z[] to the p string.
1067a6353a3fSdrh */
sqlite3_str_appendall(sqlite3_str * p,const char * z)10680cdbe1aeSdrh void sqlite3_str_appendall(sqlite3_str *p, const char *z){
10690cdbe1aeSdrh   sqlite3_str_append(p, z, sqlite3Strlen30(z));
1070a6353a3fSdrh }
1071a6353a3fSdrh 
1072a6353a3fSdrh 
1073a6353a3fSdrh /*
1074ade86483Sdrh ** Finish off a string by making sure it is zero-terminated.
1075ade86483Sdrh ** Return a pointer to the resulting string.  Return a NULL
1076ade86483Sdrh ** pointer if any kind of error was encountered.
10775f968436Sdrh */
strAccumFinishRealloc(StrAccum * p)1078043e586eSdrh static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
10793f18e6d7Sdrh   char *zText;
1080043e586eSdrh   assert( p->mxAlloc>0 && !isMalloced(p) );
10813f18e6d7Sdrh   zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
10823f18e6d7Sdrh   if( zText ){
10833f18e6d7Sdrh     memcpy(zText, p->zText, p->nChar+1);
10845f4a686fSdrh     p->printfFlags |= SQLITE_PRINTF_MALLOCED;
1085ade86483Sdrh   }else{
1086f06db3e8Sdrh     sqlite3StrAccumSetError(p, SQLITE_NOMEM);
1087ade86483Sdrh   }
10883f18e6d7Sdrh   p->zText = zText;
10893f18e6d7Sdrh   return zText;
1090043e586eSdrh }
sqlite3StrAccumFinish(StrAccum * p)1091043e586eSdrh char *sqlite3StrAccumFinish(StrAccum *p){
1092043e586eSdrh   if( p->zText ){
1093043e586eSdrh     p->zText[p->nChar] = 0;
1094043e586eSdrh     if( p->mxAlloc>0 && !isMalloced(p) ){
1095043e586eSdrh       return strAccumFinishRealloc(p);
1096ade86483Sdrh     }
1097ade86483Sdrh   }
1098ade86483Sdrh   return p->zText;
1099ade86483Sdrh }
1100ade86483Sdrh 
1101f80bba9dSdrh /*
11025bf4715eSdrh ** Use the content of the StrAccum passed as the second argument
11035bf4715eSdrh ** as the result of an SQL function.
11045bf4715eSdrh */
sqlite3ResultStrAccum(sqlite3_context * pCtx,StrAccum * p)11055bf4715eSdrh void sqlite3ResultStrAccum(sqlite3_context *pCtx, StrAccum *p){
11065bf4715eSdrh   if( p->accError ){
11075bf4715eSdrh     sqlite3_result_error_code(pCtx, p->accError);
11085bf4715eSdrh     sqlite3_str_reset(p);
11095bf4715eSdrh   }else if( isMalloced(p) ){
11105bf4715eSdrh     sqlite3_result_text(pCtx, p->zText, p->nChar, SQLITE_DYNAMIC);
11115bf4715eSdrh   }else{
11125bf4715eSdrh     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
11135bf4715eSdrh     sqlite3_str_reset(p);
11145bf4715eSdrh   }
11155bf4715eSdrh }
11165bf4715eSdrh 
11175bf4715eSdrh /*
1118f80bba9dSdrh ** This singleton is an sqlite3_str object that is returned if
1119f80bba9dSdrh ** sqlite3_malloc() fails to provide space for a real one.  This
1120f80bba9dSdrh ** sqlite3_str object accepts no new text and always returns
1121f80bba9dSdrh ** an SQLITE_NOMEM error.
1122f80bba9dSdrh */
1123f80bba9dSdrh static sqlite3_str sqlite3OomStr = {
11243e62ddbfSdrh    0, 0, 0, 0, 0, SQLITE_NOMEM, 0
1125f80bba9dSdrh };
1126f80bba9dSdrh 
11270cdbe1aeSdrh /* Finalize a string created using sqlite3_str_new().
11280cdbe1aeSdrh */
sqlite3_str_finish(sqlite3_str * p)11290cdbe1aeSdrh char *sqlite3_str_finish(sqlite3_str *p){
11300cdbe1aeSdrh   char *z;
1131f80bba9dSdrh   if( p!=0 && p!=&sqlite3OomStr ){
11320cdbe1aeSdrh     z = sqlite3StrAccumFinish(p);
1133446135d7Sdrh     sqlite3_free(p);
11340cdbe1aeSdrh   }else{
11350cdbe1aeSdrh     z = 0;
11360cdbe1aeSdrh   }
11370cdbe1aeSdrh   return z;
11380cdbe1aeSdrh }
11390cdbe1aeSdrh 
11400cdbe1aeSdrh /* Return any error code associated with p */
sqlite3_str_errcode(sqlite3_str * p)11410cdbe1aeSdrh int sqlite3_str_errcode(sqlite3_str *p){
11420cdbe1aeSdrh   return p ? p->accError : SQLITE_NOMEM;
11430cdbe1aeSdrh }
11440cdbe1aeSdrh 
11450cdbe1aeSdrh /* Return the current length of p in bytes */
sqlite3_str_length(sqlite3_str * p)11460cdbe1aeSdrh int sqlite3_str_length(sqlite3_str *p){
11470cdbe1aeSdrh   return p ? p->nChar : 0;
11480cdbe1aeSdrh }
11490cdbe1aeSdrh 
11500cdbe1aeSdrh /* Return the current value for p */
sqlite3_str_value(sqlite3_str * p)11510cdbe1aeSdrh char *sqlite3_str_value(sqlite3_str *p){
1152446135d7Sdrh   if( p==0 || p->nChar==0 ) return 0;
1153446135d7Sdrh   p->zText[p->nChar] = 0;
1154446135d7Sdrh   return p->zText;
11550cdbe1aeSdrh }
11560cdbe1aeSdrh 
1157ade86483Sdrh /*
1158ade86483Sdrh ** Reset an StrAccum string.  Reclaim all malloced memory.
1159ade86483Sdrh */
sqlite3_str_reset(StrAccum * p)11600cdbe1aeSdrh void sqlite3_str_reset(StrAccum *p){
11615f4a686fSdrh   if( isMalloced(p) ){
1162633e6d57Sdrh     sqlite3DbFree(p->db, p->zText);
11635f4a686fSdrh     p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
1164ade86483Sdrh   }
1165446135d7Sdrh   p->nAlloc = 0;
1166446135d7Sdrh   p->nChar = 0;
1167f089aa45Sdrh   p->zText = 0;
1168ade86483Sdrh }
1169ade86483Sdrh 
1170ade86483Sdrh /*
1171c0490572Sdrh ** Initialize a string accumulator.
1172c0490572Sdrh **
1173c0490572Sdrh ** p:     The accumulator to be initialized.
1174c0490572Sdrh ** db:    Pointer to a database connection.  May be NULL.  Lookaside
1175c0490572Sdrh **        memory is used if not NULL. db->mallocFailed is set appropriately
1176c0490572Sdrh **        when not NULL.
1177c0490572Sdrh ** zBase: An initial buffer.  May be NULL in which case the initial buffer
1178c0490572Sdrh **        is malloced.
1179c0490572Sdrh ** n:     Size of zBase in bytes.  If total space requirements never exceed
1180c0490572Sdrh **        n then no memory allocations ever occur.
1181c0490572Sdrh ** mx:    Maximum number of bytes to accumulate.  If mx==0 then no memory
1182c0490572Sdrh **        allocations will ever occur.
1183ade86483Sdrh */
sqlite3StrAccumInit(StrAccum * p,sqlite3 * db,char * zBase,int n,int mx)1184c0490572Sdrh void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
11853f18e6d7Sdrh   p->zText = zBase;
1186c0490572Sdrh   p->db = db;
1187ade86483Sdrh   p->nAlloc = n;
1188bb4957f8Sdrh   p->mxAlloc = mx;
11893f18e6d7Sdrh   p->nChar = 0;
1190b49bc86aSdrh   p->accError = 0;
11915f4a686fSdrh   p->printfFlags = 0;
11925f968436Sdrh }
11935f968436Sdrh 
11940cdbe1aeSdrh /* Allocate and initialize a new dynamic string object */
sqlite3_str_new(sqlite3 * db)11950cdbe1aeSdrh sqlite3_str *sqlite3_str_new(sqlite3 *db){
1196446135d7Sdrh   sqlite3_str *p = sqlite3_malloc64(sizeof(*p));
11970cdbe1aeSdrh   if( p ){
1198446135d7Sdrh     sqlite3StrAccumInit(p, 0, 0, 0,
1199446135d7Sdrh             db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
1200f80bba9dSdrh   }else{
1201f80bba9dSdrh     p = &sqlite3OomStr;
12020cdbe1aeSdrh   }
12030cdbe1aeSdrh   return p;
12040cdbe1aeSdrh }
12050cdbe1aeSdrh 
12065f968436Sdrh /*
12075f968436Sdrh ** Print into memory obtained from sqliteMalloc().  Use the internal
12085f968436Sdrh ** %-conversion extensions.
12095f968436Sdrh */
sqlite3VMPrintf(sqlite3 * db,const char * zFormat,va_list ap)121017435752Sdrh char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
121117435752Sdrh   char *z;
121279158e18Sdrh   char zBase[SQLITE_PRINT_BUF_SIZE];
1213ade86483Sdrh   StrAccum acc;
1214bc6160b0Sdrh   assert( db!=0 );
1215c0490572Sdrh   sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
1216bc6160b0Sdrh                       db->aLimit[SQLITE_LIMIT_LENGTH]);
12175f4a686fSdrh   acc.printfFlags = SQLITE_PRINTF_INTERNAL;
12180cdbe1aeSdrh   sqlite3_str_vappendf(&acc, zFormat, ap);
1219ade86483Sdrh   z = sqlite3StrAccumFinish(&acc);
12200cdbe1aeSdrh   if( acc.accError==SQLITE_NOMEM ){
12214a642b60Sdrh     sqlite3OomFault(db);
122217435752Sdrh   }
122317435752Sdrh   return z;
12245f968436Sdrh }
12255f968436Sdrh 
12265f968436Sdrh /*
12275f968436Sdrh ** Print into memory obtained from sqliteMalloc().  Use the internal
12285f968436Sdrh ** %-conversion extensions.
12295f968436Sdrh */
sqlite3MPrintf(sqlite3 * db,const char * zFormat,...)123017435752Sdrh char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
12315f968436Sdrh   va_list ap;
12325f968436Sdrh   char *z;
12335f968436Sdrh   va_start(ap, zFormat);
1234ade86483Sdrh   z = sqlite3VMPrintf(db, zFormat, ap);
12355f968436Sdrh   va_end(ap);
12365f968436Sdrh   return z;
12375f968436Sdrh }
12385f968436Sdrh 
12395f968436Sdrh /*
124028dd479cSdrh ** Print into memory obtained from sqlite3_malloc().  Omit the internal
124128dd479cSdrh ** %-conversion extensions.
124228dd479cSdrh */
sqlite3_vmprintf(const char * zFormat,va_list ap)124328dd479cSdrh char *sqlite3_vmprintf(const char *zFormat, va_list ap){
1244ade86483Sdrh   char *z;
124528dd479cSdrh   char zBase[SQLITE_PRINT_BUF_SIZE];
1246ade86483Sdrh   StrAccum acc;
12479ca95730Sdrh 
12489ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
12499ca95730Sdrh   if( zFormat==0 ){
12509ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
12519ca95730Sdrh     return 0;
12529ca95730Sdrh   }
12539ca95730Sdrh #endif
1254ff1590eeSdrh #ifndef SQLITE_OMIT_AUTOINIT
1255ff1590eeSdrh   if( sqlite3_initialize() ) return 0;
1256ff1590eeSdrh #endif
1257c0490572Sdrh   sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
12580cdbe1aeSdrh   sqlite3_str_vappendf(&acc, zFormat, ap);
1259ade86483Sdrh   z = sqlite3StrAccumFinish(&acc);
1260ade86483Sdrh   return z;
126128dd479cSdrh }
126228dd479cSdrh 
126328dd479cSdrh /*
126428dd479cSdrh ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
126528dd479cSdrh ** %-conversion extensions.
1266483750baSdrh */
sqlite3_mprintf(const char * zFormat,...)12676f8a503dSdanielk1977 char *sqlite3_mprintf(const char *zFormat, ...){
1268a18c5681Sdrh   va_list ap;
12695f968436Sdrh   char *z;
1270ff1590eeSdrh #ifndef SQLITE_OMIT_AUTOINIT
1271ff1590eeSdrh   if( sqlite3_initialize() ) return 0;
1272ff1590eeSdrh #endif
1273a18c5681Sdrh   va_start(ap, zFormat);
1274b3738b6cSdrh   z = sqlite3_vmprintf(zFormat, ap);
1275a18c5681Sdrh   va_end(ap);
12765f968436Sdrh   return z;
1277a18c5681Sdrh }
1278a18c5681Sdrh 
1279a18c5681Sdrh /*
12806f8a503dSdanielk1977 ** sqlite3_snprintf() works like snprintf() except that it ignores the
128193a5c6bdSdrh ** current locale settings.  This is important for SQLite because we
128293a5c6bdSdrh ** are not able to use a "," as the decimal point in place of "." as
128393a5c6bdSdrh ** specified by some locales.
1284db26d4c9Sdrh **
1285db26d4c9Sdrh ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
1286db26d4c9Sdrh ** from the snprintf() standard.  Unfortunately, it is too late to change
1287db26d4c9Sdrh ** this without breaking compatibility, so we just have to live with the
1288db26d4c9Sdrh ** mistake.
1289db26d4c9Sdrh **
1290db26d4c9Sdrh ** sqlite3_vsnprintf() is the varargs version.
129193a5c6bdSdrh */
sqlite3_vsnprintf(int n,char * zBuf,const char * zFormat,va_list ap)1292db26d4c9Sdrh char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
1293db26d4c9Sdrh   StrAccum acc;
1294db26d4c9Sdrh   if( n<=0 ) return zBuf;
12959ca95730Sdrh #ifdef SQLITE_ENABLE_API_ARMOR
12969ca95730Sdrh   if( zBuf==0 || zFormat==0 ) {
12979ca95730Sdrh     (void)SQLITE_MISUSE_BKPT;
129896c707a3Sdrh     if( zBuf ) zBuf[0] = 0;
12999ca95730Sdrh     return zBuf;
13009ca95730Sdrh   }
13019ca95730Sdrh #endif
1302c0490572Sdrh   sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
13030cdbe1aeSdrh   sqlite3_str_vappendf(&acc, zFormat, ap);
1304e9bb5660Sdrh   zBuf[acc.nChar] = 0;
1305e9bb5660Sdrh   return zBuf;
1306db26d4c9Sdrh }
sqlite3_snprintf(int n,char * zBuf,const char * zFormat,...)13076f8a503dSdanielk1977 char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
13085f968436Sdrh   char *z;
130993a5c6bdSdrh   va_list ap;
131093a5c6bdSdrh   va_start(ap,zFormat);
1311db26d4c9Sdrh   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
131293a5c6bdSdrh   va_end(ap);
13135f968436Sdrh   return z;
131493a5c6bdSdrh }
131593a5c6bdSdrh 
13163f280701Sdrh /*
13177c0c460fSdrh ** This is the routine that actually formats the sqlite3_log() message.
13187c0c460fSdrh ** We house it in a separate routine from sqlite3_log() to avoid using
13197c0c460fSdrh ** stack space on small-stack systems when logging is disabled.
13207c0c460fSdrh **
13217c0c460fSdrh ** sqlite3_log() must render into a static buffer.  It cannot dynamically
13227c0c460fSdrh ** allocate memory because it might be called while the memory allocator
13237c0c460fSdrh ** mutex is held.
1324a8dbd52aSdrh **
13250cdbe1aeSdrh ** sqlite3_str_vappendf() might ask for *temporary* memory allocations for
1326a8dbd52aSdrh ** certain format characters (%q) or for very large precisions or widths.
1327a8dbd52aSdrh ** Care must be taken that any sqlite3_log() calls that occur while the
1328a8dbd52aSdrh ** memory mutex is held do not use these mechanisms.
13297c0c460fSdrh */
renderLogMsg(int iErrCode,const char * zFormat,va_list ap)13307c0c460fSdrh static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
13317c0c460fSdrh   StrAccum acc;                          /* String accumulator */
1332a64fa912Sdrh   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
13337c0c460fSdrh 
1334c0490572Sdrh   sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
13350cdbe1aeSdrh   sqlite3_str_vappendf(&acc, zFormat, ap);
13367c0c460fSdrh   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
13377c0c460fSdrh                            sqlite3StrAccumFinish(&acc));
13387c0c460fSdrh }
13397c0c460fSdrh 
13407c0c460fSdrh /*
13413f280701Sdrh ** Format and write a message to the log if logging is enabled.
13423f280701Sdrh */
sqlite3_log(int iErrCode,const char * zFormat,...)1343a7564663Sdrh void sqlite3_log(int iErrCode, const char *zFormat, ...){
13443f280701Sdrh   va_list ap;                             /* Vararg list */
13457c0c460fSdrh   if( sqlite3GlobalConfig.xLog ){
13463f280701Sdrh     va_start(ap, zFormat);
13477c0c460fSdrh     renderLogMsg(iErrCode, zFormat, ap);
13483f280701Sdrh     va_end(ap);
13493f280701Sdrh   }
13503f280701Sdrh }
13513f280701Sdrh 
135202b0e267Smistachkin #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
1353e54ca3feSdrh /*
1354e54ca3feSdrh ** A version of printf() that understands %lld.  Used for debugging.
1355e54ca3feSdrh ** The printf() built into some versions of windows does not understand %lld
1356e54ca3feSdrh ** and segfaults if you give it a long long int.
1357e54ca3feSdrh */
sqlite3DebugPrintf(const char * zFormat,...)1358e54ca3feSdrh void sqlite3DebugPrintf(const char *zFormat, ...){
1359e54ca3feSdrh   va_list ap;
1360ade86483Sdrh   StrAccum acc;
1361a8e41ecaSmistachkin   char zBuf[SQLITE_PRINT_BUF_SIZE*10];
1362c0490572Sdrh   sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
1363e54ca3feSdrh   va_start(ap,zFormat);
13640cdbe1aeSdrh   sqlite3_str_vappendf(&acc, zFormat, ap);
1365e54ca3feSdrh   va_end(ap);
1366bed8e7e5Sdrh   sqlite3StrAccumFinish(&acc);
13674a9ff918Smistachkin #ifdef SQLITE_OS_TRACE_PROC
13684a9ff918Smistachkin   {
13694a9ff918Smistachkin     extern void SQLITE_OS_TRACE_PROC(const char *zBuf, int nBuf);
13704a9ff918Smistachkin     SQLITE_OS_TRACE_PROC(zBuf, sizeof(zBuf));
13714a9ff918Smistachkin   }
13724a9ff918Smistachkin #else
1373485f0039Sdrh   fprintf(stdout,"%s", zBuf);
13742ac3ee97Sdrh   fflush(stdout);
13754a9ff918Smistachkin #endif
1376e54ca3feSdrh }
1377e54ca3feSdrh #endif
1378c7bc4fdeSdrh 
13794fa4a54fSdrh 
1380c7bc4fdeSdrh /*
13810cdbe1aeSdrh ** variable-argument wrapper around sqlite3_str_vappendf(). The bFlags argument
1382d37bea5bSdrh ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
1383c7bc4fdeSdrh */
sqlite3_str_appendf(StrAccum * p,const char * zFormat,...)13840cdbe1aeSdrh void sqlite3_str_appendf(StrAccum *p, const char *zFormat, ...){
1385c7bc4fdeSdrh   va_list ap;
1386c7bc4fdeSdrh   va_start(ap,zFormat);
13870cdbe1aeSdrh   sqlite3_str_vappendf(p, zFormat, ap);
1388c7bc4fdeSdrh   va_end(ap);
1389c7bc4fdeSdrh }
1390