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