xref: /sqlite-3.40.0/src/vdbemem.c (revision bcedbb27)
1 /*
2 ** 2004 May 26
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 **
13 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
14 ** stores a single value in the VDBE.  Mem is an opaque structure visible
15 ** only within the VDBE.  Interface routines refer to a Mem using the
16 ** name sqlite_value
17 */
18 #include "sqliteInt.h"
19 #include "vdbeInt.h"
20 
21 /* True if X is a power of two.  0 is considered a power of two here.
22 ** In other words, return true if X has at most one bit set.
23 */
24 #define ISPOWEROF2(X)  (((X)&((X)-1))==0)
25 
26 #ifdef SQLITE_DEBUG
27 /*
28 ** Check invariants on a Mem object.
29 **
30 ** This routine is intended for use inside of assert() statements, like
31 ** this:    assert( sqlite3VdbeCheckMemInvariants(pMem) );
32 */
33 int sqlite3VdbeCheckMemInvariants(Mem *p){
34   /* If MEM_Dyn is set then Mem.xDel!=0.
35   ** Mem.xDel might not be initialized if MEM_Dyn is clear.
36   */
37   assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
38 
39   /* MEM_Dyn may only be set if Mem.szMalloc==0.  In this way we
40   ** ensure that if Mem.szMalloc>0 then it is safe to do
41   ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
42   ** That saves a few cycles in inner loops. */
43   assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
44 
45   /* Cannot have more than one of MEM_Int, MEM_Real, or MEM_IntReal */
46   assert( ISPOWEROF2(p->flags & (MEM_Int|MEM_Real|MEM_IntReal)) );
47 
48   if( p->flags & MEM_Null ){
49     /* Cannot be both MEM_Null and some other type */
50     assert( (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob|MEM_Agg))==0 );
51 
52     /* If MEM_Null is set, then either the value is a pure NULL (the usual
53     ** case) or it is a pointer set using sqlite3_bind_pointer() or
54     ** sqlite3_result_pointer().  If a pointer, then MEM_Term must also be
55     ** set.
56     */
57     if( (p->flags & (MEM_Term|MEM_Subtype))==(MEM_Term|MEM_Subtype) ){
58       /* This is a pointer type.  There may be a flag to indicate what to
59       ** do with the pointer. */
60       assert( ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
61               ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
62               ((p->flags&MEM_Static)!=0 ? 1 : 0) <= 1 );
63 
64       /* No other bits set */
65       assert( (p->flags & ~(MEM_Null|MEM_Term|MEM_Subtype|MEM_FromBind
66                            |MEM_Dyn|MEM_Ephem|MEM_Static))==0 );
67     }else{
68       /* A pure NULL might have other flags, such as MEM_Static, MEM_Dyn,
69       ** MEM_Ephem, MEM_Cleared, or MEM_Subtype */
70     }
71   }else{
72     /* The MEM_Cleared bit is only allowed on NULLs */
73     assert( (p->flags & MEM_Cleared)==0 );
74   }
75 
76   /* The szMalloc field holds the correct memory allocation size */
77   assert( p->szMalloc==0
78        || (p->flags==MEM_Undefined
79            && p->szMalloc<=sqlite3DbMallocSize(p->db,p->zMalloc))
80        || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc));
81 
82   /* If p holds a string or blob, the Mem.z must point to exactly
83   ** one of the following:
84   **
85   **   (1) Memory in Mem.zMalloc and managed by the Mem object
86   **   (2) Memory to be freed using Mem.xDel
87   **   (3) An ephemeral string or blob
88   **   (4) A static string or blob
89   */
90   if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
91     assert(
92       ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
93       ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
94       ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
95       ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
96     );
97   }
98   return 1;
99 }
100 #endif
101 
102 /*
103 ** Render a Mem object which is one of MEM_Int, MEM_Real, or MEM_IntReal
104 ** into a buffer.
105 */
106 static void vdbeMemRenderNum(int sz, char *zBuf, Mem *p){
107   StrAccum acc;
108   assert( p->flags & (MEM_Int|MEM_Real|MEM_IntReal) );
109   assert( sz>22 );
110   if( p->flags & MEM_Int ){
111 #if GCC_VERSION>=7000000
112     /* Work-around for GCC bug
113     ** https://gcc.gnu.org/bugzilla/show_bug.cgi?id=96270 */
114     i64 x;
115     assert( (p->flags&MEM_Int)*2==sizeof(x) );
116     memcpy(&x, (char*)&p->u, (p->flags&MEM_Int)*2);
117     sqlite3Int64ToText(x, zBuf);
118 #else
119     sqlite3Int64ToText(p->u.i, zBuf);
120 #endif
121   }else{
122     sqlite3StrAccumInit(&acc, 0, zBuf, sz, 0);
123     sqlite3_str_appendf(&acc, "%!.15g",
124          (p->flags & MEM_IntReal)!=0 ? (double)p->u.i : p->u.r);
125     assert( acc.zText==zBuf && acc.mxAlloc<=0 );
126     zBuf[acc.nChar] = 0; /* Fast version of sqlite3StrAccumFinish(&acc) */
127   }
128 }
129 
130 #ifdef SQLITE_DEBUG
131 /*
132 ** Validity checks on pMem.  pMem holds a string.
133 **
134 ** (1) Check that string value of pMem agrees with its integer or real value.
135 ** (2) Check that the string is correctly zero terminated
136 **
137 ** A single int or real value always converts to the same strings.  But
138 ** many different strings can be converted into the same int or real.
139 ** If a table contains a numeric value and an index is based on the
140 ** corresponding string value, then it is important that the string be
141 ** derived from the numeric value, not the other way around, to ensure
142 ** that the index and table are consistent.  See ticket
143 ** https://www.sqlite.org/src/info/343634942dd54ab (2018-01-31) for
144 ** an example.
145 **
146 ** This routine looks at pMem to verify that if it has both a numeric
147 ** representation and a string representation then the string rep has
148 ** been derived from the numeric and not the other way around.  It returns
149 ** true if everything is ok and false if there is a problem.
150 **
151 ** This routine is for use inside of assert() statements only.
152 */
153 int sqlite3VdbeMemValidStrRep(Mem *p){
154   char zBuf[100];
155   char *z;
156   int i, j, incr;
157   if( (p->flags & MEM_Str)==0 ) return 1;
158   if( p->flags & MEM_Term ){
159     /* Insure that the string is properly zero-terminated.  Pay particular
160     ** attention to the case where p->n is odd */
161     if( p->szMalloc>0 && p->z==p->zMalloc ){
162       assert( p->enc==SQLITE_UTF8 || p->szMalloc >= ((p->n+1)&~1)+2 );
163       assert( p->enc!=SQLITE_UTF8 || p->szMalloc >= p->n+1 );
164     }
165     assert( p->z[p->n]==0 );
166     assert( p->enc==SQLITE_UTF8 || p->z[(p->n+1)&~1]==0 );
167     assert( p->enc==SQLITE_UTF8 || p->z[((p->n+1)&~1)+1]==0 );
168   }
169   if( (p->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 ) return 1;
170   vdbeMemRenderNum(sizeof(zBuf), zBuf, p);
171   z = p->z;
172   i = j = 0;
173   incr = 1;
174   if( p->enc!=SQLITE_UTF8 ){
175     incr = 2;
176     if( p->enc==SQLITE_UTF16BE ) z++;
177   }
178   while( zBuf[j] ){
179     if( zBuf[j++]!=z[i] ) return 0;
180     i += incr;
181   }
182   return 1;
183 }
184 #endif /* SQLITE_DEBUG */
185 
186 /*
187 ** If pMem is an object with a valid string representation, this routine
188 ** ensures the internal encoding for the string representation is
189 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
190 **
191 ** If pMem is not a string object, or the encoding of the string
192 ** representation is already stored using the requested encoding, then this
193 ** routine is a no-op.
194 **
195 ** SQLITE_OK is returned if the conversion is successful (or not required).
196 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
197 ** between formats.
198 */
199 int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
200 #ifndef SQLITE_OMIT_UTF16
201   int rc;
202 #endif
203   assert( pMem!=0 );
204   assert( !sqlite3VdbeMemIsRowSet(pMem) );
205   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
206            || desiredEnc==SQLITE_UTF16BE );
207   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
208     return SQLITE_OK;
209   }
210   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
211 #ifdef SQLITE_OMIT_UTF16
212   return SQLITE_ERROR;
213 #else
214 
215   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
216   ** then the encoding of the value may not have changed.
217   */
218   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
219   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
220   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
221   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
222   return rc;
223 #endif
224 }
225 
226 /*
227 ** Make sure pMem->z points to a writable allocation of at least n bytes.
228 **
229 ** If the bPreserve argument is true, then copy of the content of
230 ** pMem->z into the new allocation.  pMem must be either a string or
231 ** blob if bPreserve is true.  If bPreserve is false, any prior content
232 ** in pMem->z is discarded.
233 */
234 SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
235   assert( sqlite3VdbeCheckMemInvariants(pMem) );
236   assert( !sqlite3VdbeMemIsRowSet(pMem) );
237   testcase( pMem->db==0 );
238 
239   /* If the bPreserve flag is set to true, then the memory cell must already
240   ** contain a valid string or blob value.  */
241   assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
242   testcase( bPreserve && pMem->z==0 );
243 
244   assert( pMem->szMalloc==0
245        || (pMem->flags==MEM_Undefined
246            && pMem->szMalloc<=sqlite3DbMallocSize(pMem->db,pMem->zMalloc))
247        || pMem->szMalloc==sqlite3DbMallocSize(pMem->db,pMem->zMalloc));
248   if( pMem->szMalloc>0 && bPreserve && pMem->z==pMem->zMalloc ){
249     if( pMem->db ){
250       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
251     }else{
252       pMem->zMalloc = sqlite3Realloc(pMem->z, n);
253       if( pMem->zMalloc==0 ) sqlite3_free(pMem->z);
254       pMem->z = pMem->zMalloc;
255     }
256     bPreserve = 0;
257   }else{
258     if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
259     pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
260   }
261   if( pMem->zMalloc==0 ){
262     sqlite3VdbeMemSetNull(pMem);
263     pMem->z = 0;
264     pMem->szMalloc = 0;
265     return SQLITE_NOMEM_BKPT;
266   }else{
267     pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
268   }
269 
270   if( bPreserve && pMem->z ){
271     assert( pMem->z!=pMem->zMalloc );
272     memcpy(pMem->zMalloc, pMem->z, pMem->n);
273   }
274   if( (pMem->flags&MEM_Dyn)!=0 ){
275     assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
276     pMem->xDel((void *)(pMem->z));
277   }
278 
279   pMem->z = pMem->zMalloc;
280   pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
281   return SQLITE_OK;
282 }
283 
284 /*
285 ** Change the pMem->zMalloc allocation to be at least szNew bytes.
286 ** If pMem->zMalloc already meets or exceeds the requested size, this
287 ** routine is a no-op.
288 **
289 ** Any prior string or blob content in the pMem object may be discarded.
290 ** The pMem->xDel destructor is called, if it exists.  Though MEM_Str
291 ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, MEM_IntReal,
292 ** and MEM_Null values are preserved.
293 **
294 ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
295 ** if unable to complete the resizing.
296 */
297 int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
298   assert( CORRUPT_DB || szNew>0 );
299   assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
300   if( pMem->szMalloc<szNew ){
301     return sqlite3VdbeMemGrow(pMem, szNew, 0);
302   }
303   assert( (pMem->flags & MEM_Dyn)==0 );
304   pMem->z = pMem->zMalloc;
305   pMem->flags &= (MEM_Null|MEM_Int|MEM_Real|MEM_IntReal);
306   return SQLITE_OK;
307 }
308 
309 /*
310 ** It is already known that pMem contains an unterminated string.
311 ** Add the zero terminator.
312 **
313 ** Three bytes of zero are added.  In this way, there is guaranteed
314 ** to be a double-zero byte at an even byte boundary in order to
315 ** terminate a UTF16 string, even if the initial size of the buffer
316 ** is an odd number of bytes.
317 */
318 static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
319   if( sqlite3VdbeMemGrow(pMem, pMem->n+3, 1) ){
320     return SQLITE_NOMEM_BKPT;
321   }
322   pMem->z[pMem->n] = 0;
323   pMem->z[pMem->n+1] = 0;
324   pMem->z[pMem->n+2] = 0;
325   pMem->flags |= MEM_Term;
326   return SQLITE_OK;
327 }
328 
329 /*
330 ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
331 ** MEM.zMalloc, where it can be safely written.
332 **
333 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
334 */
335 int sqlite3VdbeMemMakeWriteable(Mem *pMem){
336   assert( pMem!=0 );
337   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
338   assert( !sqlite3VdbeMemIsRowSet(pMem) );
339   if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
340     if( ExpandBlob(pMem) ) return SQLITE_NOMEM;
341     if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
342       int rc = vdbeMemAddTerminator(pMem);
343       if( rc ) return rc;
344     }
345   }
346   pMem->flags &= ~MEM_Ephem;
347 #ifdef SQLITE_DEBUG
348   pMem->pScopyFrom = 0;
349 #endif
350 
351   return SQLITE_OK;
352 }
353 
354 /*
355 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
356 ** blob stored in dynamically allocated space.
357 */
358 #ifndef SQLITE_OMIT_INCRBLOB
359 int sqlite3VdbeMemExpandBlob(Mem *pMem){
360   int nByte;
361   assert( pMem!=0 );
362   assert( pMem->flags & MEM_Zero );
363   assert( (pMem->flags&MEM_Blob)!=0 || MemNullNochng(pMem) );
364   testcase( sqlite3_value_nochange(pMem) );
365   assert( !sqlite3VdbeMemIsRowSet(pMem) );
366   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
367 
368   /* Set nByte to the number of bytes required to store the expanded blob. */
369   nByte = pMem->n + pMem->u.nZero;
370   if( nByte<=0 ){
371     if( (pMem->flags & MEM_Blob)==0 ) return SQLITE_OK;
372     nByte = 1;
373   }
374   if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
375     return SQLITE_NOMEM_BKPT;
376   }
377   assert( pMem->z!=0 );
378   assert( sqlite3DbMallocSize(pMem->db,pMem->z) >= nByte );
379 
380   memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
381   pMem->n += pMem->u.nZero;
382   pMem->flags &= ~(MEM_Zero|MEM_Term);
383   return SQLITE_OK;
384 }
385 #endif
386 
387 /*
388 ** Make sure the given Mem is \u0000 terminated.
389 */
390 int sqlite3VdbeMemNulTerminate(Mem *pMem){
391   assert( pMem!=0 );
392   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
393   testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
394   testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
395   if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
396     return SQLITE_OK;   /* Nothing to do */
397   }else{
398     return vdbeMemAddTerminator(pMem);
399   }
400 }
401 
402 /*
403 ** Add MEM_Str to the set of representations for the given Mem.  This
404 ** routine is only called if pMem is a number of some kind, not a NULL
405 ** or a BLOB.
406 **
407 ** Existing representations MEM_Int, MEM_Real, or MEM_IntReal are invalidated
408 ** if bForce is true but are retained if bForce is false.
409 **
410 ** A MEM_Null value will never be passed to this function. This function is
411 ** used for converting values to text for returning to the user (i.e. via
412 ** sqlite3_value_text()), or for ensuring that values to be used as btree
413 ** keys are strings. In the former case a NULL pointer is returned the
414 ** user and the latter is an internal programming error.
415 */
416 int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
417   const int nByte = 32;
418 
419   assert( pMem!=0 );
420   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
421   assert( !(pMem->flags&MEM_Zero) );
422   assert( !(pMem->flags&(MEM_Str|MEM_Blob)) );
423   assert( pMem->flags&(MEM_Int|MEM_Real|MEM_IntReal) );
424   assert( !sqlite3VdbeMemIsRowSet(pMem) );
425   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
426 
427 
428   if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
429     pMem->enc = 0;
430     return SQLITE_NOMEM_BKPT;
431   }
432 
433   vdbeMemRenderNum(nByte, pMem->z, pMem);
434   assert( pMem->z!=0 );
435   pMem->n = sqlite3Strlen30NN(pMem->z);
436   pMem->enc = SQLITE_UTF8;
437   pMem->flags |= MEM_Str|MEM_Term;
438   if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal);
439   sqlite3VdbeChangeEncoding(pMem, enc);
440   return SQLITE_OK;
441 }
442 
443 /*
444 ** Memory cell pMem contains the context of an aggregate function.
445 ** This routine calls the finalize method for that function.  The
446 ** result of the aggregate is stored back into pMem.
447 **
448 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
449 ** otherwise.
450 */
451 int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
452   sqlite3_context ctx;
453   Mem t;
454   assert( pFunc!=0 );
455   assert( pMem!=0 );
456   assert( pFunc->xFinalize!=0 );
457   assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
458   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
459   memset(&ctx, 0, sizeof(ctx));
460   memset(&t, 0, sizeof(t));
461   t.flags = MEM_Null;
462   t.db = pMem->db;
463   ctx.pOut = &t;
464   ctx.pMem = pMem;
465   ctx.pFunc = pFunc;
466   pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
467   assert( (pMem->flags & MEM_Dyn)==0 );
468   if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
469   memcpy(pMem, &t, sizeof(t));
470   return ctx.isError;
471 }
472 
473 /*
474 ** Memory cell pAccum contains the context of an aggregate function.
475 ** This routine calls the xValue method for that function and stores
476 ** the results in memory cell pMem.
477 **
478 ** SQLITE_ERROR is returned if xValue() reports an error. SQLITE_OK
479 ** otherwise.
480 */
481 #ifndef SQLITE_OMIT_WINDOWFUNC
482 int sqlite3VdbeMemAggValue(Mem *pAccum, Mem *pOut, FuncDef *pFunc){
483   sqlite3_context ctx;
484   assert( pFunc!=0 );
485   assert( pFunc->xValue!=0 );
486   assert( (pAccum->flags & MEM_Null)!=0 || pFunc==pAccum->u.pDef );
487   assert( pAccum->db==0 || sqlite3_mutex_held(pAccum->db->mutex) );
488   memset(&ctx, 0, sizeof(ctx));
489   sqlite3VdbeMemSetNull(pOut);
490   ctx.pOut = pOut;
491   ctx.pMem = pAccum;
492   ctx.pFunc = pFunc;
493   pFunc->xValue(&ctx);
494   return ctx.isError;
495 }
496 #endif /* SQLITE_OMIT_WINDOWFUNC */
497 
498 /*
499 ** If the memory cell contains a value that must be freed by
500 ** invoking the external callback in Mem.xDel, then this routine
501 ** will free that value.  It also sets Mem.flags to MEM_Null.
502 **
503 ** This is a helper routine for sqlite3VdbeMemSetNull() and
504 ** for sqlite3VdbeMemRelease().  Use those other routines as the
505 ** entry point for releasing Mem resources.
506 */
507 static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
508   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
509   assert( VdbeMemDynamic(p) );
510   if( p->flags&MEM_Agg ){
511     sqlite3VdbeMemFinalize(p, p->u.pDef);
512     assert( (p->flags & MEM_Agg)==0 );
513     testcase( p->flags & MEM_Dyn );
514   }
515   if( p->flags&MEM_Dyn ){
516     assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
517     p->xDel((void *)p->z);
518   }
519   p->flags = MEM_Null;
520 }
521 
522 /*
523 ** Release memory held by the Mem p, both external memory cleared
524 ** by p->xDel and memory in p->zMalloc.
525 **
526 ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
527 ** the unusual case where there really is memory in p that needs
528 ** to be freed.
529 */
530 static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
531   if( VdbeMemDynamic(p) ){
532     vdbeMemClearExternAndSetNull(p);
533   }
534   if( p->szMalloc ){
535     sqlite3DbFreeNN(p->db, p->zMalloc);
536     p->szMalloc = 0;
537   }
538   p->z = 0;
539 }
540 
541 /*
542 ** Release any memory resources held by the Mem.  Both the memory that is
543 ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
544 **
545 ** Use this routine prior to clean up prior to abandoning a Mem, or to
546 ** reset a Mem back to its minimum memory utilization.
547 **
548 ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
549 ** prior to inserting new content into the Mem.
550 */
551 void sqlite3VdbeMemRelease(Mem *p){
552   assert( sqlite3VdbeCheckMemInvariants(p) );
553   if( VdbeMemDynamic(p) || p->szMalloc ){
554     vdbeMemClear(p);
555   }
556 }
557 
558 /* Like sqlite3VdbeMemRelease() but faster for cases where we
559 ** know in advance that the Mem is not MEM_Dyn or MEM_Agg.
560 */
561 void sqlite3VdbeMemReleaseMalloc(Mem *p){
562   assert( !VdbeMemDynamic(p) );
563   if( p->szMalloc ) vdbeMemClear(p);
564 }
565 
566 /*
567 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
568 ** If the double is out of range of a 64-bit signed integer then
569 ** return the closest available 64-bit signed integer.
570 */
571 static SQLITE_NOINLINE i64 doubleToInt64(double r){
572 #ifdef SQLITE_OMIT_FLOATING_POINT
573   /* When floating-point is omitted, double and int64 are the same thing */
574   return r;
575 #else
576   /*
577   ** Many compilers we encounter do not define constants for the
578   ** minimum and maximum 64-bit integers, or they define them
579   ** inconsistently.  And many do not understand the "LL" notation.
580   ** So we define our own static constants here using nothing
581   ** larger than a 32-bit integer constant.
582   */
583   static const i64 maxInt = LARGEST_INT64;
584   static const i64 minInt = SMALLEST_INT64;
585 
586   if( r<=(double)minInt ){
587     return minInt;
588   }else if( r>=(double)maxInt ){
589     return maxInt;
590   }else{
591     return (i64)r;
592   }
593 #endif
594 }
595 
596 /*
597 ** Return some kind of integer value which is the best we can do
598 ** at representing the value that *pMem describes as an integer.
599 ** If pMem is an integer, then the value is exact.  If pMem is
600 ** a floating-point then the value returned is the integer part.
601 ** If pMem is a string or blob, then we make an attempt to convert
602 ** it into an integer and return that.  If pMem represents an
603 ** an SQL-NULL value, return 0.
604 **
605 ** If pMem represents a string value, its encoding might be changed.
606 */
607 static SQLITE_NOINLINE i64 memIntValue(const Mem *pMem){
608   i64 value = 0;
609   sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
610   return value;
611 }
612 i64 sqlite3VdbeIntValue(const Mem *pMem){
613   int flags;
614   assert( pMem!=0 );
615   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
616   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
617   flags = pMem->flags;
618   if( flags & (MEM_Int|MEM_IntReal) ){
619     testcase( flags & MEM_IntReal );
620     return pMem->u.i;
621   }else if( flags & MEM_Real ){
622     return doubleToInt64(pMem->u.r);
623   }else if( (flags & (MEM_Str|MEM_Blob))!=0 && pMem->z!=0 ){
624     return memIntValue(pMem);
625   }else{
626     return 0;
627   }
628 }
629 
630 /*
631 ** Return the best representation of pMem that we can get into a
632 ** double.  If pMem is already a double or an integer, return its
633 ** value.  If it is a string or blob, try to convert it to a double.
634 ** If it is a NULL, return 0.0.
635 */
636 static SQLITE_NOINLINE double memRealValue(Mem *pMem){
637   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
638   double val = (double)0;
639   sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
640   return val;
641 }
642 double sqlite3VdbeRealValue(Mem *pMem){
643   assert( pMem!=0 );
644   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
645   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
646   if( pMem->flags & MEM_Real ){
647     return pMem->u.r;
648   }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){
649     testcase( pMem->flags & MEM_IntReal );
650     return (double)pMem->u.i;
651   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
652     return memRealValue(pMem);
653   }else{
654     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
655     return (double)0;
656   }
657 }
658 
659 /*
660 ** Return 1 if pMem represents true, and return 0 if pMem represents false.
661 ** Return the value ifNull if pMem is NULL.
662 */
663 int sqlite3VdbeBooleanValue(Mem *pMem, int ifNull){
664   testcase( pMem->flags & MEM_IntReal );
665   if( pMem->flags & (MEM_Int|MEM_IntReal) ) return pMem->u.i!=0;
666   if( pMem->flags & MEM_Null ) return ifNull;
667   return sqlite3VdbeRealValue(pMem)!=0.0;
668 }
669 
670 /*
671 ** The MEM structure is already a MEM_Real.  Try to also make it a
672 ** MEM_Int if we can.
673 */
674 void sqlite3VdbeIntegerAffinity(Mem *pMem){
675   i64 ix;
676   assert( pMem!=0 );
677   assert( pMem->flags & MEM_Real );
678   assert( !sqlite3VdbeMemIsRowSet(pMem) );
679   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
680   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
681 
682   ix = doubleToInt64(pMem->u.r);
683 
684   /* Only mark the value as an integer if
685   **
686   **    (1) the round-trip conversion real->int->real is a no-op, and
687   **    (2) The integer is neither the largest nor the smallest
688   **        possible integer (ticket #3922)
689   **
690   ** The second and third terms in the following conditional enforces
691   ** the second condition under the assumption that addition overflow causes
692   ** values to wrap around.
693   */
694   if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
695     pMem->u.i = ix;
696     MemSetTypeFlag(pMem, MEM_Int);
697   }
698 }
699 
700 /*
701 ** Convert pMem to type integer.  Invalidate any prior representations.
702 */
703 int sqlite3VdbeMemIntegerify(Mem *pMem){
704   assert( pMem!=0 );
705   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
706   assert( !sqlite3VdbeMemIsRowSet(pMem) );
707   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
708 
709   pMem->u.i = sqlite3VdbeIntValue(pMem);
710   MemSetTypeFlag(pMem, MEM_Int);
711   return SQLITE_OK;
712 }
713 
714 /*
715 ** Convert pMem so that it is of type MEM_Real.
716 ** Invalidate any prior representations.
717 */
718 int sqlite3VdbeMemRealify(Mem *pMem){
719   assert( pMem!=0 );
720   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
721   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
722 
723   pMem->u.r = sqlite3VdbeRealValue(pMem);
724   MemSetTypeFlag(pMem, MEM_Real);
725   return SQLITE_OK;
726 }
727 
728 /* Compare a floating point value to an integer.  Return true if the two
729 ** values are the same within the precision of the floating point value.
730 **
731 ** This function assumes that i was obtained by assignment from r1.
732 **
733 ** For some versions of GCC on 32-bit machines, if you do the more obvious
734 ** comparison of "r1==(double)i" you sometimes get an answer of false even
735 ** though the r1 and (double)i values are bit-for-bit the same.
736 */
737 int sqlite3RealSameAsInt(double r1, sqlite3_int64 i){
738   double r2 = (double)i;
739   return r1==0.0
740       || (memcmp(&r1, &r2, sizeof(r1))==0
741           && i >= -2251799813685248LL && i < 2251799813685248LL);
742 }
743 
744 /*
745 ** Convert pMem so that it has type MEM_Real or MEM_Int.
746 ** Invalidate any prior representations.
747 **
748 ** Every effort is made to force the conversion, even if the input
749 ** is a string that does not look completely like a number.  Convert
750 ** as much of the string as we can and ignore the rest.
751 */
752 int sqlite3VdbeMemNumerify(Mem *pMem){
753   assert( pMem!=0 );
754   testcase( pMem->flags & MEM_Int );
755   testcase( pMem->flags & MEM_Real );
756   testcase( pMem->flags & MEM_IntReal );
757   testcase( pMem->flags & MEM_Null );
758   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))==0 ){
759     int rc;
760     sqlite3_int64 ix;
761     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
762     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
763     rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
764     if( ((rc==0 || rc==1) && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1)
765      || sqlite3RealSameAsInt(pMem->u.r, (ix = (i64)pMem->u.r))
766     ){
767       pMem->u.i = ix;
768       MemSetTypeFlag(pMem, MEM_Int);
769     }else{
770       MemSetTypeFlag(pMem, MEM_Real);
771     }
772   }
773   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))!=0 );
774   pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
775   return SQLITE_OK;
776 }
777 
778 /*
779 ** Cast the datatype of the value in pMem according to the affinity
780 ** "aff".  Casting is different from applying affinity in that a cast
781 ** is forced.  In other words, the value is converted into the desired
782 ** affinity even if that results in loss of data.  This routine is
783 ** used (for example) to implement the SQL "cast()" operator.
784 */
785 int sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
786   if( pMem->flags & MEM_Null ) return SQLITE_OK;
787   switch( aff ){
788     case SQLITE_AFF_BLOB: {   /* Really a cast to BLOB */
789       if( (pMem->flags & MEM_Blob)==0 ){
790         sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
791         assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
792         if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
793       }else{
794         pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
795       }
796       break;
797     }
798     case SQLITE_AFF_NUMERIC: {
799       sqlite3VdbeMemNumerify(pMem);
800       break;
801     }
802     case SQLITE_AFF_INTEGER: {
803       sqlite3VdbeMemIntegerify(pMem);
804       break;
805     }
806     case SQLITE_AFF_REAL: {
807       sqlite3VdbeMemRealify(pMem);
808       break;
809     }
810     default: {
811       assert( aff==SQLITE_AFF_TEXT );
812       assert( MEM_Str==(MEM_Blob>>3) );
813       pMem->flags |= (pMem->flags&MEM_Blob)>>3;
814       sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
815       assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
816       pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal|MEM_Blob|MEM_Zero);
817       return sqlite3VdbeChangeEncoding(pMem, encoding);
818     }
819   }
820   return SQLITE_OK;
821 }
822 
823 /*
824 ** Initialize bulk memory to be a consistent Mem object.
825 **
826 ** The minimum amount of initialization feasible is performed.
827 */
828 void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
829   assert( (flags & ~MEM_TypeMask)==0 );
830   pMem->flags = flags;
831   pMem->db = db;
832   pMem->szMalloc = 0;
833 }
834 
835 
836 /*
837 ** Delete any previous value and set the value stored in *pMem to NULL.
838 **
839 ** This routine calls the Mem.xDel destructor to dispose of values that
840 ** require the destructor.  But it preserves the Mem.zMalloc memory allocation.
841 ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
842 ** routine to invoke the destructor and deallocates Mem.zMalloc.
843 **
844 ** Use this routine to reset the Mem prior to insert a new value.
845 **
846 ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
847 */
848 void sqlite3VdbeMemSetNull(Mem *pMem){
849   if( VdbeMemDynamic(pMem) ){
850     vdbeMemClearExternAndSetNull(pMem);
851   }else{
852     pMem->flags = MEM_Null;
853   }
854 }
855 void sqlite3ValueSetNull(sqlite3_value *p){
856   sqlite3VdbeMemSetNull((Mem*)p);
857 }
858 
859 /*
860 ** Delete any previous value and set the value to be a BLOB of length
861 ** n containing all zeros.
862 */
863 #ifndef SQLITE_OMIT_INCRBLOB
864 void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
865   sqlite3VdbeMemRelease(pMem);
866   pMem->flags = MEM_Blob|MEM_Zero;
867   pMem->n = 0;
868   if( n<0 ) n = 0;
869   pMem->u.nZero = n;
870   pMem->enc = SQLITE_UTF8;
871   pMem->z = 0;
872 }
873 #else
874 int sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
875   int nByte = n>0?n:1;
876   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
877     return SQLITE_NOMEM_BKPT;
878   }
879   assert( pMem->z!=0 );
880   assert( sqlite3DbMallocSize(pMem->db, pMem->z)>=nByte );
881   memset(pMem->z, 0, nByte);
882   pMem->n = n>0?n:0;
883   pMem->flags = MEM_Blob;
884   pMem->enc = SQLITE_UTF8;
885   return SQLITE_OK;
886 }
887 #endif
888 
889 /*
890 ** The pMem is known to contain content that needs to be destroyed prior
891 ** to a value change.  So invoke the destructor, then set the value to
892 ** a 64-bit integer.
893 */
894 static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
895   sqlite3VdbeMemSetNull(pMem);
896   pMem->u.i = val;
897   pMem->flags = MEM_Int;
898 }
899 
900 /*
901 ** Delete any previous value and set the value stored in *pMem to val,
902 ** manifest type INTEGER.
903 */
904 void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
905   if( VdbeMemDynamic(pMem) ){
906     vdbeReleaseAndSetInt64(pMem, val);
907   }else{
908     pMem->u.i = val;
909     pMem->flags = MEM_Int;
910   }
911 }
912 
913 /* A no-op destructor */
914 void sqlite3NoopDestructor(void *p){ UNUSED_PARAMETER(p); }
915 
916 /*
917 ** Set the value stored in *pMem should already be a NULL.
918 ** Also store a pointer to go with it.
919 */
920 void sqlite3VdbeMemSetPointer(
921   Mem *pMem,
922   void *pPtr,
923   const char *zPType,
924   void (*xDestructor)(void*)
925 ){
926   assert( pMem->flags==MEM_Null );
927   vdbeMemClear(pMem);
928   pMem->u.zPType = zPType ? zPType : "";
929   pMem->z = pPtr;
930   pMem->flags = MEM_Null|MEM_Dyn|MEM_Subtype|MEM_Term;
931   pMem->eSubtype = 'p';
932   pMem->xDel = xDestructor ? xDestructor : sqlite3NoopDestructor;
933 }
934 
935 #ifndef SQLITE_OMIT_FLOATING_POINT
936 /*
937 ** Delete any previous value and set the value stored in *pMem to val,
938 ** manifest type REAL.
939 */
940 void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
941   sqlite3VdbeMemSetNull(pMem);
942   if( !sqlite3IsNaN(val) ){
943     pMem->u.r = val;
944     pMem->flags = MEM_Real;
945   }
946 }
947 #endif
948 
949 #ifdef SQLITE_DEBUG
950 /*
951 ** Return true if the Mem holds a RowSet object.  This routine is intended
952 ** for use inside of assert() statements.
953 */
954 int sqlite3VdbeMemIsRowSet(const Mem *pMem){
955   return (pMem->flags&(MEM_Blob|MEM_Dyn))==(MEM_Blob|MEM_Dyn)
956          && pMem->xDel==sqlite3RowSetDelete;
957 }
958 #endif
959 
960 /*
961 ** Delete any previous value and set the value of pMem to be an
962 ** empty boolean index.
963 **
964 ** Return SQLITE_OK on success and SQLITE_NOMEM if a memory allocation
965 ** error occurs.
966 */
967 int sqlite3VdbeMemSetRowSet(Mem *pMem){
968   sqlite3 *db = pMem->db;
969   RowSet *p;
970   assert( db!=0 );
971   assert( !sqlite3VdbeMemIsRowSet(pMem) );
972   sqlite3VdbeMemRelease(pMem);
973   p = sqlite3RowSetInit(db);
974   if( p==0 ) return SQLITE_NOMEM;
975   pMem->z = (char*)p;
976   pMem->flags = MEM_Blob|MEM_Dyn;
977   pMem->xDel = sqlite3RowSetDelete;
978   return SQLITE_OK;
979 }
980 
981 /*
982 ** Return true if the Mem object contains a TEXT or BLOB that is
983 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
984 */
985 int sqlite3VdbeMemTooBig(Mem *p){
986   assert( p->db!=0 );
987   if( p->flags & (MEM_Str|MEM_Blob) ){
988     int n = p->n;
989     if( p->flags & MEM_Zero ){
990       n += p->u.nZero;
991     }
992     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
993   }
994   return 0;
995 }
996 
997 #ifdef SQLITE_DEBUG
998 /*
999 ** This routine prepares a memory cell for modification by breaking
1000 ** its link to a shallow copy and by marking any current shallow
1001 ** copies of this cell as invalid.
1002 **
1003 ** This is used for testing and debugging only - to help ensure that shallow
1004 ** copies (created by OP_SCopy) are not misused.
1005 */
1006 void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
1007   int i;
1008   Mem *pX;
1009   for(i=1, pX=pVdbe->aMem+1; i<pVdbe->nMem; i++, pX++){
1010     if( pX->pScopyFrom==pMem ){
1011       u16 mFlags;
1012       if( pVdbe->db->flags & SQLITE_VdbeTrace ){
1013         sqlite3DebugPrintf("Invalidate R[%d] due to change in R[%d]\n",
1014           (int)(pX - pVdbe->aMem), (int)(pMem - pVdbe->aMem));
1015       }
1016       /* If pX is marked as a shallow copy of pMem, then try to verify that
1017       ** no significant changes have been made to pX since the OP_SCopy.
1018       ** A significant change would indicated a missed call to this
1019       ** function for pX.  Minor changes, such as adding or removing a
1020       ** dual type, are allowed, as long as the underlying value is the
1021       ** same. */
1022       mFlags = pMem->flags & pX->flags & pX->mScopyFlags;
1023       assert( (mFlags&(MEM_Int|MEM_IntReal))==0 || pMem->u.i==pX->u.i );
1024 
1025       /* pMem is the register that is changing.  But also mark pX as
1026       ** undefined so that we can quickly detect the shallow-copy error */
1027       pX->flags = MEM_Undefined;
1028       pX->pScopyFrom = 0;
1029     }
1030   }
1031   pMem->pScopyFrom = 0;
1032 }
1033 #endif /* SQLITE_DEBUG */
1034 
1035 /*
1036 ** Make an shallow copy of pFrom into pTo.  Prior contents of
1037 ** pTo are freed.  The pFrom->z field is not duplicated.  If
1038 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
1039 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
1040 */
1041 static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
1042   vdbeMemClearExternAndSetNull(pTo);
1043   assert( !VdbeMemDynamic(pTo) );
1044   sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
1045 }
1046 void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
1047   assert( !sqlite3VdbeMemIsRowSet(pFrom) );
1048   assert( pTo->db==pFrom->db );
1049   if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
1050   memcpy(pTo, pFrom, MEMCELLSIZE);
1051   if( (pFrom->flags&MEM_Static)==0 ){
1052     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
1053     assert( srcType==MEM_Ephem || srcType==MEM_Static );
1054     pTo->flags |= srcType;
1055   }
1056 }
1057 
1058 /*
1059 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
1060 ** freed before the copy is made.
1061 */
1062 int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
1063   int rc = SQLITE_OK;
1064 
1065   assert( !sqlite3VdbeMemIsRowSet(pFrom) );
1066   if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
1067   memcpy(pTo, pFrom, MEMCELLSIZE);
1068   pTo->flags &= ~MEM_Dyn;
1069   if( pTo->flags&(MEM_Str|MEM_Blob) ){
1070     if( 0==(pFrom->flags&MEM_Static) ){
1071       pTo->flags |= MEM_Ephem;
1072       rc = sqlite3VdbeMemMakeWriteable(pTo);
1073     }
1074   }
1075 
1076   return rc;
1077 }
1078 
1079 /*
1080 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
1081 ** freed. If pFrom contains ephemeral data, a copy is made.
1082 **
1083 ** pFrom contains an SQL NULL when this routine returns.
1084 */
1085 void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
1086   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
1087   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
1088   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
1089 
1090   sqlite3VdbeMemRelease(pTo);
1091   memcpy(pTo, pFrom, sizeof(Mem));
1092   pFrom->flags = MEM_Null;
1093   pFrom->szMalloc = 0;
1094 }
1095 
1096 /*
1097 ** Change the value of a Mem to be a string or a BLOB.
1098 **
1099 ** The memory management strategy depends on the value of the xDel
1100 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
1101 ** string is copied into a (possibly existing) buffer managed by the
1102 ** Mem structure. Otherwise, any existing buffer is freed and the
1103 ** pointer copied.
1104 **
1105 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
1106 ** size limit) then no memory allocation occurs.  If the string can be
1107 ** stored without allocating memory, then it is.  If a memory allocation
1108 ** is required to store the string, then value of pMem is unchanged.  In
1109 ** either case, SQLITE_TOOBIG is returned.
1110 **
1111 ** The "enc" parameter is the text encoding for the string, or zero
1112 ** to store a blob.
1113 **
1114 ** If n is negative, then the string consists of all bytes up to but
1115 ** excluding the first zero character.  The n parameter must be
1116 ** non-negative for blobs.
1117 */
1118 int sqlite3VdbeMemSetStr(
1119   Mem *pMem,          /* Memory cell to set to string value */
1120   const char *z,      /* String pointer */
1121   i64 n,              /* Bytes in string, or negative */
1122   u8 enc,             /* Encoding of z.  0 for BLOBs */
1123   void (*xDel)(void*) /* Destructor function */
1124 ){
1125   i64 nByte = n;      /* New value for pMem->n */
1126   int iLimit;         /* Maximum allowed string or blob size */
1127   u16 flags;          /* New value for pMem->flags */
1128 
1129   assert( pMem!=0 );
1130   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
1131   assert( !sqlite3VdbeMemIsRowSet(pMem) );
1132   assert( enc!=0 || n>=0 );
1133 
1134   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
1135   if( !z ){
1136     sqlite3VdbeMemSetNull(pMem);
1137     return SQLITE_OK;
1138   }
1139 
1140   if( pMem->db ){
1141     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
1142   }else{
1143     iLimit = SQLITE_MAX_LENGTH;
1144   }
1145   if( nByte<0 ){
1146     assert( enc!=0 );
1147     if( enc==SQLITE_UTF8 ){
1148       nByte = strlen(z);
1149     }else{
1150       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
1151     }
1152     flags= MEM_Str|MEM_Term;
1153   }else if( enc==0 ){
1154     flags = MEM_Blob;
1155 #ifdef SQLITE_ENABLE_SESSION
1156     enc = pMem->db ? ENC(pMem->db) : SQLITE_UTF8;
1157 #else
1158     assert( pMem->db!=0 );
1159     enc = ENC(pMem->db);
1160 #endif
1161   }else{
1162     flags = MEM_Str;
1163   }
1164   if( nByte>iLimit ){
1165     if( xDel && xDel!=SQLITE_TRANSIENT ){
1166       if( xDel==SQLITE_DYNAMIC ){
1167         sqlite3DbFree(pMem->db, (void*)z);
1168       }else{
1169         xDel((void*)z);
1170       }
1171     }
1172     return sqlite3ErrorToParser(pMem->db, SQLITE_TOOBIG);
1173   }
1174 
1175   /* The following block sets the new values of Mem.z and Mem.xDel. It
1176   ** also sets a flag in local variable "flags" to indicate the memory
1177   ** management (one of MEM_Dyn or MEM_Static).
1178   */
1179   if( xDel==SQLITE_TRANSIENT ){
1180     i64 nAlloc = nByte;
1181     if( flags&MEM_Term ){
1182       nAlloc += (enc==SQLITE_UTF8?1:2);
1183     }
1184     testcase( nAlloc==0 );
1185     testcase( nAlloc==31 );
1186     testcase( nAlloc==32 );
1187     if( sqlite3VdbeMemClearAndResize(pMem, (int)MAX(nAlloc,32)) ){
1188       return SQLITE_NOMEM_BKPT;
1189     }
1190     memcpy(pMem->z, z, nAlloc);
1191   }else{
1192     sqlite3VdbeMemRelease(pMem);
1193     pMem->z = (char *)z;
1194     if( xDel==SQLITE_DYNAMIC ){
1195       pMem->zMalloc = pMem->z;
1196       pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
1197     }else{
1198       pMem->xDel = xDel;
1199       flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
1200     }
1201   }
1202 
1203   pMem->n = (int)(nByte & 0x7fffffff);
1204   pMem->flags = flags;
1205   pMem->enc = enc;
1206 
1207 #ifndef SQLITE_OMIT_UTF16
1208   if( enc>SQLITE_UTF8
1209    && (flags & MEM_Blob)==0
1210    && sqlite3VdbeMemHandleBom(pMem)
1211   ){
1212     return SQLITE_NOMEM_BKPT;
1213   }
1214 #endif
1215 
1216 
1217   return SQLITE_OK;
1218 }
1219 
1220 /*
1221 ** Move data out of a btree key or data field and into a Mem structure.
1222 ** The data is payload from the entry that pCur is currently pointing
1223 ** to.  offset and amt determine what portion of the data or key to retrieve.
1224 ** The result is written into the pMem element.
1225 **
1226 ** The pMem object must have been initialized.  This routine will use
1227 ** pMem->zMalloc to hold the content from the btree, if possible.  New
1228 ** pMem->zMalloc space will be allocated if necessary.  The calling routine
1229 ** is responsible for making sure that the pMem object is eventually
1230 ** destroyed.
1231 **
1232 ** If this routine fails for any reason (malloc returns NULL or unable
1233 ** to read from the disk) then the pMem is left in an inconsistent state.
1234 */
1235 int sqlite3VdbeMemFromBtree(
1236   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
1237   u32 offset,       /* Offset from the start of data to return bytes from. */
1238   u32 amt,          /* Number of bytes to return. */
1239   Mem *pMem         /* OUT: Return data in this Mem structure. */
1240 ){
1241   int rc;
1242   pMem->flags = MEM_Null;
1243   if( sqlite3BtreeMaxRecordSize(pCur)<offset+amt ){
1244     return SQLITE_CORRUPT_BKPT;
1245   }
1246   if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+1)) ){
1247     rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);
1248     if( rc==SQLITE_OK ){
1249       pMem->z[amt] = 0;   /* Overrun area used when reading malformed records */
1250       pMem->flags = MEM_Blob;
1251       pMem->n = (int)amt;
1252     }else{
1253       sqlite3VdbeMemRelease(pMem);
1254     }
1255   }
1256   return rc;
1257 }
1258 int sqlite3VdbeMemFromBtreeZeroOffset(
1259   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
1260   u32 amt,          /* Number of bytes to return. */
1261   Mem *pMem         /* OUT: Return data in this Mem structure. */
1262 ){
1263   u32 available = 0;  /* Number of bytes available on the local btree page */
1264   int rc = SQLITE_OK; /* Return code */
1265 
1266   assert( sqlite3BtreeCursorIsValid(pCur) );
1267   assert( !VdbeMemDynamic(pMem) );
1268 
1269   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
1270   ** that both the BtShared and database handle mutexes are held. */
1271   assert( !sqlite3VdbeMemIsRowSet(pMem) );
1272   pMem->z = (char *)sqlite3BtreePayloadFetch(pCur, &available);
1273   assert( pMem->z!=0 );
1274 
1275   if( amt<=available ){
1276     pMem->flags = MEM_Blob|MEM_Ephem;
1277     pMem->n = (int)amt;
1278   }else{
1279     rc = sqlite3VdbeMemFromBtree(pCur, 0, amt, pMem);
1280   }
1281 
1282   return rc;
1283 }
1284 
1285 /*
1286 ** The pVal argument is known to be a value other than NULL.
1287 ** Convert it into a string with encoding enc and return a pointer
1288 ** to a zero-terminated version of that string.
1289 */
1290 static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
1291   assert( pVal!=0 );
1292   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
1293   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
1294   assert( !sqlite3VdbeMemIsRowSet(pVal) );
1295   assert( (pVal->flags & (MEM_Null))==0 );
1296   if( pVal->flags & (MEM_Blob|MEM_Str) ){
1297     if( ExpandBlob(pVal) ) return 0;
1298     pVal->flags |= MEM_Str;
1299     if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
1300       sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
1301     }
1302     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
1303       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
1304       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
1305         return 0;
1306       }
1307     }
1308     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
1309   }else{
1310     sqlite3VdbeMemStringify(pVal, enc, 0);
1311     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
1312   }
1313   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
1314               || pVal->db->mallocFailed );
1315   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
1316     assert( sqlite3VdbeMemValidStrRep(pVal) );
1317     return pVal->z;
1318   }else{
1319     return 0;
1320   }
1321 }
1322 
1323 /* This function is only available internally, it is not part of the
1324 ** external API. It works in a similar way to sqlite3_value_text(),
1325 ** except the data returned is in the encoding specified by the second
1326 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
1327 ** SQLITE_UTF8.
1328 **
1329 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
1330 ** If that is the case, then the result must be aligned on an even byte
1331 ** boundary.
1332 */
1333 const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
1334   if( !pVal ) return 0;
1335   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
1336   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
1337   assert( !sqlite3VdbeMemIsRowSet(pVal) );
1338   if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
1339     assert( sqlite3VdbeMemValidStrRep(pVal) );
1340     return pVal->z;
1341   }
1342   if( pVal->flags&MEM_Null ){
1343     return 0;
1344   }
1345   return valueToText(pVal, enc);
1346 }
1347 
1348 /*
1349 ** Create a new sqlite3_value object.
1350 */
1351 sqlite3_value *sqlite3ValueNew(sqlite3 *db){
1352   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
1353   if( p ){
1354     p->flags = MEM_Null;
1355     p->db = db;
1356   }
1357   return p;
1358 }
1359 
1360 /*
1361 ** Context object passed by sqlite3Stat4ProbeSetValue() through to
1362 ** valueNew(). See comments above valueNew() for details.
1363 */
1364 struct ValueNewStat4Ctx {
1365   Parse *pParse;
1366   Index *pIdx;
1367   UnpackedRecord **ppRec;
1368   int iVal;
1369 };
1370 
1371 /*
1372 ** Allocate and return a pointer to a new sqlite3_value object. If
1373 ** the second argument to this function is NULL, the object is allocated
1374 ** by calling sqlite3ValueNew().
1375 **
1376 ** Otherwise, if the second argument is non-zero, then this function is
1377 ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
1378 ** already been allocated, allocate the UnpackedRecord structure that
1379 ** that function will return to its caller here. Then return a pointer to
1380 ** an sqlite3_value within the UnpackedRecord.a[] array.
1381 */
1382 static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
1383 #ifdef SQLITE_ENABLE_STAT4
1384   if( p ){
1385     UnpackedRecord *pRec = p->ppRec[0];
1386 
1387     if( pRec==0 ){
1388       Index *pIdx = p->pIdx;      /* Index being probed */
1389       int nByte;                  /* Bytes of space to allocate */
1390       int i;                      /* Counter variable */
1391       int nCol = pIdx->nColumn;   /* Number of index columns including rowid */
1392 
1393       nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
1394       pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
1395       if( pRec ){
1396         pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
1397         if( pRec->pKeyInfo ){
1398           assert( pRec->pKeyInfo->nAllField==nCol );
1399           assert( pRec->pKeyInfo->enc==ENC(db) );
1400           pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
1401           for(i=0; i<nCol; i++){
1402             pRec->aMem[i].flags = MEM_Null;
1403             pRec->aMem[i].db = db;
1404           }
1405         }else{
1406           sqlite3DbFreeNN(db, pRec);
1407           pRec = 0;
1408         }
1409       }
1410       if( pRec==0 ) return 0;
1411       p->ppRec[0] = pRec;
1412     }
1413 
1414     pRec->nField = p->iVal+1;
1415     return &pRec->aMem[p->iVal];
1416   }
1417 #else
1418   UNUSED_PARAMETER(p);
1419 #endif /* defined(SQLITE_ENABLE_STAT4) */
1420   return sqlite3ValueNew(db);
1421 }
1422 
1423 /*
1424 ** The expression object indicated by the second argument is guaranteed
1425 ** to be a scalar SQL function. If
1426 **
1427 **   * all function arguments are SQL literals,
1428 **   * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
1429 **   * the SQLITE_FUNC_NEEDCOLL function flag is not set,
1430 **
1431 ** then this routine attempts to invoke the SQL function. Assuming no
1432 ** error occurs, output parameter (*ppVal) is set to point to a value
1433 ** object containing the result before returning SQLITE_OK.
1434 **
1435 ** Affinity aff is applied to the result of the function before returning.
1436 ** If the result is a text value, the sqlite3_value object uses encoding
1437 ** enc.
1438 **
1439 ** If the conditions above are not met, this function returns SQLITE_OK
1440 ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
1441 ** NULL and an SQLite error code returned.
1442 */
1443 #ifdef SQLITE_ENABLE_STAT4
1444 static int valueFromFunction(
1445   sqlite3 *db,                    /* The database connection */
1446   const Expr *p,                  /* The expression to evaluate */
1447   u8 enc,                         /* Encoding to use */
1448   u8 aff,                         /* Affinity to use */
1449   sqlite3_value **ppVal,          /* Write the new value here */
1450   struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
1451 ){
1452   sqlite3_context ctx;            /* Context object for function invocation */
1453   sqlite3_value **apVal = 0;      /* Function arguments */
1454   int nVal = 0;                   /* Size of apVal[] array */
1455   FuncDef *pFunc = 0;             /* Function definition */
1456   sqlite3_value *pVal = 0;        /* New value */
1457   int rc = SQLITE_OK;             /* Return code */
1458   ExprList *pList = 0;            /* Function arguments */
1459   int i;                          /* Iterator variable */
1460 
1461   assert( pCtx!=0 );
1462   assert( (p->flags & EP_TokenOnly)==0 );
1463   assert( ExprUseXList(p) );
1464   pList = p->x.pList;
1465   if( pList ) nVal = pList->nExpr;
1466   assert( !ExprHasProperty(p, EP_IntValue) );
1467   pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
1468   assert( pFunc );
1469   if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
1470    || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
1471   ){
1472     return SQLITE_OK;
1473   }
1474 
1475   if( pList ){
1476     apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
1477     if( apVal==0 ){
1478       rc = SQLITE_NOMEM_BKPT;
1479       goto value_from_function_out;
1480     }
1481     for(i=0; i<nVal; i++){
1482       rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
1483       if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
1484     }
1485   }
1486 
1487   pVal = valueNew(db, pCtx);
1488   if( pVal==0 ){
1489     rc = SQLITE_NOMEM_BKPT;
1490     goto value_from_function_out;
1491   }
1492 
1493   assert( pCtx->pParse->rc==SQLITE_OK );
1494   memset(&ctx, 0, sizeof(ctx));
1495   ctx.pOut = pVal;
1496   ctx.pFunc = pFunc;
1497   pFunc->xSFunc(&ctx, nVal, apVal);
1498   if( ctx.isError ){
1499     rc = ctx.isError;
1500     sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
1501   }else{
1502     sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
1503     assert( rc==SQLITE_OK );
1504     rc = sqlite3VdbeChangeEncoding(pVal, enc);
1505     if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
1506       rc = SQLITE_TOOBIG;
1507       pCtx->pParse->nErr++;
1508     }
1509   }
1510   pCtx->pParse->rc = rc;
1511 
1512  value_from_function_out:
1513   if( rc!=SQLITE_OK ){
1514     pVal = 0;
1515   }
1516   if( apVal ){
1517     for(i=0; i<nVal; i++){
1518       sqlite3ValueFree(apVal[i]);
1519     }
1520     sqlite3DbFreeNN(db, apVal);
1521   }
1522 
1523   *ppVal = pVal;
1524   return rc;
1525 }
1526 #else
1527 # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
1528 #endif /* defined(SQLITE_ENABLE_STAT4) */
1529 
1530 /*
1531 ** Extract a value from the supplied expression in the manner described
1532 ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
1533 ** using valueNew().
1534 **
1535 ** If pCtx is NULL and an error occurs after the sqlite3_value object
1536 ** has been allocated, it is freed before returning. Or, if pCtx is not
1537 ** NULL, it is assumed that the caller will free any allocated object
1538 ** in all cases.
1539 */
1540 static int valueFromExpr(
1541   sqlite3 *db,                    /* The database connection */
1542   const Expr *pExpr,              /* The expression to evaluate */
1543   u8 enc,                         /* Encoding to use */
1544   u8 affinity,                    /* Affinity to use */
1545   sqlite3_value **ppVal,          /* Write the new value here */
1546   struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
1547 ){
1548   int op;
1549   char *zVal = 0;
1550   sqlite3_value *pVal = 0;
1551   int negInt = 1;
1552   const char *zNeg = "";
1553   int rc = SQLITE_OK;
1554 
1555   assert( pExpr!=0 );
1556   while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
1557   if( op==TK_REGISTER ) op = pExpr->op2;
1558 
1559   /* Compressed expressions only appear when parsing the DEFAULT clause
1560   ** on a table column definition, and hence only when pCtx==0.  This
1561   ** check ensures that an EP_TokenOnly expression is never passed down
1562   ** into valueFromFunction(). */
1563   assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
1564 
1565   if( op==TK_CAST ){
1566     u8 aff;
1567     assert( !ExprHasProperty(pExpr, EP_IntValue) );
1568     aff = sqlite3AffinityType(pExpr->u.zToken,0);
1569     rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
1570     testcase( rc!=SQLITE_OK );
1571     if( *ppVal ){
1572       sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
1573       sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
1574     }
1575     return rc;
1576   }
1577 
1578   /* Handle negative integers in a single step.  This is needed in the
1579   ** case when the value is -9223372036854775808.
1580   */
1581   if( op==TK_UMINUS
1582    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
1583     pExpr = pExpr->pLeft;
1584     op = pExpr->op;
1585     negInt = -1;
1586     zNeg = "-";
1587   }
1588 
1589   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
1590     pVal = valueNew(db, pCtx);
1591     if( pVal==0 ) goto no_mem;
1592     if( ExprHasProperty(pExpr, EP_IntValue) ){
1593       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
1594     }else{
1595       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
1596       if( zVal==0 ) goto no_mem;
1597       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
1598     }
1599     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
1600       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
1601     }else{
1602       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
1603     }
1604     assert( (pVal->flags & MEM_IntReal)==0 );
1605     if( pVal->flags & (MEM_Int|MEM_IntReal|MEM_Real) ){
1606       testcase( pVal->flags & MEM_Int );
1607       testcase( pVal->flags & MEM_Real );
1608       pVal->flags &= ~MEM_Str;
1609     }
1610     if( enc!=SQLITE_UTF8 ){
1611       rc = sqlite3VdbeChangeEncoding(pVal, enc);
1612     }
1613   }else if( op==TK_UMINUS ) {
1614     /* This branch happens for multiple negative signs.  Ex: -(-5) */
1615     if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx)
1616      && pVal!=0
1617     ){
1618       sqlite3VdbeMemNumerify(pVal);
1619       if( pVal->flags & MEM_Real ){
1620         pVal->u.r = -pVal->u.r;
1621       }else if( pVal->u.i==SMALLEST_INT64 ){
1622 #ifndef SQLITE_OMIT_FLOATING_POINT
1623         pVal->u.r = -(double)SMALLEST_INT64;
1624 #else
1625         pVal->u.r = LARGEST_INT64;
1626 #endif
1627         MemSetTypeFlag(pVal, MEM_Real);
1628       }else{
1629         pVal->u.i = -pVal->u.i;
1630       }
1631       sqlite3ValueApplyAffinity(pVal, affinity, enc);
1632     }
1633   }else if( op==TK_NULL ){
1634     pVal = valueNew(db, pCtx);
1635     if( pVal==0 ) goto no_mem;
1636     sqlite3VdbeMemSetNull(pVal);
1637   }
1638 #ifndef SQLITE_OMIT_BLOB_LITERAL
1639   else if( op==TK_BLOB ){
1640     int nVal;
1641     assert( !ExprHasProperty(pExpr, EP_IntValue) );
1642     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
1643     assert( pExpr->u.zToken[1]=='\'' );
1644     pVal = valueNew(db, pCtx);
1645     if( !pVal ) goto no_mem;
1646     zVal = &pExpr->u.zToken[2];
1647     nVal = sqlite3Strlen30(zVal)-1;
1648     assert( zVal[nVal]=='\'' );
1649     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
1650                          0, SQLITE_DYNAMIC);
1651   }
1652 #endif
1653 #ifdef SQLITE_ENABLE_STAT4
1654   else if( op==TK_FUNCTION && pCtx!=0 ){
1655     rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
1656   }
1657 #endif
1658   else if( op==TK_TRUEFALSE ){
1659     assert( !ExprHasProperty(pExpr, EP_IntValue) );
1660     pVal = valueNew(db, pCtx);
1661     if( pVal ){
1662       pVal->flags = MEM_Int;
1663       pVal->u.i = pExpr->u.zToken[4]==0;
1664     }
1665   }
1666 
1667   *ppVal = pVal;
1668   return rc;
1669 
1670 no_mem:
1671 #ifdef SQLITE_ENABLE_STAT4
1672   if( pCtx==0 || NEVER(pCtx->pParse->nErr==0) )
1673 #endif
1674     sqlite3OomFault(db);
1675   sqlite3DbFree(db, zVal);
1676   assert( *ppVal==0 );
1677 #ifdef SQLITE_ENABLE_STAT4
1678   if( pCtx==0 ) sqlite3ValueFree(pVal);
1679 #else
1680   assert( pCtx==0 ); sqlite3ValueFree(pVal);
1681 #endif
1682   return SQLITE_NOMEM_BKPT;
1683 }
1684 
1685 /*
1686 ** Create a new sqlite3_value object, containing the value of pExpr.
1687 **
1688 ** This only works for very simple expressions that consist of one constant
1689 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
1690 ** be converted directly into a value, then the value is allocated and
1691 ** a pointer written to *ppVal. The caller is responsible for deallocating
1692 ** the value by passing it to sqlite3ValueFree() later on. If the expression
1693 ** cannot be converted to a value, then *ppVal is set to NULL.
1694 */
1695 int sqlite3ValueFromExpr(
1696   sqlite3 *db,              /* The database connection */
1697   const Expr *pExpr,        /* The expression to evaluate */
1698   u8 enc,                   /* Encoding to use */
1699   u8 affinity,              /* Affinity to use */
1700   sqlite3_value **ppVal     /* Write the new value here */
1701 ){
1702   return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0;
1703 }
1704 
1705 #ifdef SQLITE_ENABLE_STAT4
1706 /*
1707 ** Attempt to extract a value from pExpr and use it to construct *ppVal.
1708 **
1709 ** If pAlloc is not NULL, then an UnpackedRecord object is created for
1710 ** pAlloc if one does not exist and the new value is added to the
1711 ** UnpackedRecord object.
1712 **
1713 ** A value is extracted in the following cases:
1714 **
1715 **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
1716 **
1717 **  * The expression is a bound variable, and this is a reprepare, or
1718 **
1719 **  * The expression is a literal value.
1720 **
1721 ** On success, *ppVal is made to point to the extracted value.  The caller
1722 ** is responsible for ensuring that the value is eventually freed.
1723 */
1724 static int stat4ValueFromExpr(
1725   Parse *pParse,                  /* Parse context */
1726   Expr *pExpr,                    /* The expression to extract a value from */
1727   u8 affinity,                    /* Affinity to use */
1728   struct ValueNewStat4Ctx *pAlloc,/* How to allocate space.  Or NULL */
1729   sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
1730 ){
1731   int rc = SQLITE_OK;
1732   sqlite3_value *pVal = 0;
1733   sqlite3 *db = pParse->db;
1734 
1735   /* Skip over any TK_COLLATE nodes */
1736   pExpr = sqlite3ExprSkipCollate(pExpr);
1737 
1738   assert( pExpr==0 || pExpr->op!=TK_REGISTER || pExpr->op2!=TK_VARIABLE );
1739   if( !pExpr ){
1740     pVal = valueNew(db, pAlloc);
1741     if( pVal ){
1742       sqlite3VdbeMemSetNull((Mem*)pVal);
1743     }
1744   }else if( pExpr->op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
1745     Vdbe *v;
1746     int iBindVar = pExpr->iColumn;
1747     sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
1748     if( (v = pParse->pReprepare)!=0 ){
1749       pVal = valueNew(db, pAlloc);
1750       if( pVal ){
1751         rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
1752         sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
1753         pVal->db = pParse->db;
1754       }
1755     }
1756   }else{
1757     rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
1758   }
1759 
1760   assert( pVal==0 || pVal->db==db );
1761   *ppVal = pVal;
1762   return rc;
1763 }
1764 
1765 /*
1766 ** This function is used to allocate and populate UnpackedRecord
1767 ** structures intended to be compared against sample index keys stored
1768 ** in the sqlite_stat4 table.
1769 **
1770 ** A single call to this function populates zero or more fields of the
1771 ** record starting with field iVal (fields are numbered from left to
1772 ** right starting with 0). A single field is populated if:
1773 **
1774 **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
1775 **
1776 **  * The expression is a bound variable, and this is a reprepare, or
1777 **
1778 **  * The sqlite3ValueFromExpr() function is able to extract a value
1779 **    from the expression (i.e. the expression is a literal value).
1780 **
1781 ** Or, if pExpr is a TK_VECTOR, one field is populated for each of the
1782 ** vector components that match either of the two latter criteria listed
1783 ** above.
1784 **
1785 ** Before any value is appended to the record, the affinity of the
1786 ** corresponding column within index pIdx is applied to it. Before
1787 ** this function returns, output parameter *pnExtract is set to the
1788 ** number of values appended to the record.
1789 **
1790 ** When this function is called, *ppRec must either point to an object
1791 ** allocated by an earlier call to this function, or must be NULL. If it
1792 ** is NULL and a value can be successfully extracted, a new UnpackedRecord
1793 ** is allocated (and *ppRec set to point to it) before returning.
1794 **
1795 ** Unless an error is encountered, SQLITE_OK is returned. It is not an
1796 ** error if a value cannot be extracted from pExpr. If an error does
1797 ** occur, an SQLite error code is returned.
1798 */
1799 int sqlite3Stat4ProbeSetValue(
1800   Parse *pParse,                  /* Parse context */
1801   Index *pIdx,                    /* Index being probed */
1802   UnpackedRecord **ppRec,         /* IN/OUT: Probe record */
1803   Expr *pExpr,                    /* The expression to extract a value from */
1804   int nElem,                      /* Maximum number of values to append */
1805   int iVal,                       /* Array element to populate */
1806   int *pnExtract                  /* OUT: Values appended to the record */
1807 ){
1808   int rc = SQLITE_OK;
1809   int nExtract = 0;
1810 
1811   if( pExpr==0 || pExpr->op!=TK_SELECT ){
1812     int i;
1813     struct ValueNewStat4Ctx alloc;
1814 
1815     alloc.pParse = pParse;
1816     alloc.pIdx = pIdx;
1817     alloc.ppRec = ppRec;
1818 
1819     for(i=0; i<nElem; i++){
1820       sqlite3_value *pVal = 0;
1821       Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0);
1822       u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
1823       alloc.iVal = iVal+i;
1824       rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal);
1825       if( !pVal ) break;
1826       nExtract++;
1827     }
1828   }
1829 
1830   *pnExtract = nExtract;
1831   return rc;
1832 }
1833 
1834 /*
1835 ** Attempt to extract a value from expression pExpr using the methods
1836 ** as described for sqlite3Stat4ProbeSetValue() above.
1837 **
1838 ** If successful, set *ppVal to point to a new value object and return
1839 ** SQLITE_OK. If no value can be extracted, but no other error occurs
1840 ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
1841 ** does occur, return an SQLite error code. The final value of *ppVal
1842 ** is undefined in this case.
1843 */
1844 int sqlite3Stat4ValueFromExpr(
1845   Parse *pParse,                  /* Parse context */
1846   Expr *pExpr,                    /* The expression to extract a value from */
1847   u8 affinity,                    /* Affinity to use */
1848   sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
1849 ){
1850   return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
1851 }
1852 
1853 /*
1854 ** Extract the iCol-th column from the nRec-byte record in pRec.  Write
1855 ** the column value into *ppVal.  If *ppVal is initially NULL then a new
1856 ** sqlite3_value object is allocated.
1857 **
1858 ** If *ppVal is initially NULL then the caller is responsible for
1859 ** ensuring that the value written into *ppVal is eventually freed.
1860 */
1861 int sqlite3Stat4Column(
1862   sqlite3 *db,                    /* Database handle */
1863   const void *pRec,               /* Pointer to buffer containing record */
1864   int nRec,                       /* Size of buffer pRec in bytes */
1865   int iCol,                       /* Column to extract */
1866   sqlite3_value **ppVal           /* OUT: Extracted value */
1867 ){
1868   u32 t = 0;                      /* a column type code */
1869   int nHdr;                       /* Size of the header in the record */
1870   int iHdr;                       /* Next unread header byte */
1871   int iField;                     /* Next unread data byte */
1872   int szField = 0;                /* Size of the current data field */
1873   int i;                          /* Column index */
1874   u8 *a = (u8*)pRec;              /* Typecast byte array */
1875   Mem *pMem = *ppVal;             /* Write result into this Mem object */
1876 
1877   assert( iCol>0 );
1878   iHdr = getVarint32(a, nHdr);
1879   if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
1880   iField = nHdr;
1881   for(i=0; i<=iCol; i++){
1882     iHdr += getVarint32(&a[iHdr], t);
1883     testcase( iHdr==nHdr );
1884     testcase( iHdr==nHdr+1 );
1885     if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
1886     szField = sqlite3VdbeSerialTypeLen(t);
1887     iField += szField;
1888   }
1889   testcase( iField==nRec );
1890   testcase( iField==nRec+1 );
1891   if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
1892   if( pMem==0 ){
1893     pMem = *ppVal = sqlite3ValueNew(db);
1894     if( pMem==0 ) return SQLITE_NOMEM_BKPT;
1895   }
1896   sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
1897   pMem->enc = ENC(db);
1898   return SQLITE_OK;
1899 }
1900 
1901 /*
1902 ** Unless it is NULL, the argument must be an UnpackedRecord object returned
1903 ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
1904 ** the object.
1905 */
1906 void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
1907   if( pRec ){
1908     int i;
1909     int nCol = pRec->pKeyInfo->nAllField;
1910     Mem *aMem = pRec->aMem;
1911     sqlite3 *db = aMem[0].db;
1912     for(i=0; i<nCol; i++){
1913       sqlite3VdbeMemRelease(&aMem[i]);
1914     }
1915     sqlite3KeyInfoUnref(pRec->pKeyInfo);
1916     sqlite3DbFreeNN(db, pRec);
1917   }
1918 }
1919 #endif /* ifdef SQLITE_ENABLE_STAT4 */
1920 
1921 /*
1922 ** Change the string value of an sqlite3_value object
1923 */
1924 void sqlite3ValueSetStr(
1925   sqlite3_value *v,     /* Value to be set */
1926   int n,                /* Length of string z */
1927   const void *z,        /* Text of the new string */
1928   u8 enc,               /* Encoding to use */
1929   void (*xDel)(void*)   /* Destructor for the string */
1930 ){
1931   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
1932 }
1933 
1934 /*
1935 ** Free an sqlite3_value object
1936 */
1937 void sqlite3ValueFree(sqlite3_value *v){
1938   if( !v ) return;
1939   sqlite3VdbeMemRelease((Mem *)v);
1940   sqlite3DbFreeNN(((Mem*)v)->db, v);
1941 }
1942 
1943 /*
1944 ** The sqlite3ValueBytes() routine returns the number of bytes in the
1945 ** sqlite3_value object assuming that it uses the encoding "enc".
1946 ** The valueBytes() routine is a helper function.
1947 */
1948 static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
1949   return valueToText(pVal, enc)!=0 ? pVal->n : 0;
1950 }
1951 int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
1952   Mem *p = (Mem*)pVal;
1953   assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
1954   if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
1955     return p->n;
1956   }
1957   if( (p->flags & MEM_Blob)!=0 ){
1958     if( p->flags & MEM_Zero ){
1959       return p->n + p->u.nZero;
1960     }else{
1961       return p->n;
1962     }
1963   }
1964   if( p->flags & MEM_Null ) return 0;
1965   return valueBytes(pVal, enc);
1966 }
1967