xref: /sqlite-3.40.0/src/vdbemem.c (revision ef5ecb41)
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 "os.h"
20 #include <ctype.h>
21 #include "vdbeInt.h"
22 
23 /*
24 ** If pMem is a string object, this routine sets the encoding of the string
25 ** (to one of UTF-8 or UTF16) and whether or not the string is
26 ** nul-terminated. If pMem is not a string object, then this routine is
27 ** a no-op.
28 **
29 ** The second argument, "desiredEnc" is one of TEXT_Utf8, TEXT_Utf16le
30 ** or TEXT_Utf16be.  This routine changes the encoding of pMem to match
31 ** desiredEnc.
32 **
33 ** SQLITE_OK is returned if the conversion is successful (or not required).
34 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
35 ** between formats.
36 */
37 int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
38   /* If this is not a string, or if it is a string but the encoding is
39   ** already correct, do nothing. */
40   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
41     return SQLITE_OK;
42   }
43 
44   if( pMem->enc==TEXT_Utf8 || desiredEnc==TEXT_Utf8 ){
45     /* If the current encoding does not match the desired encoding, then
46     ** we will need to do some translation between encodings.
47     */
48     char *z;
49     int n;
50     int rc;
51 
52     rc = sqlite3utfTranslate(pMem->z, pMem->n, pMem->enc, &z, &n, desiredEnc);
53     if( rc!=SQLITE_OK ){
54       return rc;
55     }
56     if( pMem->flags&MEM_Dyn ){
57       sqliteFree(pMem->z);
58     }
59     /* Result of sqlite3utfTranslate is currently always dynamically
60     ** allocated and nul terminated. This might be altered as a performance
61     ** enhancement later.
62     */
63     pMem->z = z;
64     pMem->n = n;
65     pMem->flags &= ~(MEM_Ephem | MEM_Short | MEM_Static);
66     pMem->flags |= MEM_Str | MEM_Dyn | MEM_Term;
67   }else{
68     /* Must be translating between UTF-16le and UTF-16be. */
69     int i;
70     u8 *pFrom, *pTo;
71     sqlite3VdbeMemMakeWriteable(pMem);
72     for(i=0, pFrom=pMem->z, pTo=&pMem->z[1]; i<pMem->n; i+=2, pFrom+=2,pTo+=2){
73       u8 temp = *pFrom;
74       *pFrom = *pTo;
75       *pTo = temp;
76     }
77   }
78   pMem->enc = desiredEnc;
79   return SQLITE_OK;
80 }
81 
82 /*
83 ** Make the given Mem object MEM_Dyn.
84 **
85 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
86 */
87 int sqlite3VdbeMemDynamicify(Mem *pMem){
88   int n = pMem->n;
89   u8 *z;
90   if( (pMem->flags & (MEM_Ephem|MEM_Static|MEM_Short))==0 ){
91     return SQLITE_OK;
92   }
93   assert( (pMem->flags & MEM_Dyn)==0 );
94   assert( pMem->flags & (MEM_Str|MEM_Blob) );
95   z = sqliteMallocRaw( n+2 );
96   if( z==0 ){
97     return SQLITE_NOMEM;
98   }
99   pMem->flags |= MEM_Dyn|MEM_Term;
100   memcpy(z, pMem->z, n );
101   z[n] = 0;
102   z[n+1] = 0;
103   pMem->z = z;
104   pMem->flags &= ~(MEM_Ephem|MEM_Static|MEM_Short);
105   return SQLITE_OK;
106 }
107 
108 /*
109 ** Make the given Mem object either MEM_Short or MEM_Dyn so that bytes
110 ** of the Mem.z[] array can be modified.
111 **
112 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
113 */
114 int sqlite3VdbeMemMakeWriteable(Mem *pMem){
115   int n;
116   u8 *z;
117   if( (pMem->flags & (MEM_Ephem|MEM_Static))==0 ){
118     return SQLITE_OK;
119   }
120   assert( (pMem->flags & MEM_Dyn)==0 );
121   assert( pMem->flags & (MEM_Str|MEM_Blob) );
122   if( (n = pMem->n)+2<sizeof(pMem->zShort) ){
123     z = pMem->zShort;
124     pMem->flags |= MEM_Short|MEM_Term;
125   }else{
126     z = sqliteMallocRaw( n+2 );
127     if( z==0 ){
128       return SQLITE_NOMEM;
129     }
130     pMem->flags |= MEM_Dyn|MEM_Term;
131   }
132   memcpy(z, pMem->z, n );
133   z[n] = 0;
134   z[n+1] = 0;
135   pMem->z = z;
136   pMem->flags &= ~(MEM_Ephem|MEM_Static);
137   return SQLITE_OK;
138 }
139 
140 /*
141 ** Make sure the given Mem is \u0000 terminated.
142 */
143 int sqlite3VdbeMemNulTerminate(Mem *pMem){
144   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & (MEM_Str|MEM_Blob))==0 ){
145     return SQLITE_OK;   /* Nothing to do */
146   }
147   /* Only static or ephemeral strings can be unterminated */
148   assert( (pMem->flags & (MEM_Static|MEM_Ephem))!=0 );
149   return sqlite3VdbeMemMakeWriteable(pMem);
150 }
151 
152 /*
153 ** Add MEM_Str to the set of representations for the given Mem.
154 ** A NULL is converted into an empty string.  Numbers are converted
155 ** using sqlite3_snprintf().  Converting a BLOB to a string is a
156 ** no-op.
157 **
158 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
159 ** But MEM_Null is.
160 */
161 int sqlite3VdbeMemStringify(Mem *pMem, int enc){
162   int rc = SQLITE_OK;
163   int fg = pMem->flags;
164 
165   assert( !(fg&(MEM_Str|MEM_Blob)) );
166   assert( fg&(MEM_Int|MEM_Real|MEM_Null) );
167 
168   if( fg & MEM_Null ){
169     /* A NULL value is converted to a zero length string */
170     u8 *z = pMem->zShort;
171     z[0] = 0;
172     z[1] = 0;
173     pMem->flags = MEM_Str | MEM_Short | MEM_Term;
174     pMem->z = z;
175     pMem->n = 0;
176     pMem->enc = enc;
177   }else{
178     /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
179     ** string representation of the value. Then, if the required encoding
180     ** is UTF-16le or UTF-16be do a translation.
181     **
182     ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
183     */
184     u8 *z = pMem->zShort;
185     if( fg & MEM_Real || (pMem->type==SQLITE_FLOAT) ){
186       sqlite3_snprintf(NBFS, z, "%.15g", pMem->r);
187     }else{
188       assert( fg & MEM_Int );
189       sqlite3_snprintf(NBFS, z, "%lld", pMem->i);
190     }
191     pMem->n = strlen(z);
192     pMem->z = z;
193     pMem->enc = TEXT_Utf8;
194     pMem->flags |= MEM_Str | MEM_Short | MEM_Term;
195     sqlite3VdbeChangeEncoding(pMem, enc);
196   }
197   return rc;
198 }
199 
200 /*
201 ** Release any memory held by the Mem
202 */
203 static void releaseMem(Mem *p){
204   if( p->flags & MEM_Dyn ){
205     sqliteFree(p->z);
206     p->z = 0;
207   }
208 }
209 
210 /*
211 ** Convert the Mem to have representation MEM_Int only.  All
212 ** prior representations are invalidated.  NULL is converted into 0.
213 */
214 int sqlite3VdbeMemIntegerify(Mem *pMem){
215   int flags = pMem->flags;
216   if( flags & MEM_Int ){
217     /* Do nothing */
218   }else if( flags & MEM_Real ){
219     pMem->i = (i64)pMem->r;
220   }else if( flags & (MEM_Str|MEM_Blob) ){
221     if( sqlite3VdbeChangeEncoding(pMem, TEXT_Utf8)
222        || sqlite3VdbeMemNulTerminate(pMem) ){
223       return SQLITE_NOMEM;
224     }
225     assert( pMem->z );
226     sqlite3atoi64(pMem->z, &pMem->i);
227   }else{
228     pMem->i = 0;
229   }
230   pMem->flags |= MEM_Int;
231   return SQLITE_OK;
232 }
233 
234 /*
235 ** Add MEM_Real to the set of representations for pMem.  Prior
236 ** prior representations other than MEM_Null retained.  NULL is
237 ** converted into 0.0.
238 */
239 int sqlite3VdbeMemRealify(Mem *pMem){
240   if( pMem->flags & MEM_Real ){
241     /* Do nothing */
242   }else if( (pMem->flags & MEM_Int) && pMem->type!=SQLITE_TEXT ){
243     pMem->r = pMem->i;
244   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
245     if( sqlite3VdbeChangeEncoding(pMem, TEXT_Utf8)
246        || sqlite3VdbeMemNulTerminate(pMem) ){
247       return SQLITE_NOMEM;
248     }
249     assert( pMem->z );
250     pMem->r = sqlite3AtoF(pMem->z, 0);
251   }else{
252     pMem->r = 0.0;
253   }
254   pMem->flags |= MEM_Real;
255   return SQLITE_OK;
256 }
257 
258 /*
259 ** Delete any previous value and set the value stored in *pMem to NULL.
260 */
261 void sqlite3VdbeMemSetNull(Mem *pMem){
262   releaseMem(pMem);
263   pMem->flags = MEM_Null;
264   pMem->type = SQLITE_NULL;
265 }
266 
267 /*
268 ** Delete any previous value and set the value stored in *pMem to val,
269 ** manifest type INTEGER.
270 */
271 void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
272   releaseMem(pMem);
273   pMem->i = val;
274   pMem->flags = MEM_Int;
275   pMem->type = SQLITE_INTEGER;
276 }
277 
278 /*
279 ** Delete any previous value and set the value stored in *pMem to val,
280 ** manifest type REAL.
281 */
282 void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
283   releaseMem(pMem);
284   pMem->r = val;
285   pMem->flags = MEM_Real;
286   pMem->type = SQLITE_FLOAT;
287 }
288 
289 /*
290 ** Copy the contents of memory cell pFrom into pTo.
291 */
292 int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
293   releaseMem(pTo);
294   memcpy(pTo, pFrom, sizeof(*pFrom)-sizeof(pFrom->zShort));
295   if( pTo->flags & (MEM_Str|MEM_Blob) ){
296     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Short);
297     pTo->flags |= MEM_Ephem;
298     sqlite3VdbeMemMakeWriteable(pTo);
299   }
300   return SQLITE_OK;
301 }
302 
303 /*
304 ** Change the value of a Mem to be a string or a BLOB.
305 */
306 int sqlite3VdbeMemSetStr(
307   Mem *pMem,          /* Memory cell to set to string value */
308   const char *z,      /* String pointer */
309   int n,              /* Bytes in string, or negative */
310   u8 enc,             /* Encoding of z.  0 for BLOBs */
311   int eCopy           /* True if this function should make a copy of z */
312 ){
313   releaseMem(pMem);
314   if( !z ){
315     pMem->flags = MEM_Null;
316     pMem->type = SQLITE_NULL;
317     return SQLITE_OK;
318   }
319 
320   pMem->z = (char *)z;
321   if( eCopy ){
322     pMem->flags = MEM_Ephem;
323   }else{
324     pMem->flags = MEM_Static;
325   }
326   pMem->enc = enc;
327   pMem->type = enc==0 ? SQLITE_BLOB : SQLITE_TEXT;
328   pMem->n = n;
329   switch( enc ){
330     case 0:
331       pMem->flags |= MEM_Blob;
332       break;
333 
334     case TEXT_Utf8:
335       pMem->flags |= MEM_Str;
336       if( n<0 ){
337         pMem->n = strlen(z);
338         pMem->flags |= MEM_Term;
339       }
340       break;
341 
342     case TEXT_Utf16le:
343     case TEXT_Utf16be:
344       pMem->flags |= MEM_Str;
345       if( n<0 ){
346         pMem->n = sqlite3utf16ByteLen(z,-1);
347         pMem->flags |= MEM_Term;
348       }
349       break;
350 
351     default:
352       assert(0);
353   }
354   if( eCopy ){
355     return sqlite3VdbeMemMakeWriteable(pMem);
356   }
357   return SQLITE_OK;
358 }
359 
360 /*
361 ** Compare the values contained by the two memory cells, returning
362 ** negative, zero or positive if pMem1 is less than, equal to, or greater
363 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
364 ** and reals) sorted numerically, followed by text ordered by the collating
365 ** sequence pColl and finally blob's ordered by memcmp().
366 **
367 ** Two NULL values are considered equal by this function.
368 */
369 int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
370   int rc;
371   int f1, f2;
372   int combined_flags;
373 
374   /* Interchange pMem1 and pMem2 if the collating sequence specifies
375   ** DESC order.
376   */
377   f1 = pMem1->flags;
378   f2 = pMem2->flags;
379   combined_flags = f1|f2;
380 
381   /* If one value is NULL, it is less than the other. If both values
382   ** are NULL, return 0.
383   */
384   if( combined_flags&MEM_Null ){
385     return (f2&MEM_Null) - (f1&MEM_Null);
386   }
387 
388   /* If one value is a number and the other is not, the number is less.
389   ** If both are numbers, compare as reals if one is a real, or as integers
390   ** if both values are integers.
391   */
392   if( combined_flags&(MEM_Int|MEM_Real) ){
393     if( !(f1&(MEM_Int|MEM_Real)) ){
394       return 1;
395     }
396     if( !(f2&(MEM_Int|MEM_Real)) ){
397       return -1;
398     }
399     if( (f1 & f2 & MEM_Int)==0 ){
400       double r1, r2;
401       if( (f1&MEM_Real)==0 ){
402         r1 = pMem1->i;
403       }else{
404         r1 = pMem1->r;
405       }
406       if( (f2&MEM_Real)==0 ){
407         r2 = pMem2->i;
408       }else{
409         r2 = pMem2->r;
410       }
411       if( r1<r2 ) return -1;
412       if( r1>r2 ) return 1;
413       return 0;
414     }else{
415       assert( f1&MEM_Int );
416       assert( f2&MEM_Int );
417       if( pMem1->i < pMem2->i ) return -1;
418       if( pMem1->i > pMem2->i ) return 1;
419       return 0;
420     }
421   }
422 
423   /* If one value is a string and the other is a blob, the string is less.
424   ** If both are strings, compare using the collating functions.
425   */
426   if( combined_flags&MEM_Str ){
427     if( (f1 & MEM_Str)==0 ){
428       return 1;
429     }
430     if( (f2 & MEM_Str)==0 ){
431       return -1;
432     }
433 
434     assert( pMem1->enc==pMem2->enc );
435     assert( pMem1->enc==TEXT_Utf8 ||
436             pMem1->enc==TEXT_Utf16le || pMem1->enc==TEXT_Utf16be );
437 
438     /* FIX ME: This may fail if the collation sequence is deleted after
439     ** this vdbe program is compiled. We cannot just use BINARY in this
440     ** case as this may lead to a segfault caused by traversing an index
441     ** table incorrectly.  We need to return an error to the user in this
442     ** case.
443     */
444     assert( !pColl || pColl->xCmp );
445 
446     if( pColl ){
447       if( pMem1->enc==pColl->enc ){
448         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
449       }else{
450         return pColl->xCmp(
451           pColl->pUser,
452           sqlite3ValueBytes((sqlite3_value*)pMem1, pColl->enc),
453           sqlite3ValueText((sqlite3_value*)pMem1, pColl->enc),
454           sqlite3ValueBytes((sqlite3_value*)pMem2, pColl->enc),
455           sqlite3ValueText((sqlite3_value*)pMem2, pColl->enc)
456         );
457       }
458     }
459     /* If a NULL pointer was passed as the collate function, fall through
460     ** to the blob case and use memcmp().  */
461   }
462 
463   /* Both values must be blobs.  Compare using memcmp().  */
464   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
465   if( rc==0 ){
466     rc = pMem1->n - pMem2->n;
467   }
468   return rc;
469 }
470 
471 /*
472 ** Move data out of a btree key or data field and into a Mem structure.
473 ** The data or key is taken from the entry that pCur is currently pointing
474 ** to.  offset and amt determine what portion of the data or key to retrieve.
475 ** key is true to get the key or false to get data.  The result is written
476 ** into the pMem element.
477 **
478 ** The pMem structure is assumed to be uninitialized.  Any prior content
479 ** is overwritten without being freed.
480 **
481 ** If this routine fails for any reason (malloc returns NULL or unable
482 ** to read from the disk) then the pMem is left in an inconsistent state.
483 */
484 int sqlite3VdbeMemFromBtree(
485   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
486   int offset,       /* Offset from the start of data to return bytes from. */
487   int amt,          /* Number of bytes to return. */
488   int key,          /* If true, retrieve from the btree key, not data. */
489   Mem *pMem         /* OUT: Return data in this Mem structure. */
490 ){
491   char *zData;      /* Data from the btree layer */
492   int available;    /* Number of bytes available on the local btree page */
493 
494   if( key ){
495     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
496   }else{
497     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
498   }
499 
500   pMem->n = amt;
501   if( offset+amt<=available ){
502     pMem->z = &zData[offset];
503     pMem->flags = MEM_Blob|MEM_Ephem;
504   }else{
505     int rc;
506     if( amt>NBFS-2 ){
507       zData = (char *)sqliteMallocRaw(amt+2);
508       if( !zData ){
509         return SQLITE_NOMEM;
510       }
511       pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
512     }else{
513       zData = &(pMem->zShort[0]);
514       pMem->flags = MEM_Blob|MEM_Short|MEM_Term;
515     }
516     pMem->z = zData;
517     pMem->enc = 0;
518     pMem->type = SQLITE_BLOB;
519 
520     if( key ){
521       rc = sqlite3BtreeKey(pCur, offset, amt, zData);
522     }else{
523       rc = sqlite3BtreeData(pCur, offset, amt, zData);
524     }
525     zData[amt] = 0;
526     zData[amt+1] = 0;
527     if( rc!=SQLITE_OK ){
528       if( amt>NBFS ){
529         sqliteFree(zData);
530       }
531       return rc;
532     }
533   }
534 
535   return SQLITE_OK;
536 }
537 
538 #ifndef NDEBUG
539 /*
540 ** Perform various checks on the memory cell pMem. An assert() will
541 ** fail if pMem is internally inconsistent.
542 */
543 void sqlite3VdbeMemSanity(Mem *pMem, u8 db_enc){
544   int flags = pMem->flags;
545   assert( flags!=0 );  /* Must define some type */
546   if( pMem->flags & (MEM_Str|MEM_Blob) ){
547     int x = pMem->flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short);
548     assert( x!=0 );            /* Strings must define a string subtype */
549     assert( (x & (x-1))==0 );  /* Only one string subtype can be defined */
550     assert( pMem->z!=0 );      /* Strings must have a value */
551     /* Mem.z points to Mem.zShort iff the subtype is MEM_Short */
552     assert( (pMem->flags & MEM_Short)==0 || pMem->z==pMem->zShort );
553     assert( (pMem->flags & MEM_Short)!=0 || pMem->z!=pMem->zShort );
554 
555     if( (flags & MEM_Str) ){
556       assert( pMem->enc==TEXT_Utf8 ||
557               pMem->enc==TEXT_Utf16le ||
558               pMem->enc==TEXT_Utf16be
559       );
560       /* If the string is UTF-8 encoded and nul terminated, then pMem->n
561       ** must be the length of the string.
562       */
563       if( pMem->enc==TEXT_Utf8 && (flags & MEM_Term) ){
564         assert( strlen(pMem->z)==pMem->n );
565       }
566     }
567   }else{
568     /* Cannot define a string subtype for non-string objects */
569     assert( (pMem->flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short))==0 );
570   }
571   /* MEM_Null excludes all other types */
572   assert( (pMem->flags&(MEM_Str|MEM_Int|MEM_Real|MEM_Blob))==0
573           || (pMem->flags&MEM_Null)==0 );
574 }
575 #endif
576 
577 /* This function is only available internally, it is not part of the
578 ** external API. It works in a similar way to sqlite3_value_text(),
579 ** except the data returned is in the encoding specified by the second
580 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
581 ** SQLITE_UTF8.
582 */
583 const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
584   assert( enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE || enc==SQLITE_UTF8);
585   if( pVal->flags&MEM_Null ){
586     /* For a NULL return a NULL Pointer */
587     return 0;
588   }
589 
590   if( pVal->flags&MEM_Str ){
591     /* If there is already a string representation, make sure it is in
592     ** encoded in the required UTF-16 byte order.
593     */
594     sqlite3VdbeChangeEncoding(pVal, enc);
595   }else if( !(pVal->flags&MEM_Blob) ){
596     /* Otherwise, unless this is a blob, convert it to a UTF-16 string */
597     sqlite3VdbeMemStringify(pVal, enc);
598   }
599 
600   return (const void *)(pVal->z);
601 }
602 
603 sqlite3_value* sqlite3ValueNew(){
604   Mem *p = sqliteMalloc(sizeof(*p));
605   if( p ){
606     p->flags = MEM_Null;
607     p->type = SQLITE_NULL;
608   }
609   return p;
610 }
611 
612 void sqlite3ValueSetStr(sqlite3_value *v, int n, const void *z, u8 enc){
613   Mem *p = (Mem *)v;
614   if( p->z && p->flags&MEM_Dyn ){
615     sqliteFree(p->z);
616   }
617   p->z = (char *)z;
618   p->n = n;
619   p->enc = enc;
620   p->type = SQLITE_TEXT;
621   p->flags = (MEM_Str|MEM_Static);
622 
623   if( p->n<0 ){
624     if( enc==SQLITE_UTF8 ){
625       p->n = strlen(p->z);
626     }else{
627       p->n = sqlite3utf16ByteLen(p->z, -1);
628     }
629   }
630   return;
631 }
632 
633 void sqlite3ValueFree(sqlite3_value *v){
634   sqlite3ValueSetStr(v, 0, 0, SQLITE_UTF8);
635   sqliteFree(v);
636 }
637 
638 int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
639   Mem *p = (Mem*)pVal;
640   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
641     return p->n;
642   }
643   return 0;
644 }
645