xref: /sqlite-3.40.0/src/vdbemem.c (revision a3fdec71)
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 /*
22 ** If pMem is an object with a valid string representation, this routine
23 ** ensures the internal encoding for the string representation is
24 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
25 **
26 ** If pMem is not a string object, or the encoding of the string
27 ** representation is already stored using the requested encoding, then this
28 ** routine is a no-op.
29 **
30 ** SQLITE_OK is returned if the conversion is successful (or not required).
31 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
32 ** between formats.
33 */
34 int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
35 #ifndef SQLITE_OMIT_UTF16
36   int rc;
37 #endif
38   assert( (pMem->flags&MEM_RowSet)==0 );
39   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
40            || desiredEnc==SQLITE_UTF16BE );
41   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
42     return SQLITE_OK;
43   }
44   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
45 #ifdef SQLITE_OMIT_UTF16
46   return SQLITE_ERROR;
47 #else
48 
49   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
50   ** then the encoding of the value may not have changed.
51   */
52   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
53   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
54   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
55   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
56   return rc;
57 #endif
58 }
59 
60 /*
61 ** Make sure pMem->z points to a writable allocation of at least
62 ** min(n,32) bytes.
63 **
64 ** If the bPreserve argument is true, then copy of the content of
65 ** pMem->z into the new allocation.  pMem must be either a string or
66 ** blob if bPreserve is true.  If bPreserve is false, any prior content
67 ** in pMem->z is discarded.
68 */
69 int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
70   assert( 1 >=
71     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
72     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
73     ((pMem->flags&MEM_Ephem) ? 1 : 0) +
74     ((pMem->flags&MEM_Static) ? 1 : 0)
75   );
76   assert( (pMem->flags&MEM_RowSet)==0 );
77 
78   /* If the bPreserve flag is set to true, then the memory cell must already
79   ** contain a valid string or blob value.  */
80   assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
81   testcase( bPreserve && pMem->z==0 );
82 
83   if( pMem->zMalloc==0 || sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
84     if( n<32 ) n = 32;
85     if( bPreserve && pMem->z==pMem->zMalloc ){
86       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
87       bPreserve = 0;
88     }else{
89       sqlite3DbFree(pMem->db, pMem->zMalloc);
90       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
91     }
92     if( pMem->zMalloc==0 ){
93       sqlite3VdbeMemRelease(pMem);
94       pMem->flags = MEM_Null;
95       return SQLITE_NOMEM;
96     }
97   }
98 
99   if( pMem->z && bPreserve && pMem->z!=pMem->zMalloc ){
100     memcpy(pMem->zMalloc, pMem->z, pMem->n);
101   }
102   if( (pMem->flags&MEM_Dyn)!=0 && pMem->xDel ){
103     assert( pMem->xDel!=SQLITE_DYNAMIC );
104     pMem->xDel((void *)(pMem->z));
105   }
106 
107   pMem->z = pMem->zMalloc;
108   pMem->flags &= ~(MEM_Ephem|MEM_Static);
109   pMem->xDel = 0;
110   return SQLITE_OK;
111 }
112 
113 /*
114 ** Make the given Mem object MEM_Dyn.  In other words, make it so
115 ** that any TEXT or BLOB content is stored in memory obtained from
116 ** malloc().  In this way, we know that the memory is safe to be
117 ** overwritten or altered.
118 **
119 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
120 */
121 int sqlite3VdbeMemMakeWriteable(Mem *pMem){
122   int f;
123   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
124   assert( (pMem->flags&MEM_RowSet)==0 );
125   ExpandBlob(pMem);
126   f = pMem->flags;
127   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
128     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
129       return SQLITE_NOMEM;
130     }
131     pMem->z[pMem->n] = 0;
132     pMem->z[pMem->n+1] = 0;
133     pMem->flags |= MEM_Term;
134 #ifdef SQLITE_DEBUG
135     pMem->pScopyFrom = 0;
136 #endif
137   }
138 
139   return SQLITE_OK;
140 }
141 
142 /*
143 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
144 ** blob stored in dynamically allocated space.
145 */
146 #ifndef SQLITE_OMIT_INCRBLOB
147 int sqlite3VdbeMemExpandBlob(Mem *pMem){
148   if( pMem->flags & MEM_Zero ){
149     int nByte;
150     assert( pMem->flags&MEM_Blob );
151     assert( (pMem->flags&MEM_RowSet)==0 );
152     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
153 
154     /* Set nByte to the number of bytes required to store the expanded blob. */
155     nByte = pMem->n + pMem->u.nZero;
156     if( nByte<=0 ){
157       nByte = 1;
158     }
159     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
160       return SQLITE_NOMEM;
161     }
162 
163     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
164     pMem->n += pMem->u.nZero;
165     pMem->flags &= ~(MEM_Zero|MEM_Term);
166   }
167   return SQLITE_OK;
168 }
169 #endif
170 
171 
172 /*
173 ** Make sure the given Mem is \u0000 terminated.
174 */
175 int sqlite3VdbeMemNulTerminate(Mem *pMem){
176   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
177   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
178     return SQLITE_OK;   /* Nothing to do */
179   }
180   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
181     return SQLITE_NOMEM;
182   }
183   pMem->z[pMem->n] = 0;
184   pMem->z[pMem->n+1] = 0;
185   pMem->flags |= MEM_Term;
186   return SQLITE_OK;
187 }
188 
189 /*
190 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
191 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
192 ** is a no-op.
193 **
194 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
195 **
196 ** A MEM_Null value will never be passed to this function. This function is
197 ** used for converting values to text for returning to the user (i.e. via
198 ** sqlite3_value_text()), or for ensuring that values to be used as btree
199 ** keys are strings. In the former case a NULL pointer is returned the
200 ** user and the later is an internal programming error.
201 */
202 int sqlite3VdbeMemStringify(Mem *pMem, int enc){
203   int rc = SQLITE_OK;
204   int fg = pMem->flags;
205   const int nByte = 32;
206 
207   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
208   assert( !(fg&MEM_Zero) );
209   assert( !(fg&(MEM_Str|MEM_Blob)) );
210   assert( fg&(MEM_Int|MEM_Real) );
211   assert( (pMem->flags&MEM_RowSet)==0 );
212   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
213 
214 
215   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
216     return SQLITE_NOMEM;
217   }
218 
219   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
220   ** string representation of the value. Then, if the required encoding
221   ** is UTF-16le or UTF-16be do a translation.
222   **
223   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
224   */
225   if( fg & MEM_Int ){
226     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
227   }else{
228     assert( fg & MEM_Real );
229     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
230   }
231   pMem->n = sqlite3Strlen30(pMem->z);
232   pMem->enc = SQLITE_UTF8;
233   pMem->flags |= MEM_Str|MEM_Term;
234   sqlite3VdbeChangeEncoding(pMem, enc);
235   return rc;
236 }
237 
238 /*
239 ** Memory cell pMem contains the context of an aggregate function.
240 ** This routine calls the finalize method for that function.  The
241 ** result of the aggregate is stored back into pMem.
242 **
243 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
244 ** otherwise.
245 */
246 int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
247   int rc = SQLITE_OK;
248   if( ALWAYS(pFunc && pFunc->xFinalize) ){
249     sqlite3_context ctx;
250     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
251     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
252     memset(&ctx, 0, sizeof(ctx));
253     ctx.s.flags = MEM_Null;
254     ctx.s.db = pMem->db;
255     ctx.pMem = pMem;
256     ctx.pFunc = pFunc;
257     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
258     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
259     sqlite3DbFree(pMem->db, pMem->zMalloc);
260     memcpy(pMem, &ctx.s, sizeof(ctx.s));
261     rc = ctx.isError;
262   }
263   return rc;
264 }
265 
266 /*
267 ** If the memory cell contains a string value that must be freed by
268 ** invoking an external callback, free it now. Calling this function
269 ** does not free any Mem.zMalloc buffer.
270 */
271 void sqlite3VdbeMemReleaseExternal(Mem *p){
272   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
273   if( p->flags&MEM_Agg ){
274     sqlite3VdbeMemFinalize(p, p->u.pDef);
275     assert( (p->flags & MEM_Agg)==0 );
276     sqlite3VdbeMemRelease(p);
277   }else if( p->flags&MEM_Dyn && p->xDel ){
278     assert( (p->flags&MEM_RowSet)==0 );
279     assert( p->xDel!=SQLITE_DYNAMIC );
280     p->xDel((void *)p->z);
281     p->xDel = 0;
282   }else if( p->flags&MEM_RowSet ){
283     sqlite3RowSetClear(p->u.pRowSet);
284   }else if( p->flags&MEM_Frame ){
285     sqlite3VdbeMemSetNull(p);
286   }
287 }
288 
289 /*
290 ** Release any memory held by the Mem. This may leave the Mem in an
291 ** inconsistent state, for example with (Mem.z==0) and
292 ** (Mem.type==SQLITE_TEXT).
293 */
294 void sqlite3VdbeMemRelease(Mem *p){
295   VdbeMemRelease(p);
296   if( p->zMalloc ){
297     sqlite3DbFree(p->db, p->zMalloc);
298     p->zMalloc = 0;
299   }
300   p->z = 0;
301   assert( p->xDel==0 );  /* Zeroed by VdbeMemRelease() above */
302 }
303 
304 /*
305 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
306 ** If the double is out of range of a 64-bit signed integer then
307 ** return the closest available 64-bit signed integer.
308 */
309 static i64 doubleToInt64(double r){
310 #ifdef SQLITE_OMIT_FLOATING_POINT
311   /* When floating-point is omitted, double and int64 are the same thing */
312   return r;
313 #else
314   /*
315   ** Many compilers we encounter do not define constants for the
316   ** minimum and maximum 64-bit integers, or they define them
317   ** inconsistently.  And many do not understand the "LL" notation.
318   ** So we define our own static constants here using nothing
319   ** larger than a 32-bit integer constant.
320   */
321   static const i64 maxInt = LARGEST_INT64;
322   static const i64 minInt = SMALLEST_INT64;
323 
324   if( r<=(double)minInt ){
325     return minInt;
326   }else if( r>=(double)maxInt ){
327     return maxInt;
328   }else{
329     return (i64)r;
330   }
331 #endif
332 }
333 
334 /*
335 ** Return some kind of integer value which is the best we can do
336 ** at representing the value that *pMem describes as an integer.
337 ** If pMem is an integer, then the value is exact.  If pMem is
338 ** a floating-point then the value returned is the integer part.
339 ** If pMem is a string or blob, then we make an attempt to convert
340 ** it into a integer and return that.  If pMem represents an
341 ** an SQL-NULL value, return 0.
342 **
343 ** If pMem represents a string value, its encoding might be changed.
344 */
345 i64 sqlite3VdbeIntValue(Mem *pMem){
346   int flags;
347   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
348   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
349   flags = pMem->flags;
350   if( flags & MEM_Int ){
351     return pMem->u.i;
352   }else if( flags & MEM_Real ){
353     return doubleToInt64(pMem->r);
354   }else if( flags & (MEM_Str|MEM_Blob) ){
355     i64 value = 0;
356     assert( pMem->z || pMem->n==0 );
357     testcase( pMem->z==0 );
358     sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
359     return value;
360   }else{
361     return 0;
362   }
363 }
364 
365 /*
366 ** Return the best representation of pMem that we can get into a
367 ** double.  If pMem is already a double or an integer, return its
368 ** value.  If it is a string or blob, try to convert it to a double.
369 ** If it is a NULL, return 0.0.
370 */
371 double sqlite3VdbeRealValue(Mem *pMem){
372   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
373   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
374   if( pMem->flags & MEM_Real ){
375     return pMem->r;
376   }else if( pMem->flags & MEM_Int ){
377     return (double)pMem->u.i;
378   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
379     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
380     double val = (double)0;
381     sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
382     return val;
383   }else{
384     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
385     return (double)0;
386   }
387 }
388 
389 /*
390 ** The MEM structure is already a MEM_Real.  Try to also make it a
391 ** MEM_Int if we can.
392 */
393 void sqlite3VdbeIntegerAffinity(Mem *pMem){
394   assert( pMem->flags & MEM_Real );
395   assert( (pMem->flags & MEM_RowSet)==0 );
396   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
397   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
398 
399   pMem->u.i = doubleToInt64(pMem->r);
400 
401   /* Only mark the value as an integer if
402   **
403   **    (1) the round-trip conversion real->int->real is a no-op, and
404   **    (2) The integer is neither the largest nor the smallest
405   **        possible integer (ticket #3922)
406   **
407   ** The second and third terms in the following conditional enforces
408   ** the second condition under the assumption that addition overflow causes
409   ** values to wrap around.
410   */
411   if( pMem->r==(double)pMem->u.i
412    && pMem->u.i>SMALLEST_INT64
413    && pMem->u.i<LARGEST_INT64
414   ){
415     pMem->flags |= MEM_Int;
416   }
417 }
418 
419 /*
420 ** Convert pMem to type integer.  Invalidate any prior representations.
421 */
422 int sqlite3VdbeMemIntegerify(Mem *pMem){
423   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
424   assert( (pMem->flags & MEM_RowSet)==0 );
425   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
426 
427   pMem->u.i = sqlite3VdbeIntValue(pMem);
428   MemSetTypeFlag(pMem, MEM_Int);
429   return SQLITE_OK;
430 }
431 
432 /*
433 ** Convert pMem so that it is of type MEM_Real.
434 ** Invalidate any prior representations.
435 */
436 int sqlite3VdbeMemRealify(Mem *pMem){
437   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
438   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
439 
440   pMem->r = sqlite3VdbeRealValue(pMem);
441   MemSetTypeFlag(pMem, MEM_Real);
442   return SQLITE_OK;
443 }
444 
445 /*
446 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
447 ** Invalidate any prior representations.
448 **
449 ** Every effort is made to force the conversion, even if the input
450 ** is a string that does not look completely like a number.  Convert
451 ** as much of the string as we can and ignore the rest.
452 */
453 int sqlite3VdbeMemNumerify(Mem *pMem){
454   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
455     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
456     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
457     if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
458       MemSetTypeFlag(pMem, MEM_Int);
459     }else{
460       pMem->r = sqlite3VdbeRealValue(pMem);
461       MemSetTypeFlag(pMem, MEM_Real);
462       sqlite3VdbeIntegerAffinity(pMem);
463     }
464   }
465   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
466   pMem->flags &= ~(MEM_Str|MEM_Blob);
467   return SQLITE_OK;
468 }
469 
470 /*
471 ** Delete any previous value and set the value stored in *pMem to NULL.
472 */
473 void sqlite3VdbeMemSetNull(Mem *pMem){
474   if( pMem->flags & MEM_Frame ){
475     VdbeFrame *pFrame = pMem->u.pFrame;
476     pFrame->pParent = pFrame->v->pDelFrame;
477     pFrame->v->pDelFrame = pFrame;
478   }
479   if( pMem->flags & MEM_RowSet ){
480     sqlite3RowSetClear(pMem->u.pRowSet);
481   }
482   MemSetTypeFlag(pMem, MEM_Null);
483   pMem->type = SQLITE_NULL;
484 }
485 void sqlite3ValueSetNull(sqlite3_value *p){
486   sqlite3VdbeMemSetNull((Mem*)p);
487 }
488 
489 /*
490 ** Delete any previous value and set the value to be a BLOB of length
491 ** n containing all zeros.
492 */
493 void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
494   sqlite3VdbeMemRelease(pMem);
495   pMem->flags = MEM_Blob|MEM_Zero;
496   pMem->type = SQLITE_BLOB;
497   pMem->n = 0;
498   if( n<0 ) n = 0;
499   pMem->u.nZero = n;
500   pMem->enc = SQLITE_UTF8;
501 
502 #ifdef SQLITE_OMIT_INCRBLOB
503   sqlite3VdbeMemGrow(pMem, n, 0);
504   if( pMem->z ){
505     pMem->n = n;
506     memset(pMem->z, 0, n);
507   }
508 #endif
509 }
510 
511 /*
512 ** Delete any previous value and set the value stored in *pMem to val,
513 ** manifest type INTEGER.
514 */
515 void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
516   sqlite3VdbeMemRelease(pMem);
517   pMem->u.i = val;
518   pMem->flags = MEM_Int;
519   pMem->type = SQLITE_INTEGER;
520 }
521 
522 #ifndef SQLITE_OMIT_FLOATING_POINT
523 /*
524 ** Delete any previous value and set the value stored in *pMem to val,
525 ** manifest type REAL.
526 */
527 void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
528   if( sqlite3IsNaN(val) ){
529     sqlite3VdbeMemSetNull(pMem);
530   }else{
531     sqlite3VdbeMemRelease(pMem);
532     pMem->r = val;
533     pMem->flags = MEM_Real;
534     pMem->type = SQLITE_FLOAT;
535   }
536 }
537 #endif
538 
539 /*
540 ** Delete any previous value and set the value of pMem to be an
541 ** empty boolean index.
542 */
543 void sqlite3VdbeMemSetRowSet(Mem *pMem){
544   sqlite3 *db = pMem->db;
545   assert( db!=0 );
546   assert( (pMem->flags & MEM_RowSet)==0 );
547   sqlite3VdbeMemRelease(pMem);
548   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
549   if( db->mallocFailed ){
550     pMem->flags = MEM_Null;
551   }else{
552     assert( pMem->zMalloc );
553     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
554                                        sqlite3DbMallocSize(db, pMem->zMalloc));
555     assert( pMem->u.pRowSet!=0 );
556     pMem->flags = MEM_RowSet;
557   }
558 }
559 
560 /*
561 ** Return true if the Mem object contains a TEXT or BLOB that is
562 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
563 */
564 int sqlite3VdbeMemTooBig(Mem *p){
565   assert( p->db!=0 );
566   if( p->flags & (MEM_Str|MEM_Blob) ){
567     int n = p->n;
568     if( p->flags & MEM_Zero ){
569       n += p->u.nZero;
570     }
571     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
572   }
573   return 0;
574 }
575 
576 #ifdef SQLITE_DEBUG
577 /*
578 ** This routine prepares a memory cell for modication by breaking
579 ** its link to a shallow copy and by marking any current shallow
580 ** copies of this cell as invalid.
581 **
582 ** This is used for testing and debugging only - to make sure shallow
583 ** copies are not misused.
584 */
585 void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
586   int i;
587   Mem *pX;
588   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
589     if( pX->pScopyFrom==pMem ){
590       pX->flags |= MEM_Invalid;
591       pX->pScopyFrom = 0;
592     }
593   }
594   pMem->pScopyFrom = 0;
595 }
596 #endif /* SQLITE_DEBUG */
597 
598 /*
599 ** Size of struct Mem not including the Mem.zMalloc member.
600 */
601 #define MEMCELLSIZE offsetof(Mem,zMalloc)
602 
603 /*
604 ** Make an shallow copy of pFrom into pTo.  Prior contents of
605 ** pTo are freed.  The pFrom->z field is not duplicated.  If
606 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
607 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
608 */
609 void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
610   assert( (pFrom->flags & MEM_RowSet)==0 );
611   VdbeMemRelease(pTo);
612   memcpy(pTo, pFrom, MEMCELLSIZE);
613   pTo->xDel = 0;
614   if( (pFrom->flags&MEM_Static)==0 ){
615     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
616     assert( srcType==MEM_Ephem || srcType==MEM_Static );
617     pTo->flags |= srcType;
618   }
619 }
620 
621 /*
622 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
623 ** freed before the copy is made.
624 */
625 int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
626   int rc = SQLITE_OK;
627 
628   assert( (pFrom->flags & MEM_RowSet)==0 );
629   VdbeMemRelease(pTo);
630   memcpy(pTo, pFrom, MEMCELLSIZE);
631   pTo->flags &= ~MEM_Dyn;
632 
633   if( pTo->flags&(MEM_Str|MEM_Blob) ){
634     if( 0==(pFrom->flags&MEM_Static) ){
635       pTo->flags |= MEM_Ephem;
636       rc = sqlite3VdbeMemMakeWriteable(pTo);
637     }
638   }
639 
640   return rc;
641 }
642 
643 /*
644 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
645 ** freed. If pFrom contains ephemeral data, a copy is made.
646 **
647 ** pFrom contains an SQL NULL when this routine returns.
648 */
649 void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
650   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
651   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
652   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
653 
654   sqlite3VdbeMemRelease(pTo);
655   memcpy(pTo, pFrom, sizeof(Mem));
656   pFrom->flags = MEM_Null;
657   pFrom->xDel = 0;
658   pFrom->zMalloc = 0;
659 }
660 
661 /*
662 ** Change the value of a Mem to be a string or a BLOB.
663 **
664 ** The memory management strategy depends on the value of the xDel
665 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
666 ** string is copied into a (possibly existing) buffer managed by the
667 ** Mem structure. Otherwise, any existing buffer is freed and the
668 ** pointer copied.
669 **
670 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
671 ** size limit) then no memory allocation occurs.  If the string can be
672 ** stored without allocating memory, then it is.  If a memory allocation
673 ** is required to store the string, then value of pMem is unchanged.  In
674 ** either case, SQLITE_TOOBIG is returned.
675 */
676 int sqlite3VdbeMemSetStr(
677   Mem *pMem,          /* Memory cell to set to string value */
678   const char *z,      /* String pointer */
679   int n,              /* Bytes in string, or negative */
680   u8 enc,             /* Encoding of z.  0 for BLOBs */
681   void (*xDel)(void*) /* Destructor function */
682 ){
683   int nByte = n;      /* New value for pMem->n */
684   int iLimit;         /* Maximum allowed string or blob size */
685   u16 flags = 0;      /* New value for pMem->flags */
686 
687   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
688   assert( (pMem->flags & MEM_RowSet)==0 );
689 
690   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
691   if( !z ){
692     sqlite3VdbeMemSetNull(pMem);
693     return SQLITE_OK;
694   }
695 
696   if( pMem->db ){
697     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
698   }else{
699     iLimit = SQLITE_MAX_LENGTH;
700   }
701   flags = (enc==0?MEM_Blob:MEM_Str);
702   if( nByte<0 ){
703     assert( enc!=0 );
704     if( enc==SQLITE_UTF8 ){
705       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
706     }else{
707       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
708     }
709     flags |= MEM_Term;
710   }
711 
712   /* The following block sets the new values of Mem.z and Mem.xDel. It
713   ** also sets a flag in local variable "flags" to indicate the memory
714   ** management (one of MEM_Dyn or MEM_Static).
715   */
716   if( xDel==SQLITE_TRANSIENT ){
717     int nAlloc = nByte;
718     if( flags&MEM_Term ){
719       nAlloc += (enc==SQLITE_UTF8?1:2);
720     }
721     if( nByte>iLimit ){
722       return SQLITE_TOOBIG;
723     }
724     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
725       return SQLITE_NOMEM;
726     }
727     memcpy(pMem->z, z, nAlloc);
728   }else if( xDel==SQLITE_DYNAMIC ){
729     sqlite3VdbeMemRelease(pMem);
730     pMem->zMalloc = pMem->z = (char *)z;
731     pMem->xDel = 0;
732   }else{
733     sqlite3VdbeMemRelease(pMem);
734     pMem->z = (char *)z;
735     pMem->xDel = xDel;
736     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
737   }
738 
739   pMem->n = nByte;
740   pMem->flags = flags;
741   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
742   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
743 
744 #ifndef SQLITE_OMIT_UTF16
745   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
746     return SQLITE_NOMEM;
747   }
748 #endif
749 
750   if( nByte>iLimit ){
751     return SQLITE_TOOBIG;
752   }
753 
754   return SQLITE_OK;
755 }
756 
757 /*
758 ** Compare the values contained by the two memory cells, returning
759 ** negative, zero or positive if pMem1 is less than, equal to, or greater
760 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
761 ** and reals) sorted numerically, followed by text ordered by the collating
762 ** sequence pColl and finally blob's ordered by memcmp().
763 **
764 ** Two NULL values are considered equal by this function.
765 */
766 int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
767   int rc;
768   int f1, f2;
769   int combined_flags;
770 
771   f1 = pMem1->flags;
772   f2 = pMem2->flags;
773   combined_flags = f1|f2;
774   assert( (combined_flags & MEM_RowSet)==0 );
775 
776   /* If one value is NULL, it is less than the other. If both values
777   ** are NULL, return 0.
778   */
779   if( combined_flags&MEM_Null ){
780     return (f2&MEM_Null) - (f1&MEM_Null);
781   }
782 
783   /* If one value is a number and the other is not, the number is less.
784   ** If both are numbers, compare as reals if one is a real, or as integers
785   ** if both values are integers.
786   */
787   if( combined_flags&(MEM_Int|MEM_Real) ){
788     double r1, r2;
789     if( (f1 & f2 & MEM_Int)!=0 ){
790       if( pMem1->u.i < pMem2->u.i ) return -1;
791       if( pMem1->u.i > pMem2->u.i ) return 1;
792       return 0;
793     }
794     if( (f1&MEM_Real)!=0 ){
795       r1 = pMem1->r;
796     }else if( (f1&MEM_Int)!=0 ){
797       r1 = (double)pMem1->u.i;
798     }else{
799       return 1;
800     }
801     if( (f2&MEM_Real)!=0 ){
802       r2 = pMem2->r;
803     }else if( (f2&MEM_Int)!=0 ){
804       r2 = (double)pMem2->u.i;
805     }else{
806       return -1;
807     }
808     if( r1<r2 ) return -1;
809     if( r1>r2 ) return 1;
810     return 0;
811   }
812 
813   /* If one value is a string and the other is a blob, the string is less.
814   ** If both are strings, compare using the collating functions.
815   */
816   if( combined_flags&MEM_Str ){
817     if( (f1 & MEM_Str)==0 ){
818       return 1;
819     }
820     if( (f2 & MEM_Str)==0 ){
821       return -1;
822     }
823 
824     assert( pMem1->enc==pMem2->enc );
825     assert( pMem1->enc==SQLITE_UTF8 ||
826             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
827 
828     /* The collation sequence must be defined at this point, even if
829     ** the user deletes the collation sequence after the vdbe program is
830     ** compiled (this was not always the case).
831     */
832     assert( !pColl || pColl->xCmp );
833 
834     if( pColl ){
835       if( pMem1->enc==pColl->enc ){
836         /* The strings are already in the correct encoding.  Call the
837         ** comparison function directly */
838         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
839       }else{
840         const void *v1, *v2;
841         int n1, n2;
842         Mem c1;
843         Mem c2;
844         memset(&c1, 0, sizeof(c1));
845         memset(&c2, 0, sizeof(c2));
846         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
847         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
848         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
849         n1 = v1==0 ? 0 : c1.n;
850         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
851         n2 = v2==0 ? 0 : c2.n;
852         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
853         sqlite3VdbeMemRelease(&c1);
854         sqlite3VdbeMemRelease(&c2);
855         return rc;
856       }
857     }
858     /* If a NULL pointer was passed as the collate function, fall through
859     ** to the blob case and use memcmp().  */
860   }
861 
862   /* Both values must be blobs.  Compare using memcmp().  */
863   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
864   if( rc==0 ){
865     rc = pMem1->n - pMem2->n;
866   }
867   return rc;
868 }
869 
870 /*
871 ** Move data out of a btree key or data field and into a Mem structure.
872 ** The data or key is taken from the entry that pCur is currently pointing
873 ** to.  offset and amt determine what portion of the data or key to retrieve.
874 ** key is true to get the key or false to get data.  The result is written
875 ** into the pMem element.
876 **
877 ** The pMem structure is assumed to be uninitialized.  Any prior content
878 ** is overwritten without being freed.
879 **
880 ** If this routine fails for any reason (malloc returns NULL or unable
881 ** to read from the disk) then the pMem is left in an inconsistent state.
882 */
883 int sqlite3VdbeMemFromBtree(
884   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
885   u32 offset,       /* Offset from the start of data to return bytes from. */
886   u32 amt,          /* Number of bytes to return. */
887   int key,          /* If true, retrieve from the btree key, not data. */
888   Mem *pMem         /* OUT: Return data in this Mem structure. */
889 ){
890   char *zData;        /* Data from the btree layer */
891   u32 available = 0;  /* Number of bytes available on the local btree page */
892   int rc = SQLITE_OK; /* Return code */
893 
894   assert( sqlite3BtreeCursorIsValid(pCur) );
895 
896   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
897   ** that both the BtShared and database handle mutexes are held. */
898   assert( (pMem->flags & MEM_RowSet)==0 );
899   if( key ){
900     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
901   }else{
902     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
903   }
904   assert( zData!=0 );
905 
906   if( offset+amt<=available ){
907     sqlite3VdbeMemRelease(pMem);
908     pMem->z = &zData[offset];
909     pMem->flags = MEM_Blob|MEM_Ephem;
910   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
911     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
912     pMem->enc = 0;
913     pMem->type = SQLITE_BLOB;
914     if( key ){
915       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
916     }else{
917       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
918     }
919     pMem->z[amt] = 0;
920     pMem->z[amt+1] = 0;
921     if( rc!=SQLITE_OK ){
922       sqlite3VdbeMemRelease(pMem);
923     }
924   }
925   pMem->n = (int)amt;
926 
927   return rc;
928 }
929 
930 /* This function is only available internally, it is not part of the
931 ** external API. It works in a similar way to sqlite3_value_text(),
932 ** except the data returned is in the encoding specified by the second
933 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
934 ** SQLITE_UTF8.
935 **
936 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
937 ** If that is the case, then the result must be aligned on an even byte
938 ** boundary.
939 */
940 const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
941   if( !pVal ) return 0;
942 
943   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
944   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
945   assert( (pVal->flags & MEM_RowSet)==0 );
946 
947   if( pVal->flags&MEM_Null ){
948     return 0;
949   }
950   assert( (MEM_Blob>>3) == MEM_Str );
951   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
952   ExpandBlob(pVal);
953   if( pVal->flags&MEM_Str ){
954     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
955     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
956       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
957       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
958         return 0;
959       }
960     }
961     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
962   }else{
963     assert( (pVal->flags&MEM_Blob)==0 );
964     sqlite3VdbeMemStringify(pVal, enc);
965     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
966   }
967   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
968               || pVal->db->mallocFailed );
969   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
970     return pVal->z;
971   }else{
972     return 0;
973   }
974 }
975 
976 /*
977 ** Create a new sqlite3_value object.
978 */
979 sqlite3_value *sqlite3ValueNew(sqlite3 *db){
980   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
981   if( p ){
982     p->flags = MEM_Null;
983     p->type = SQLITE_NULL;
984     p->db = db;
985   }
986   return p;
987 }
988 
989 /*
990 ** Context object passed by sqlite3Stat4ProbeSetValue() through to
991 ** valueNew(). See comments above valueNew() for details.
992 */
993 struct ValueNewStat4Ctx {
994   Parse *pParse;
995   Index *pIdx;
996   UnpackedRecord **ppRec;
997   int iVal;
998 };
999 
1000 /*
1001 ** Allocate and return a pointer to a new sqlite3_value object. If
1002 ** the second argument to this function is NULL, the object is allocated
1003 ** by calling sqlite3ValueNew().
1004 **
1005 ** Otherwise, if the second argument is non-zero, then this function is
1006 ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
1007 ** already been allocated, allocate the UnpackedRecord structure that
1008 ** that function will return to its caller here. Then return a pointer
1009 ** an sqlite3_value within the UnpackedRecord.a[] array.
1010 */
1011 static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
1012 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1013   if( p ){
1014     UnpackedRecord *pRec = p->ppRec[0];
1015 
1016     if( pRec==0 ){
1017       Index *pIdx = p->pIdx;      /* Index being probed */
1018       int nByte;                  /* Bytes of space to allocate */
1019       int i;                      /* Counter variable */
1020       int nCol = pIdx->nColumn;   /* Number of index columns including rowid */
1021 
1022       nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
1023       pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
1024       if( pRec ){
1025         pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
1026         if( pRec->pKeyInfo ){
1027           assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
1028           assert( pRec->pKeyInfo->enc==ENC(db) );
1029           pRec->flags = UNPACKED_PREFIX_MATCH;
1030           pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
1031           for(i=0; i<nCol; i++){
1032             pRec->aMem[i].flags = MEM_Null;
1033             pRec->aMem[i].type = SQLITE_NULL;
1034             pRec->aMem[i].db = db;
1035           }
1036         }else{
1037           sqlite3DbFree(db, pRec);
1038           pRec = 0;
1039         }
1040       }
1041       if( pRec==0 ) return 0;
1042       p->ppRec[0] = pRec;
1043     }
1044 
1045     pRec->nField = p->iVal+1;
1046     return &pRec->aMem[p->iVal];
1047   }
1048 #else
1049   UNUSED_PARAMETER(p);
1050 #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
1051   return sqlite3ValueNew(db);
1052 }
1053 
1054 /*
1055 ** Extract a value from the supplied expression in the manner described
1056 ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
1057 ** using valueNew().
1058 **
1059 ** If pCtx is NULL and an error occurs after the sqlite3_value object
1060 ** has been allocated, it is freed before returning. Or, if pCtx is not
1061 ** NULL, it is assumed that the caller will free any allocated object
1062 ** in all cases.
1063 */
1064 static int valueFromExpr(
1065   sqlite3 *db,                    /* The database connection */
1066   Expr *pExpr,                    /* The expression to evaluate */
1067   u8 enc,                         /* Encoding to use */
1068   u8 affinity,                    /* Affinity to use */
1069   sqlite3_value **ppVal,          /* Write the new value here */
1070   struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
1071 ){
1072   int op;
1073   char *zVal = 0;
1074   sqlite3_value *pVal = 0;
1075   int negInt = 1;
1076   const char *zNeg = "";
1077   int rc = SQLITE_OK;
1078 
1079   if( !pExpr ){
1080     *ppVal = 0;
1081     return SQLITE_OK;
1082   }
1083   op = pExpr->op;
1084   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
1085 
1086   /* Handle negative integers in a single step.  This is needed in the
1087   ** case when the value is -9223372036854775808.
1088   */
1089   if( op==TK_UMINUS
1090    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
1091     pExpr = pExpr->pLeft;
1092     op = pExpr->op;
1093     negInt = -1;
1094     zNeg = "-";
1095   }
1096 
1097   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
1098     pVal = valueNew(db, pCtx);
1099     if( pVal==0 ) goto no_mem;
1100     if( ExprHasProperty(pExpr, EP_IntValue) ){
1101       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
1102     }else{
1103       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
1104       if( zVal==0 ) goto no_mem;
1105       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
1106       if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
1107     }
1108     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
1109       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
1110     }else{
1111       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
1112     }
1113     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
1114     if( enc!=SQLITE_UTF8 ){
1115       rc = sqlite3VdbeChangeEncoding(pVal, enc);
1116     }
1117   }else if( op==TK_UMINUS ) {
1118     /* This branch happens for multiple negative signs.  Ex: -(-5) */
1119     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
1120      && pVal!=0
1121     ){
1122       sqlite3VdbeMemNumerify(pVal);
1123       if( pVal->u.i==SMALLEST_INT64 ){
1124         pVal->flags &= MEM_Int;
1125         pVal->flags |= MEM_Real;
1126         pVal->r = (double)LARGEST_INT64;
1127       }else{
1128         pVal->u.i = -pVal->u.i;
1129       }
1130       pVal->r = -pVal->r;
1131       sqlite3ValueApplyAffinity(pVal, affinity, enc);
1132     }
1133   }else if( op==TK_NULL ){
1134     pVal = valueNew(db, pCtx);
1135     if( pVal==0 ) goto no_mem;
1136   }
1137 #ifndef SQLITE_OMIT_BLOB_LITERAL
1138   else if( op==TK_BLOB ){
1139     int nVal;
1140     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
1141     assert( pExpr->u.zToken[1]=='\'' );
1142     pVal = valueNew(db, pCtx);
1143     if( !pVal ) goto no_mem;
1144     zVal = &pExpr->u.zToken[2];
1145     nVal = sqlite3Strlen30(zVal)-1;
1146     assert( zVal[nVal]=='\'' );
1147     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
1148                          0, SQLITE_DYNAMIC);
1149   }
1150 #endif
1151 
1152   if( pVal ){
1153     sqlite3VdbeMemStoreType(pVal);
1154   }
1155   *ppVal = pVal;
1156   return rc;
1157 
1158 no_mem:
1159   db->mallocFailed = 1;
1160   sqlite3DbFree(db, zVal);
1161   assert( *ppVal==0 );
1162 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1163   if( pCtx==0 ) sqlite3ValueFree(pVal);
1164 #else
1165   assert( pCtx==0 ); sqlite3ValueFree(pVal);
1166 #endif
1167   return SQLITE_NOMEM;
1168 }
1169 
1170 /*
1171 ** Create a new sqlite3_value object, containing the value of pExpr.
1172 **
1173 ** This only works for very simple expressions that consist of one constant
1174 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
1175 ** be converted directly into a value, then the value is allocated and
1176 ** a pointer written to *ppVal. The caller is responsible for deallocating
1177 ** the value by passing it to sqlite3ValueFree() later on. If the expression
1178 ** cannot be converted to a value, then *ppVal is set to NULL.
1179 */
1180 int sqlite3ValueFromExpr(
1181   sqlite3 *db,              /* The database connection */
1182   Expr *pExpr,              /* The expression to evaluate */
1183   u8 enc,                   /* Encoding to use */
1184   u8 affinity,              /* Affinity to use */
1185   sqlite3_value **ppVal     /* Write the new value here */
1186 ){
1187   return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
1188 }
1189 
1190 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1191 /*
1192 ** The implementation of the sqlite_record() function. This function accepts
1193 ** a single argument of any type. The return value is a formatted database
1194 ** record (a blob) containing the argument value.
1195 **
1196 ** This is used to convert the value stored in the 'sample' column of the
1197 ** sqlite_stat3 table to the record format SQLite uses internally.
1198 */
1199 static void recordFunc(
1200   sqlite3_context *context,
1201   int argc,
1202   sqlite3_value **argv
1203 ){
1204   const int file_format = 1;
1205   int iSerial;                    /* Serial type */
1206   int nSerial;                    /* Bytes of space for iSerial as varint */
1207   int nVal;                       /* Bytes of space required for argv[0] */
1208   int nRet;
1209   sqlite3 *db;
1210   u8 *aRet;
1211 
1212   UNUSED_PARAMETER( argc );
1213   iSerial = sqlite3VdbeSerialType(argv[0], file_format);
1214   nSerial = sqlite3VarintLen(iSerial);
1215   nVal = sqlite3VdbeSerialTypeLen(iSerial);
1216   db = sqlite3_context_db_handle(context);
1217 
1218   nRet = 1 + nSerial + nVal;
1219   aRet = sqlite3DbMallocRaw(db, nRet);
1220   if( aRet==0 ){
1221     sqlite3_result_error_nomem(context);
1222   }else{
1223     aRet[0] = nSerial+1;
1224     sqlite3PutVarint(&aRet[1], iSerial);
1225     sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
1226     sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
1227     sqlite3DbFree(db, aRet);
1228   }
1229 }
1230 
1231 /*
1232 ** Register built-in functions used to help read ANALYZE data.
1233 */
1234 void sqlite3AnalyzeFunctions(void){
1235   static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
1236     FUNCTION(sqlite_record,   1, 0, 0, recordFunc),
1237   };
1238   int i;
1239   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
1240   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
1241   for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
1242     sqlite3FuncDefInsert(pHash, &aFunc[i]);
1243   }
1244 }
1245 
1246 /*
1247 ** This function is used to allocate and populate UnpackedRecord
1248 ** structures intended to be compared against sample index keys stored
1249 ** in the sqlite_stat4 table.
1250 **
1251 ** A single call to this function attempts to populates field iVal (leftmost
1252 ** is 0 etc.) of the unpacked record with a value extracted from expression
1253 ** pExpr. Extraction of values is possible if:
1254 **
1255 **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
1256 **
1257 **  * The expression is a bound variable, and this is a reprepare, or
1258 **
1259 **  * The sqlite3ValueFromExpr() function is able to extract a value
1260 **    from the expression (i.e. the expression is a literal value).
1261 **
1262 ** If a value can be extracted, the affinity passed as the 5th argument
1263 ** is applied to it before it is copied into the UnpackedRecord. Output
1264 ** parameter *pbOk is set to true if a value is extracted, or false
1265 ** otherwise.
1266 **
1267 ** When this function is called, *ppRec must either point to an object
1268 ** allocated by an earlier call to this function, or must be NULL. If it
1269 ** is NULL and a value can be successfully extracted, a new UnpackedRecord
1270 ** is allocated (and *ppRec set to point to it) before returning.
1271 **
1272 ** Unless an error is encountered, SQLITE_OK is returned. It is not an
1273 ** error if a value cannot be extracted from pExpr. If an error does
1274 ** occur, an SQLite error code is returned.
1275 */
1276 int sqlite3Stat4ProbeSetValue(
1277   Parse *pParse,                  /* Parse context */
1278   Index *pIdx,                    /* Index being probed */
1279   UnpackedRecord **ppRec,         /* IN/OUT: Probe record */
1280   Expr *pExpr,                    /* The expression to extract a value from */
1281   u8 affinity,                    /* Affinity to use */
1282   int iVal,                       /* Array element to populate */
1283   int *pbOk                       /* OUT: True if value was extracted */
1284 ){
1285   int rc = SQLITE_OK;
1286   sqlite3_value *pVal = 0;
1287   sqlite3 *db = pParse->db;
1288 
1289 
1290   struct ValueNewStat4Ctx alloc;
1291   alloc.pParse = pParse;
1292   alloc.pIdx = pIdx;
1293   alloc.ppRec = ppRec;
1294   alloc.iVal = iVal;
1295 
1296   /* Skip over any TK_COLLATE nodes */
1297   pExpr = sqlite3ExprSkipCollate(pExpr);
1298 
1299   if( !pExpr ){
1300     pVal = valueNew(db, &alloc);
1301     if( pVal ){
1302       sqlite3VdbeMemSetNull((Mem*)pVal);
1303     }
1304   }else if( pExpr->op==TK_VARIABLE
1305         || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
1306   ){
1307     Vdbe *v;
1308     int iBindVar = pExpr->iColumn;
1309     sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
1310     if( (v = pParse->pReprepare)!=0 ){
1311       pVal = valueNew(db, &alloc);
1312       if( pVal ){
1313         rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
1314         if( rc==SQLITE_OK ){
1315           sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
1316         }
1317         pVal->db = pParse->db;
1318         sqlite3VdbeMemStoreType((Mem*)pVal);
1319       }
1320     }
1321   }else{
1322     rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, &alloc);
1323   }
1324   *pbOk = (pVal!=0);
1325 
1326   assert( pVal==0 || pVal->db==db );
1327   return rc;
1328 }
1329 
1330 /*
1331 ** Unless it is NULL, the argument must be an UnpackedRecord object returned
1332 ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
1333 ** the object.
1334 */
1335 void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
1336   if( pRec ){
1337     int i;
1338     int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
1339     Mem *aMem = pRec->aMem;
1340     sqlite3 *db = aMem[0].db;
1341     for(i=0; i<nCol; i++){
1342       sqlite3DbFree(db, aMem[i].zMalloc);
1343     }
1344     sqlite3KeyInfoUnref(pRec->pKeyInfo);
1345     sqlite3DbFree(db, pRec);
1346   }
1347 }
1348 #endif /* ifdef SQLITE_ENABLE_STAT4 */
1349 
1350 /*
1351 ** Change the string value of an sqlite3_value object
1352 */
1353 void sqlite3ValueSetStr(
1354   sqlite3_value *v,     /* Value to be set */
1355   int n,                /* Length of string z */
1356   const void *z,        /* Text of the new string */
1357   u8 enc,               /* Encoding to use */
1358   void (*xDel)(void*)   /* Destructor for the string */
1359 ){
1360   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
1361 }
1362 
1363 /*
1364 ** Free an sqlite3_value object
1365 */
1366 void sqlite3ValueFree(sqlite3_value *v){
1367   if( !v ) return;
1368   sqlite3VdbeMemRelease((Mem *)v);
1369   sqlite3DbFree(((Mem*)v)->db, v);
1370 }
1371 
1372 /*
1373 ** Return the number of bytes in the sqlite3_value object assuming
1374 ** that it uses the encoding "enc"
1375 */
1376 int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
1377   Mem *p = (Mem*)pVal;
1378   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
1379     if( p->flags & MEM_Zero ){
1380       return p->n + p->u.nZero;
1381     }else{
1382       return p->n;
1383     }
1384   }
1385   return 0;
1386 }
1387