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