xref: /sqlite-3.40.0/src/vdbemem.c (revision 8a29dfde)
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 <ctype.h>
20 #include "vdbeInt.h"
21 
22 /*
23 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
24 ** P if required.
25 */
26 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
27 
28 /*
29 ** If pMem is an object with a valid string representation, this routine
30 ** ensures the internal encoding for the string representation is
31 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
32 **
33 ** If pMem is not a string object, or the encoding of the string
34 ** representation is already stored using the requested encoding, then this
35 ** routine is a no-op.
36 **
37 ** SQLITE_OK is returned if the conversion is successful (or not required).
38 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
39 ** between formats.
40 */
41 int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
42   int rc;
43   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
44     return SQLITE_OK;
45   }
46   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
47 #ifdef SQLITE_OMIT_UTF16
48   return SQLITE_ERROR;
49 #else
50 
51   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
52   ** then the encoding of the value may not have changed.
53   */
54   rc = sqlite3VdbeMemTranslate(pMem, desiredEnc);
55   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
56   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
57   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
58   return rc;
59 #endif
60 }
61 
62 /*
63 ** Make sure pMem->z points to a writable allocation of at least
64 ** n bytes.
65 **
66 ** If the memory cell currently contains string or blob data
67 ** and the third argument passed to this function is true, the
68 ** current content of the cell is preserved. Otherwise, it may
69 ** be discarded.
70 **
71 ** This function sets the MEM_Dyn flag and clears any xDel callback.
72 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
73 ** not set, Mem.n is zeroed.
74 */
75 int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
76   assert( 1 >=
77     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
78     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
79     ((pMem->flags&MEM_Ephem) ? 1 : 0) +
80     ((pMem->flags&MEM_Static) ? 1 : 0)
81   );
82 
83   if( !pMem->zMalloc || sqlite3MallocSize(pMem->zMalloc)<n ){
84     n = (n>32?n:32);
85     if( preserve && pMem->z==pMem->zMalloc ){
86       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
87       if( !pMem->z ){
88         pMem->flags = MEM_Null;
89       }
90       preserve = 0;
91     }else{
92       sqlite3_free(pMem->zMalloc);
93       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
94     }
95   }
96 
97   if( preserve && pMem->z && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
98     memcpy(pMem->zMalloc, pMem->z, pMem->n);
99   }
100   if( pMem->xDel && pMem->flags&MEM_Dyn){
101     pMem->xDel((void *)(pMem->z));
102   }
103 
104   pMem->z = pMem->zMalloc;
105   pMem->flags &= ~(MEM_Ephem|MEM_Static);
106   pMem->xDel = 0;
107   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
108 }
109 
110 /*
111 ** Make the given Mem object MEM_Dyn.
112 **
113 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
114 */
115 int sqlite3VdbeMemDynamicify(Mem *pMem){
116   int f;
117   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
118   expandBlob(pMem);
119   f = pMem->flags;
120   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
121     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
122       return SQLITE_NOMEM;
123     }
124     pMem->z[pMem->n] = 0;
125     pMem->z[pMem->n+1] = 0;
126     pMem->flags |= MEM_Term;
127   }
128 
129   return SQLITE_OK;
130 }
131 
132 /*
133 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
134 ** blob stored in dynamically allocated space.
135 */
136 #ifndef SQLITE_OMIT_INCRBLOB
137 int sqlite3VdbeMemExpandBlob(Mem *pMem){
138   if( pMem->flags & MEM_Zero ){
139     int nByte;
140     assert( pMem->flags&MEM_Blob );
141     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
142 
143     /* Set nByte to the number of bytes required to store the expanded blob. */
144     nByte = pMem->n + pMem->u.i;
145     if( nByte<=0 ){
146       nByte = 1;
147     }
148     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
149       return SQLITE_NOMEM;
150     }
151 
152     memset(&pMem->z[pMem->n], 0, pMem->u.i);
153     pMem->n += pMem->u.i;
154     pMem->flags &= ~(MEM_Zero|MEM_Term);
155   }
156   return SQLITE_OK;
157 }
158 #endif
159 
160 
161 /*
162 ** Make the given Mem object either MEM_Short or MEM_Dyn so that bytes
163 ** of the Mem.z[] array can be modified.
164 **
165 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
166 */
167 int sqlite3VdbeMemMakeWriteable(Mem *pMem){
168   return sqlite3VdbeMemDynamicify(pMem);
169 }
170 
171 /*
172 ** Make sure the given Mem is \u0000 terminated.
173 */
174 int sqlite3VdbeMemNulTerminate(Mem *pMem){
175   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
176   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
177     return SQLITE_OK;   /* Nothing to do */
178   }
179   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
180     return SQLITE_NOMEM;
181   }
182   pMem->z[pMem->n] = 0;
183   pMem->z[pMem->n+1] = 0;
184   pMem->flags |= MEM_Term;
185   return SQLITE_OK;
186 }
187 
188 /*
189 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
190 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
191 ** is a no-op.
192 **
193 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
194 **
195 ** A MEM_Null value will never be passed to this function. This function is
196 ** used for converting values to text for returning to the user (i.e. via
197 ** sqlite3_value_text()), or for ensuring that values to be used as btree
198 ** keys are strings. In the former case a NULL pointer is returned the
199 ** user and the later is an internal programming error.
200 */
201 int sqlite3VdbeMemStringify(Mem *pMem, int enc){
202   int rc = SQLITE_OK;
203   int fg = pMem->flags;
204   const int nByte = 32;
205 
206   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
207   assert( !(fg&MEM_Zero) );
208   assert( !(fg&(MEM_Str|MEM_Blob)) );
209   assert( fg&(MEM_Int|MEM_Real) );
210 
211   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
212     return SQLITE_NOMEM;
213   }
214 
215   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
216   ** string representation of the value. Then, if the required encoding
217   ** is UTF-16le or UTF-16be do a translation.
218   **
219   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
220   */
221   if( fg & MEM_Int ){
222     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
223   }else{
224     assert( fg & MEM_Real );
225     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
226   }
227   pMem->n = strlen(pMem->z);
228   pMem->enc = SQLITE_UTF8;
229   pMem->flags |= MEM_Str|MEM_Term;
230   sqlite3VdbeChangeEncoding(pMem, enc);
231   return rc;
232 }
233 
234 /*
235 ** Memory cell pMem contains the context of an aggregate function.
236 ** This routine calls the finalize method for that function.  The
237 ** result of the aggregate is stored back into pMem.
238 **
239 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
240 ** otherwise.
241 */
242 int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
243   int rc = SQLITE_OK;
244   if( pFunc && pFunc->xFinalize ){
245     sqlite3_context ctx;
246     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
247     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
248     ctx.s.flags = MEM_Null;
249     ctx.s.db = pMem->db;
250     ctx.s.zMalloc = 0;
251     ctx.pMem = pMem;
252     ctx.pFunc = pFunc;
253     ctx.isError = 0;
254     pFunc->xFinalize(&ctx);
255     assert( !pMem->xDel || 0==(pMem->flags&MEM_Dyn) );
256     sqlite3_free(pMem->zMalloc);
257     *pMem = ctx.s;
258     rc = (ctx.isError?SQLITE_ERROR:SQLITE_OK);
259   }
260   return rc;
261 }
262 
263 /*
264 ** If the memory cell contains a string value that must be freed by
265 ** invoking an external callback, free it now. Calling this function
266 ** does not free any Mem.zMalloc buffer.
267 */
268 void sqlite3VdbeMemReleaseExternal(Mem *p){
269   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
270   if( p->flags&MEM_Agg ){
271     sqlite3VdbeMemFinalize(p, p->u.pDef);
272     assert( (p->flags & MEM_Agg)==0 );
273     sqlite3VdbeMemRelease(p);
274   }else if( p->xDel && p->flags&MEM_Dyn ){
275     p->xDel((void *)p->z);
276     p->xDel = 0;
277   }
278 }
279 
280 /*
281 ** Release any memory held by the Mem. This may leave the Mem in an
282 ** inconsistent state, for example with (Mem.z==0) and
283 ** (Mem.type==SQLITE_TEXT).
284 */
285 void sqlite3VdbeMemRelease(Mem *p){
286   sqlite3VdbeMemReleaseExternal(p);
287   sqlite3_free(p->zMalloc);
288   p->z = 0;
289   p->zMalloc = 0;
290   p->xDel = 0;
291 }
292 
293 /*
294 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
295 ** If the double is too large, return 0x8000000000000000.
296 **
297 ** Most systems appear to do this simply by assigning
298 ** variables and without the extra range tests.  But
299 ** there are reports that windows throws an expection
300 ** if the floating point value is out of range. (See ticket #2880.)
301 ** Because we do not completely understand the problem, we will
302 ** take the conservative approach and always do range tests
303 ** before attempting the conversion.
304 */
305 static i64 doubleToInt64(double r){
306   /*
307   ** Many compilers we encounter do not define constants for the
308   ** minimum and maximum 64-bit integers, or they define them
309   ** inconsistently.  And many do not understand the "LL" notation.
310   ** So we define our own static constants here using nothing
311   ** larger than a 32-bit integer constant.
312   */
313   static const i64 maxInt = (((i64)0x7fffffff)<<32)|0xffffffff;
314   static const i64 minInt = ((i64)0x80000000)<<32;
315 
316   if( r<(double)minInt ){
317     return minInt;
318   }else if( r>(double)maxInt ){
319     return minInt;
320   }else{
321     return (i64)r;
322   }
323 }
324 
325 /*
326 ** Return some kind of integer value which is the best we can do
327 ** at representing the value that *pMem describes as an integer.
328 ** If pMem is an integer, then the value is exact.  If pMem is
329 ** a floating-point then the value returned is the integer part.
330 ** If pMem is a string or blob, then we make an attempt to convert
331 ** it into a integer and return that.  If pMem is NULL, return 0.
332 **
333 ** If pMem is a string, its encoding might be changed.
334 */
335 i64 sqlite3VdbeIntValue(Mem *pMem){
336   int flags;
337   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
338   flags = pMem->flags;
339   if( flags & MEM_Int ){
340     return pMem->u.i;
341   }else if( flags & MEM_Real ){
342     return doubleToInt64(pMem->r);
343   }else if( flags & (MEM_Str|MEM_Blob) ){
344     i64 value;
345     pMem->flags |= MEM_Str;
346     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
347        || sqlite3VdbeMemNulTerminate(pMem) ){
348       return 0;
349     }
350     assert( pMem->z );
351     sqlite3Atoi64(pMem->z, &value);
352     return value;
353   }else{
354     return 0;
355   }
356 }
357 
358 /*
359 ** Return the best representation of pMem that we can get into a
360 ** double.  If pMem is already a double or an integer, return its
361 ** value.  If it is a string or blob, try to convert it to a double.
362 ** If it is a NULL, return 0.0.
363 */
364 double sqlite3VdbeRealValue(Mem *pMem){
365   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
366   if( pMem->flags & MEM_Real ){
367     return pMem->r;
368   }else if( pMem->flags & MEM_Int ){
369     return (double)pMem->u.i;
370   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
371     double val = 0.0;
372     pMem->flags |= MEM_Str;
373     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
374        || sqlite3VdbeMemNulTerminate(pMem) ){
375       return 0.0;
376     }
377     assert( pMem->z );
378     sqlite3AtoF(pMem->z, &val);
379     return val;
380   }else{
381     return 0.0;
382   }
383 }
384 
385 /*
386 ** The MEM structure is already a MEM_Real.  Try to also make it a
387 ** MEM_Int if we can.
388 */
389 void sqlite3VdbeIntegerAffinity(Mem *pMem){
390   assert( pMem->flags & MEM_Real );
391   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
392 
393   pMem->u.i = doubleToInt64(pMem->r);
394   if( pMem->r==(double)pMem->u.i ){
395     pMem->flags |= MEM_Int;
396   }
397 }
398 
399 static void setTypeFlag(Mem *pMem, int f){
400   MemSetTypeFlag(pMem, f);
401 }
402 
403 /*
404 ** Convert pMem to type integer.  Invalidate any prior representations.
405 */
406 int sqlite3VdbeMemIntegerify(Mem *pMem){
407   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
408   pMem->u.i = sqlite3VdbeIntValue(pMem);
409   setTypeFlag(pMem, MEM_Int);
410   return SQLITE_OK;
411 }
412 
413 /*
414 ** Convert pMem so that it is of type MEM_Real.
415 ** Invalidate any prior representations.
416 */
417 int sqlite3VdbeMemRealify(Mem *pMem){
418   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
419   pMem->r = sqlite3VdbeRealValue(pMem);
420   setTypeFlag(pMem, MEM_Real);
421   return SQLITE_OK;
422 }
423 
424 /*
425 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
426 ** Invalidate any prior representations.
427 */
428 int sqlite3VdbeMemNumerify(Mem *pMem){
429   double r1, r2;
430   i64 i;
431   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
432   assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
433   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
434   r1 = sqlite3VdbeRealValue(pMem);
435   i = doubleToInt64(r1);
436   r2 = (double)i;
437   if( r1==r2 ){
438     sqlite3VdbeMemIntegerify(pMem);
439   }else{
440     pMem->r = r1;
441     setTypeFlag(pMem, MEM_Real);
442   }
443   return SQLITE_OK;
444 }
445 
446 /*
447 ** Delete any previous value and set the value stored in *pMem to NULL.
448 */
449 void sqlite3VdbeMemSetNull(Mem *pMem){
450   setTypeFlag(pMem, MEM_Null);
451   pMem->type = SQLITE_NULL;
452 }
453 
454 /*
455 ** Delete any previous value and set the value to be a BLOB of length
456 ** n containing all zeros.
457 */
458 void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
459   sqlite3VdbeMemRelease(pMem);
460   setTypeFlag(pMem, MEM_Blob);
461   pMem->flags = MEM_Blob|MEM_Zero;
462   pMem->type = SQLITE_BLOB;
463   pMem->n = 0;
464   if( n<0 ) n = 0;
465   pMem->u.i = n;
466   pMem->enc = SQLITE_UTF8;
467 }
468 
469 /*
470 ** Delete any previous value and set the value stored in *pMem to val,
471 ** manifest type INTEGER.
472 */
473 void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
474   sqlite3VdbeMemRelease(pMem);
475   pMem->u.i = val;
476   pMem->flags = MEM_Int;
477   pMem->type = SQLITE_INTEGER;
478 }
479 
480 /*
481 ** Delete any previous value and set the value stored in *pMem to val,
482 ** manifest type REAL.
483 */
484 void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
485   if( sqlite3_isnan(val) ){
486     sqlite3VdbeMemSetNull(pMem);
487   }else{
488     sqlite3VdbeMemRelease(pMem);
489     pMem->r = val;
490     pMem->flags = MEM_Real;
491     pMem->type = SQLITE_FLOAT;
492   }
493 }
494 
495 /*
496 ** Return true if the Mem object contains a TEXT or BLOB that is
497 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
498 */
499 int sqlite3VdbeMemTooBig(Mem *p){
500   assert( p->db!=0 );
501   if( p->flags & (MEM_Str|MEM_Blob) ){
502     int n = p->n;
503     if( p->flags & MEM_Zero ){
504       n += p->u.i;
505     }
506     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
507   }
508   return 0;
509 }
510 
511 /*
512 ** Size of struct Mem not including the Mem.zMalloc member.
513 */
514 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
515 
516 /*
517 ** Make an shallow copy of pFrom into pTo.  Prior contents of
518 ** pTo are freed.  The pFrom->z field is not duplicated.  If
519 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
520 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
521 */
522 void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
523   sqlite3VdbeMemReleaseExternal(pTo);
524   memcpy(pTo, pFrom, MEMCELLSIZE);
525   pTo->xDel = 0;
526   if( pFrom->xDel || pFrom->z==pFrom->zMalloc ){
527     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
528     assert( srcType==MEM_Ephem || srcType==MEM_Static );
529     pTo->flags |= srcType;
530   }
531 }
532 
533 /*
534 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
535 ** freed before the copy is made.
536 */
537 int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
538   int rc = SQLITE_OK;
539 
540   sqlite3VdbeMemReleaseExternal(pTo);
541   memcpy(pTo, pFrom, MEMCELLSIZE);
542   pTo->flags &= ~MEM_Dyn;
543 
544   if( pTo->flags&(MEM_Str|MEM_Blob) ){
545     if( 0==(pFrom->flags&MEM_Static) ){
546       pTo->flags |= MEM_Ephem;
547       rc = sqlite3VdbeMemMakeWriteable(pTo);
548     }
549   }
550 
551   return rc;
552 }
553 
554 /*
555 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
556 ** freed. If pFrom contains ephemeral data, a copy is made.
557 **
558 ** pFrom contains an SQL NULL when this routine returns.
559 */
560 void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
561   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
562   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
563   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
564 
565   sqlite3VdbeMemRelease(pTo);
566   memcpy(pTo, pFrom, sizeof(Mem));
567   pFrom->flags = MEM_Null;
568   pFrom->xDel = 0;
569   pFrom->zMalloc = 0;
570 }
571 
572 /*
573 ** Change the value of a Mem to be a string or a BLOB.
574 **
575 ** The memory management strategy depends on the value of the xDel
576 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
577 ** string is copied into a (possibly existing) buffer managed by the
578 ** Mem structure. Otherwise, any existing buffer is freed and the
579 ** pointer copied.
580 */
581 int sqlite3VdbeMemSetStr(
582   Mem *pMem,          /* Memory cell to set to string value */
583   const char *z,      /* String pointer */
584   int n,              /* Bytes in string, or negative */
585   u8 enc,             /* Encoding of z.  0 for BLOBs */
586   void (*xDel)(void*) /* Destructor function */
587 ){
588   int nByte = n;      /* New value for pMem->n */
589   int flags = 0;      /* New value for pMem->flags */
590 
591   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
592 
593   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
594   if( !z ){
595     sqlite3VdbeMemSetNull(pMem);
596     return SQLITE_OK;
597   }
598 
599   flags = (enc==0?MEM_Blob:MEM_Str);
600   if( nByte<0 ){
601     assert( enc!=0 );
602     if( enc==SQLITE_UTF8 ){
603       for(nByte=0; z[nByte]; nByte++){}
604     }else{
605       for(nByte=0; z[nByte] | z[nByte+1]; nByte+=2){}
606     }
607     flags |= MEM_Term;
608   }else if( enc==SQLITE_UTF8 && nByte>0 && z[nByte-1]=='\0' ){
609     nByte--;
610     flags |= MEM_Term;
611 #ifndef SQLITE_OMIT_UTF16
612   }else if( enc && nByte>1 && z[nByte-1]=='\0' && z[nByte-2]=='\0' ){
613     nByte -= 2;
614     flags |= MEM_Term;
615 #endif
616   }
617 
618   /* The following block sets the new values of Mem.z and Mem.xDel. It
619   ** also sets a flag in local variable "flags" to indicate the memory
620   ** management (one of MEM_Dyn or MEM_Static).
621   */
622   if( xDel==SQLITE_TRANSIENT ){
623     int nAlloc = nByte;
624     if( flags&MEM_Term ){
625       nAlloc += (enc==SQLITE_UTF8?1:2);
626     }
627     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
628       return SQLITE_NOMEM;
629     }
630     memcpy(pMem->z, z, nAlloc);
631   }else{
632     sqlite3VdbeMemRelease(pMem);
633     pMem->z = (char *)z;
634     pMem->xDel = xDel;
635     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
636   }
637 
638   pMem->n = nByte;
639   pMem->flags = flags;
640   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
641   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
642 
643 #ifndef SQLITE_OMIT_UTF16
644   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
645     return SQLITE_NOMEM;
646   }
647 #endif
648 
649   return SQLITE_OK;
650 }
651 
652 /*
653 ** Compare the values contained by the two memory cells, returning
654 ** negative, zero or positive if pMem1 is less than, equal to, or greater
655 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
656 ** and reals) sorted numerically, followed by text ordered by the collating
657 ** sequence pColl and finally blob's ordered by memcmp().
658 **
659 ** Two NULL values are considered equal by this function.
660 */
661 int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
662   int rc;
663   int f1, f2;
664   int combined_flags;
665 
666   /* Interchange pMem1 and pMem2 if the collating sequence specifies
667   ** DESC order.
668   */
669   f1 = pMem1->flags;
670   f2 = pMem2->flags;
671   combined_flags = f1|f2;
672 
673   /* If one value is NULL, it is less than the other. If both values
674   ** are NULL, return 0.
675   */
676   if( combined_flags&MEM_Null ){
677     return (f2&MEM_Null) - (f1&MEM_Null);
678   }
679 
680   /* If one value is a number and the other is not, the number is less.
681   ** If both are numbers, compare as reals if one is a real, or as integers
682   ** if both values are integers.
683   */
684   if( combined_flags&(MEM_Int|MEM_Real) ){
685     if( !(f1&(MEM_Int|MEM_Real)) ){
686       return 1;
687     }
688     if( !(f2&(MEM_Int|MEM_Real)) ){
689       return -1;
690     }
691     if( (f1 & f2 & MEM_Int)==0 ){
692       double r1, r2;
693       if( (f1&MEM_Real)==0 ){
694         r1 = pMem1->u.i;
695       }else{
696         r1 = pMem1->r;
697       }
698       if( (f2&MEM_Real)==0 ){
699         r2 = pMem2->u.i;
700       }else{
701         r2 = pMem2->r;
702       }
703       if( r1<r2 ) return -1;
704       if( r1>r2 ) return 1;
705       return 0;
706     }else{
707       assert( f1&MEM_Int );
708       assert( f2&MEM_Int );
709       if( pMem1->u.i < pMem2->u.i ) return -1;
710       if( pMem1->u.i > pMem2->u.i ) return 1;
711       return 0;
712     }
713   }
714 
715   /* If one value is a string and the other is a blob, the string is less.
716   ** If both are strings, compare using the collating functions.
717   */
718   if( combined_flags&MEM_Str ){
719     if( (f1 & MEM_Str)==0 ){
720       return 1;
721     }
722     if( (f2 & MEM_Str)==0 ){
723       return -1;
724     }
725 
726     assert( pMem1->enc==pMem2->enc );
727     assert( pMem1->enc==SQLITE_UTF8 ||
728             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
729 
730     /* The collation sequence must be defined at this point, even if
731     ** the user deletes the collation sequence after the vdbe program is
732     ** compiled (this was not always the case).
733     */
734     assert( !pColl || pColl->xCmp );
735 
736     if( pColl ){
737       if( pMem1->enc==pColl->enc ){
738         /* The strings are already in the correct encoding.  Call the
739         ** comparison function directly */
740         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
741       }else{
742         u8 origEnc = pMem1->enc;
743         const void *v1, *v2;
744         int n1, n2;
745         /* Convert the strings into the encoding that the comparison
746         ** function expects */
747         v1 = sqlite3ValueText((sqlite3_value*)pMem1, pColl->enc);
748         n1 = v1==0 ? 0 : pMem1->n;
749         assert( n1==sqlite3ValueBytes((sqlite3_value*)pMem1, pColl->enc) );
750         v2 = sqlite3ValueText((sqlite3_value*)pMem2, pColl->enc);
751         n2 = v2==0 ? 0 : pMem2->n;
752         assert( n2==sqlite3ValueBytes((sqlite3_value*)pMem2, pColl->enc) );
753         /* Do the comparison */
754         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
755         /* Convert the strings back into the database encoding */
756         sqlite3ValueText((sqlite3_value*)pMem1, origEnc);
757         sqlite3ValueText((sqlite3_value*)pMem2, origEnc);
758         return rc;
759       }
760     }
761     /* If a NULL pointer was passed as the collate function, fall through
762     ** to the blob case and use memcmp().  */
763   }
764 
765   /* Both values must be blobs.  Compare using memcmp().  */
766   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
767   if( rc==0 ){
768     rc = pMem1->n - pMem2->n;
769   }
770   return rc;
771 }
772 
773 /*
774 ** Move data out of a btree key or data field and into a Mem structure.
775 ** The data or key is taken from the entry that pCur is currently pointing
776 ** to.  offset and amt determine what portion of the data or key to retrieve.
777 ** key is true to get the key or false to get data.  The result is written
778 ** into the pMem element.
779 **
780 ** The pMem structure is assumed to be uninitialized.  Any prior content
781 ** is overwritten without being freed.
782 **
783 ** If this routine fails for any reason (malloc returns NULL or unable
784 ** to read from the disk) then the pMem is left in an inconsistent state.
785 */
786 int sqlite3VdbeMemFromBtree(
787   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
788   int offset,       /* Offset from the start of data to return bytes from. */
789   int amt,          /* Number of bytes to return. */
790   int key,          /* If true, retrieve from the btree key, not data. */
791   Mem *pMem         /* OUT: Return data in this Mem structure. */
792 ){
793   char *zData;       /* Data from the btree layer */
794   int available = 0; /* Number of bytes available on the local btree page */
795   sqlite3 *db;       /* Database connection */
796   int rc = SQLITE_OK;
797 
798   db = sqlite3BtreeCursorDb(pCur);
799   assert( sqlite3_mutex_held(db->mutex) );
800   if( key ){
801     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
802   }else{
803     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
804   }
805   assert( zData!=0 );
806 
807   if( offset+amt<=available && ((pMem->flags&MEM_Dyn)==0 || pMem->xDel) ){
808     sqlite3VdbeMemRelease(pMem);
809     pMem->z = &zData[offset];
810     pMem->flags = MEM_Blob|MEM_Ephem;
811   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
812     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
813     pMem->enc = 0;
814     pMem->type = SQLITE_BLOB;
815     if( key ){
816       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
817     }else{
818       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
819     }
820     pMem->z[amt] = 0;
821     pMem->z[amt+1] = 0;
822     if( rc!=SQLITE_OK ){
823       sqlite3VdbeMemRelease(pMem);
824     }
825   }
826   pMem->n = amt;
827 
828   return rc;
829 }
830 
831 #if 0
832 /*
833 ** Perform various checks on the memory cell pMem. An assert() will
834 ** fail if pMem is internally inconsistent.
835 */
836 void sqlite3VdbeMemSanity(Mem *pMem){
837   int flags = pMem->flags;
838   assert( flags!=0 );  /* Must define some type */
839   if( flags & (MEM_Str|MEM_Blob) ){
840     int x = flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short);
841     assert( x!=0 );            /* Strings must define a string subtype */
842     assert( (x & (x-1))==0 );  /* Only one string subtype can be defined */
843     assert( pMem->z!=0 );      /* Strings must have a value */
844     /* Mem.z points to Mem.zShort iff the subtype is MEM_Short */
845     assert( (x & MEM_Short)==0 || pMem->z==pMem->zShort );
846     assert( (x & MEM_Short)!=0 || pMem->z!=pMem->zShort );
847     /* No destructor unless there is MEM_Dyn */
848     assert( pMem->xDel==0 || (pMem->flags & MEM_Dyn)!=0 );
849 
850     if( (flags & MEM_Str) ){
851       assert( pMem->enc==SQLITE_UTF8 ||
852               pMem->enc==SQLITE_UTF16BE ||
853               pMem->enc==SQLITE_UTF16LE
854       );
855       /* If the string is UTF-8 encoded and nul terminated, then pMem->n
856       ** must be the length of the string.  (Later:)  If the database file
857       ** has been corrupted, '\000' characters might have been inserted
858       ** into the middle of the string.  In that case, the strlen() might
859       ** be less.
860       */
861       if( pMem->enc==SQLITE_UTF8 && (flags & MEM_Term) ){
862         assert( strlen(pMem->z)<=pMem->n );
863         assert( pMem->z[pMem->n]==0 );
864       }
865     }
866   }else{
867     /* Cannot define a string subtype for non-string objects */
868     assert( (pMem->flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short))==0 );
869     assert( pMem->xDel==0 );
870   }
871   /* MEM_Null excludes all other types */
872   assert( (pMem->flags&(MEM_Str|MEM_Int|MEM_Real|MEM_Blob))==0
873           || (pMem->flags&MEM_Null)==0 );
874   /* If the MEM is both real and integer, the values are equal */
875   assert( (pMem->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real)
876           || pMem->r==pMem->u.i );
877 }
878 #endif
879 
880 /* This function is only available internally, it is not part of the
881 ** external API. It works in a similar way to sqlite3_value_text(),
882 ** except the data returned is in the encoding specified by the second
883 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
884 ** SQLITE_UTF8.
885 **
886 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
887 ** If that is the case, then the result must be aligned on an even byte
888 ** boundary.
889 */
890 const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
891   if( !pVal ) return 0;
892 
893   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
894   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
895 
896   if( pVal->flags&MEM_Null ){
897     return 0;
898   }
899   assert( (MEM_Blob>>3) == MEM_Str );
900   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
901   expandBlob(pVal);
902   if( pVal->flags&MEM_Str ){
903     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
904     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&(sqlite3_intptr_t)pVal->z) ){
905       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
906       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
907         return 0;
908       }
909     }
910     sqlite3VdbeMemNulTerminate(pVal);
911   }else{
912     assert( (pVal->flags&MEM_Blob)==0 );
913     sqlite3VdbeMemStringify(pVal, enc);
914     assert( 0==(1&(sqlite3_intptr_t)pVal->z) );
915   }
916   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
917               || pVal->db->mallocFailed );
918   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
919     return pVal->z;
920   }else{
921     return 0;
922   }
923 }
924 
925 /*
926 ** Create a new sqlite3_value object.
927 */
928 sqlite3_value *sqlite3ValueNew(sqlite3 *db){
929   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
930   if( p ){
931     p->flags = MEM_Null;
932     p->type = SQLITE_NULL;
933     p->db = db;
934   }
935   return p;
936 }
937 
938 /*
939 ** Create a new sqlite3_value object, containing the value of pExpr.
940 **
941 ** This only works for very simple expressions that consist of one constant
942 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
943 ** be converted directly into a value, then the value is allocated and
944 ** a pointer written to *ppVal. The caller is responsible for deallocating
945 ** the value by passing it to sqlite3ValueFree() later on. If the expression
946 ** cannot be converted to a value, then *ppVal is set to NULL.
947 */
948 int sqlite3ValueFromExpr(
949   sqlite3 *db,              /* The database connection */
950   Expr *pExpr,              /* The expression to evaluate */
951   u8 enc,                   /* Encoding to use */
952   u8 affinity,              /* Affinity to use */
953   sqlite3_value **ppVal     /* Write the new value here */
954 ){
955   int op;
956   char *zVal = 0;
957   sqlite3_value *pVal = 0;
958 
959   if( !pExpr ){
960     *ppVal = 0;
961     return SQLITE_OK;
962   }
963   op = pExpr->op;
964 
965   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
966     zVal = sqlite3StrNDup((char*)pExpr->token.z, pExpr->token.n);
967     pVal = sqlite3ValueNew(db);
968     if( !zVal || !pVal ) goto no_mem;
969     sqlite3Dequote(zVal);
970     sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, sqlite3_free);
971     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
972       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, enc);
973     }else{
974       sqlite3ValueApplyAffinity(pVal, affinity, enc);
975     }
976   }else if( op==TK_UMINUS ) {
977     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
978       pVal->u.i = -1 * pVal->u.i;
979       pVal->r = -1.0 * pVal->r;
980     }
981   }
982 #ifndef SQLITE_OMIT_BLOB_LITERAL
983   else if( op==TK_BLOB ){
984     int nVal;
985     assert( pExpr->token.n>=3 );
986     assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
987     assert( pExpr->token.z[1]=='\'' );
988     assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
989     pVal = sqlite3ValueNew(db);
990     nVal = pExpr->token.n - 3;
991     zVal = (char*)pExpr->token.z + 2;
992     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
993                          0, sqlite3_free);
994   }
995 #endif
996 
997   *ppVal = pVal;
998   return SQLITE_OK;
999 
1000 no_mem:
1001   db->mallocFailed = 1;
1002   sqlite3_free(zVal);
1003   sqlite3ValueFree(pVal);
1004   *ppVal = 0;
1005   return SQLITE_NOMEM;
1006 }
1007 
1008 /*
1009 ** Change the string value of an sqlite3_value object
1010 */
1011 void sqlite3ValueSetStr(
1012   sqlite3_value *v,     /* Value to be set */
1013   int n,                /* Length of string z */
1014   const void *z,        /* Text of the new string */
1015   u8 enc,               /* Encoding to use */
1016   void (*xDel)(void*)   /* Destructor for the string */
1017 ){
1018   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
1019 }
1020 
1021 /*
1022 ** Free an sqlite3_value object
1023 */
1024 void sqlite3ValueFree(sqlite3_value *v){
1025   if( !v ) return;
1026   sqlite3VdbeMemRelease((Mem *)v);
1027   sqlite3_free(v);
1028 }
1029 
1030 /*
1031 ** Return the number of bytes in the sqlite3_value object assuming
1032 ** that it uses the encoding "enc"
1033 */
1034 int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
1035   Mem *p = (Mem*)pVal;
1036   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
1037     if( p->flags & MEM_Zero ){
1038       return p->n+p->u.i;
1039     }else{
1040       return p->n;
1041     }
1042   }
1043   return 0;
1044 }
1045