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