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