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