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