SQLite4
Check-in [209c12ae0b]
Not logged in

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Merge trunk changes.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | embedded-btree
Files: files | file ages | folders
SHA1: 209c12ae0bc27040076b253af35574064850dba7
User & Date: dan 2012-06-26 20:39:01
Context
2012-06-27
10:22
Ensure that "expensive-assert" code only runs when LSM_DEBUG_EXPENSIVE is defined. check-in: 2be9bac408 user: dan tags: embedded-btree
2012-06-26
20:39
Merge trunk changes. check-in: 209c12ae0b user: dan tags: embedded-btree
20:17
Updates to the design and storage documents. check-in: f19a93d9f9 user: drh tags: trunk
19:45
Fix a bug causing an infinite loop if there are open cursors when the in-memory tree is flushed to disk. check-in: d409cd8c8a user: dan tags: embedded-btree
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to src/alter.c.

75
76
77
78
79
80
81
82

83
84
85
86
87
88
89
...
137
138
139
140
141
142
143
144
145

146
147
148
149
150
151
152
...
214
215
216
217
218
219
220
221

222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
        len = sqlite4GetToken(zCsr, &token);
      } while( token==TK_SPACE );
      assert( len>0 );
    } while( token!=TK_LP && token!=TK_USING );

    zRet = sqlite4MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
       zTableName, tname.z+tname.n);
    sqlite4_result_text(context, zRet, -1, SQLITE_DYNAMIC);

  }
}

/*
** This C function implements an SQL user function that is used by SQL code
** generated by the ALTER TABLE ... RENAME command to modify the definition
** of any foreign key constraints that use the table being renamed as the 
................................................................................
        zInput = &z[n];
      }
      sqlite4DbFree(db, zParent);
    }
  }

  zResult = sqlite4MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
  sqlite4_result_text(context, zResult, -1, SQLITE_DYNAMIC);
  sqlite4DbFree(db, zOutput);

}
#endif

#ifndef SQLITE_OMIT_TRIGGER
/* This function is used by SQL generated to implement the
** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
** statement. The second is a table name. The table name in the CREATE 
................................................................................
    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );

    /* Variable tname now contains the token that is the old table-name
    ** in the CREATE TRIGGER statement.
    */
    zRet = sqlite4MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
       zTableName, tname.z+tname.n);
    sqlite4_result_text(context, zRet, -1, SQLITE_DYNAMIC);

  }
}
#endif   /* !SQLITE_OMIT_TRIGGER */

/*
** Register built-in functions used to help implement ALTER TABLE
*/
void sqlite4AlterFunctions(void){
  static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
    FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
#ifndef SQLITE_OMIT_TRIGGER
    FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
#endif
#ifndef SQLITE_OMIT_FOREIGN_KEY
    FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
#endif
  };
  int i;
  FuncDefHash *pHash = &sqlite4GlobalFunctions;
  FuncDef *aFunc = (FuncDef*)aAlterTableFuncs;

  for(i=0; i<ArraySize(aAlterTableFuncs); i++){
    sqlite4FuncDefInsert(pHash, &aFunc[i]);
  }
}

/*
** This function is used to create the text of expressions of the form:
**
**   name=<constant1> OR name=<constant2> OR ...







|
>







 







|

>







 







|
>







|
|









|



|







75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
...
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
...
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
        len = sqlite4GetToken(zCsr, &token);
      } while( token==TK_SPACE );
      assert( len>0 );
    } while( token!=TK_LP && token!=TK_USING );

    zRet = sqlite4MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
       zTableName, tname.z+tname.n);
    sqlite4_result_text(context, zRet, -1, SQLITE_TRANSIENT);
    sqlite4DbFree(db, zRet);
  }
}

/*
** This C function implements an SQL user function that is used by SQL code
** generated by the ALTER TABLE ... RENAME command to modify the definition
** of any foreign key constraints that use the table being renamed as the 
................................................................................
        zInput = &z[n];
      }
      sqlite4DbFree(db, zParent);
    }
  }

  zResult = sqlite4MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
  sqlite4_result_text(context, zResult, -1, SQLITE_TRANSIENT);
  sqlite4DbFree(db, zOutput);
  sqlite4DbFree(db, zResult);
}
#endif

#ifndef SQLITE_OMIT_TRIGGER
/* This function is used by SQL generated to implement the
** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
** statement. The second is a table name. The table name in the CREATE 
................................................................................
    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );

    /* Variable tname now contains the token that is the old table-name
    ** in the CREATE TRIGGER statement.
    */
    zRet = sqlite4MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
       zTableName, tname.z+tname.n);
    sqlite4_result_text(context, zRet, -1, SQLITE_TRANSIENT);
    sqlite4DbFree(db, zRet);
  }
}
#endif   /* !SQLITE_OMIT_TRIGGER */

/*
** Register built-in functions used to help implement ALTER TABLE
*/
void sqlite4AlterFunctions(sqlite4_env *pEnv){
  static FuncDef aAlterTableFuncs[] = {
    FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
#ifndef SQLITE_OMIT_TRIGGER
    FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
#endif
#ifndef SQLITE_OMIT_FOREIGN_KEY
    FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
#endif
  };
  int i;
  FuncDefTable *pFuncTab = &pEnv->aGlobalFuncs;
  FuncDef *aFunc = (FuncDef*)aAlterTableFuncs;

  for(i=0; i<ArraySize(aAlterTableFuncs); i++){
    sqlite4FuncDefInsert(pFuncTab, &aFunc[i], 1);
  }
}

/*
** This function is used to create the text of expressions of the form:
**
**   name=<constant1> OR name=<constant2> OR ...

Changes to src/attach.c.

131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
  rc = sqlite4ParseUri(db->pEnv, zFile, &flags, &zPath, &zErr);
  if( rc!=SQLITE_OK ){
    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
    sqlite4_result_error(context, zErr, -1);
    sqlite4_free(db->pEnv, zErr);
    return;
  }
  flags |= SQLITE_OPEN_MAIN_DB;
  rc = sqlite4KVStoreOpen(db, zName, zPath, &aNew->pKV, 0);
  sqlite4_free(db->pEnv, zPath);
  db->nDb++;
  if( rc==SQLITE_CONSTRAINT ){
    rc = SQLITE_ERROR;
    zErrDyn = sqlite4MPrintf(db, "database is already attached");
  }else if( rc==SQLITE_OK ){
    aNew->pSchema = sqlite4SchemaGet(db);







<
|







131
132
133
134
135
136
137

138
139
140
141
142
143
144
145
  rc = sqlite4ParseUri(db->pEnv, zFile, &flags, &zPath, &zErr);
  if( rc!=SQLITE_OK ){
    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
    sqlite4_result_error(context, zErr, -1);
    sqlite4_free(db->pEnv, zErr);
    return;
  }

  rc = sqlite4KVStoreOpen(db, zName, zPath, &aNew->pKV, flags);
  sqlite4_free(db->pEnv, zPath);
  db->nDb++;
  if( rc==SQLITE_CONSTRAINT ){
    rc = SQLITE_ERROR;
    zErrDyn = sqlite4MPrintf(db, "database is already attached");
  }else if( rc==SQLITE_OK ){
    aNew->pSchema = sqlite4SchemaGet(db);

Changes to src/build.c.

3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
** Make sure the TEMP database is open and available for use.  Return
** the number of errors.  Leave any error messages in the pParse structure.
*/
int sqlite4OpenTempDatabase(Parse *pParse){
  sqlite4 *db = pParse->db;
  if( db->aDb[1].pKV==0 && !pParse->explain ){
    int rc;
#if 0
    static const int flags = 
          SQLITE_OPEN_READWRITE |
          SQLITE_OPEN_CREATE |
          SQLITE_OPEN_EXCLUSIVE |
          SQLITE_OPEN_DELETEONCLOSE |
          SQLITE_OPEN_TEMP_DB;
#endif

    rc = sqlite4KVStoreOpen(db, "temp", ":memory:", &db->aDb[1].pKV,
                            SQLITE_KVOPEN_TEMPORARY);
    if( rc!=SQLITE_OK ){
      sqlite4ErrorMsg(pParse, "unable to open a temporary database "
        "file for storing temporary tables");
      pParse->rc = rc;
      return 1;







<
<
<
<
<
<
<
<
<







3323
3324
3325
3326
3327
3328
3329









3330
3331
3332
3333
3334
3335
3336
** Make sure the TEMP database is open and available for use.  Return
** the number of errors.  Leave any error messages in the pParse structure.
*/
int sqlite4OpenTempDatabase(Parse *pParse){
  sqlite4 *db = pParse->db;
  if( db->aDb[1].pKV==0 && !pParse->explain ){
    int rc;









    rc = sqlite4KVStoreOpen(db, "temp", ":memory:", &db->aDb[1].pKV,
                            SQLITE_KVOPEN_TEMPORARY);
    if( rc!=SQLITE_OK ){
      sqlite4ErrorMsg(pParse, "unable to open a temporary database "
        "file for storing temporary tables");
      pParse->rc = rc;
      return 1;

Changes to src/callback.c.

255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271

272
273
274
275
276
277
278
279
280
281






282
283
284
285

286
287
288
289
290
291
292
293












294
295
296
297
298


299

300
301
302
303
304
305
306
...
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
...
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
...
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
      match += 1;
    }
  }
  return match;
}

/*
** Search a FuncDefHash for a function with the given name.  Return
** a pointer to the matching FuncDef if found, or 0 if there is no match.
*/
static FuncDef *functionSearch(
  FuncDefHash *pHash,  /* Hash table to search */
  int h,               /* Hash of the name */
  const char *zFunc,   /* Name of function */
  int nFunc            /* Number of bytes in zFunc */
){
  FuncDef *p;

  for(p=pHash->a[h]; p; p=p->pHash){
    if( sqlite4StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
      return p;
    }
  }
  return 0;
}

/*
** Insert a new FuncDef into a FuncDefHash hash table.






*/
void sqlite4FuncDefInsert(
  FuncDefHash *pHash,  /* The hash table into which to insert */
  FuncDef *pDef        /* The function definition to insert */

){
  FuncDef *pOther;
  int nName = sqlite4Strlen30(pDef->zName);
  u8 c1 = (u8)pDef->zName[0];
  int h = (sqlite4UpperToLower[c1] + nName) % ArraySize(pHash->a);
  pOther = functionSearch(pHash, h, pDef->zName, nName);
  if( pOther ){
    assert( pOther!=pDef && pOther->pNext!=pDef );












    pDef->pNext = pOther->pNext;
    pOther->pNext = pDef;
  }else{
    pDef->pNext = 0;
    pDef->pHash = pHash->a[h];


    pHash->a[h] = pDef;

  }
}
  
  

/*
** Locate a user function given a name, a number of arguments and a flag
................................................................................
  int nArg,          /* Number of arguments.  -1 means any number */
  u8 enc,            /* Preferred text encoding */
  int createFlag     /* Create new entry if true and does not otherwise exist */
){
  FuncDef *p;         /* Iterator variable */
  FuncDef *pBest = 0; /* Best match found so far */
  int bestScore = 0;  /* Score of best match */
  int h;              /* Hash value */


  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  h = (sqlite4UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);

  /* First search for a match amongst the application-defined functions.
  */
  p = functionSearch(&db->aFunc, h, zName, nName);
  while( p ){
    int score = matchQuality(p, nArg, enc);
    if( score>bestScore ){
      pBest = p;
      bestScore = score;
    }
    p = p->pNext;
  }

  /* If no match is found, search the built-in functions.
  **
  ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
  ** functions even if a prior app-defined function was found.  And give
  ** priority to built-in functions.
................................................................................
  ** Except, if createFlag is true, that means that we are trying to
  ** install a new function.  Whatever FuncDef structure is returned it will
  ** have fields overwritten with new information appropriate for the
  ** new function.  But the FuncDefs for built-in functions are read-only.
  ** So we must not search for built-ins when creating a new function.
  */ 
  if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
    FuncDefHash *pHash = &sqlite4GlobalFunctions;
    bestScore = 0;
    p = functionSearch(pHash, h, zName, nName);
    while( p ){
      int score = matchQuality(p, nArg, enc);
      if( score>bestScore ){
        pBest = p;
        bestScore = score;
      }
      p = p->pNext;
    }
  }

  /* If the createFlag parameter is true and the search did not reveal an
  ** exact match for the name, number of arguments and encoding, then add a
  ** new entry to the hash table and return it.
  */
................................................................................
  if( createFlag && (bestScore<6 || pBest->nArg!=nArg) && 
      (pBest = sqlite4DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
    pBest->zName = (char *)&pBest[1];
    pBest->nArg = (u16)nArg;
    pBest->iPrefEnc = enc;
    memcpy(pBest->zName, zName, nName);
    pBest->zName[nName] = 0;
    sqlite4FuncDefInsert(&db->aFunc, pBest);
  }

  if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
    return pBest;
  }
  return 0;
}







|



|
<
|
|


>
|








|
>
>
>
>
>
>


|
|
>


<
<
<
<
<
<
>
>
>
>
>
>
>
>
>
>
>
>
|
|

<
<
>
>
|
>







 







<



<



|






|







 







|

|






|







 







|







255
256
257
258
259
260
261
262
263
264
265
266

267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294






295
296
297
298
299
300
301
302
303
304
305
306
307
308
309


310
311
312
313
314
315
316
317
318
319
320
...
343
344
345
346
347
348
349

350
351
352

353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
...
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
...
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
      match += 1;
    }
  }
  return match;
}

/*
** Search a FuncDefTable for a function with the given name.  Return
** a pointer to the matching FuncDef if found, or 0 if there is no match.
*/
static FuncDef *functionSearch(
  FuncDefTable *pFuncTab,  /* Lookup table to search */

  const char *zFunc,       /* Name of function */
  int nFunc                /* Number of bytes in zFunc */
){
  FuncDef *p;
  if( nFunc<0 ) nFunc = sqlite4Strlen30(zFunc);
  for(p=pFuncTab->pFirst; p; p=p->pNextName){
    if( sqlite4StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
      return p;
    }
  }
  return 0;
}

/*
** Insert a new FuncDef into a FuncDefTable.
**
** The pDef is private to a single database connection if isBuiltIn==0 but
** is a global public function if isBuiltIn==1.  In the case of isBuiltIn==1,
** any changes to pDef are made in a way that is threadsafe, so that if two
** threads attempt to build the global function table at the same time, the
** trailing thread will perform harmless no-op assignments.
*/
void sqlite4FuncDefInsert(
  FuncDefTable *pFuncTab,  /* The lookup table into which to insert */
  FuncDef *pDef,           /* The function definition to insert */
  int isBuiltIn            /* True if pDef is one of the built-in functions */
){
  FuncDef *pOther;






  assert( pDef->pSameName==0 || isBuiltIn );
  assert( pDef->pNextName==0 || isBuiltIn );
  if( pFuncTab->pFirst==0 ){
    pFuncTab->pFirst = pDef;
    pFuncTab->pLast = pDef;
    pFuncTab->pSame = pDef;
  }else if( isBuiltIn
            && sqlite4StrICmp(pDef->zName, pFuncTab->pLast->zName)==0 ){
    assert( pFuncTab->pSame->pSameName==0 || pFuncTab->pSame->pSameName==pDef );
    pFuncTab->pSame->pSameName = pDef;
    pFuncTab->pSame = pDef;
  }else if( !isBuiltIn && (pOther=functionSearch(pFuncTab,pDef->zName,-1))!=0 ){
    pDef->pSameName = pOther->pSameName;
    pOther->pSameName = pDef;
  }else{


    assert( pFuncTab->pLast->pNextName==0 || pFuncTab->pLast->pNextName==pDef );
    pFuncTab->pLast->pNextName = pDef;
    pFuncTab->pLast = pDef;
    pFuncTab->pSame = pDef;
  }
}
  
  

/*
** Locate a user function given a name, a number of arguments and a flag
................................................................................
  int nArg,          /* Number of arguments.  -1 means any number */
  u8 enc,            /* Preferred text encoding */
  int createFlag     /* Create new entry if true and does not otherwise exist */
){
  FuncDef *p;         /* Iterator variable */
  FuncDef *pBest = 0; /* Best match found so far */
  int bestScore = 0;  /* Score of best match */



  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );


  /* First search for a match amongst the application-defined functions.
  */
  p = functionSearch(&db->aFunc, zName, nName);
  while( p ){
    int score = matchQuality(p, nArg, enc);
    if( score>bestScore ){
      pBest = p;
      bestScore = score;
    }
    p = p->pSameName;
  }

  /* If no match is found, search the built-in functions.
  **
  ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
  ** functions even if a prior app-defined function was found.  And give
  ** priority to built-in functions.
................................................................................
  ** Except, if createFlag is true, that means that we are trying to
  ** install a new function.  Whatever FuncDef structure is returned it will
  ** have fields overwritten with new information appropriate for the
  ** new function.  But the FuncDefs for built-in functions are read-only.
  ** So we must not search for built-ins when creating a new function.
  */ 
  if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
    FuncDefTable *pFuncTab = &db->pEnv->aGlobalFuncs;
    bestScore = 0;
    p = functionSearch(pFuncTab, zName, nName);
    while( p ){
      int score = matchQuality(p, nArg, enc);
      if( score>bestScore ){
        pBest = p;
        bestScore = score;
      }
      p = p->pSameName;
    }
  }

  /* If the createFlag parameter is true and the search did not reveal an
  ** exact match for the name, number of arguments and encoding, then add a
  ** new entry to the hash table and return it.
  */
................................................................................
  if( createFlag && (bestScore<6 || pBest->nArg!=nArg) && 
      (pBest = sqlite4DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
    pBest->zName = (char *)&pBest[1];
    pBest->nArg = (u16)nArg;
    pBest->iPrefEnc = enc;
    memcpy(pBest->zName, zName, nName);
    pBest->zName[nName] = 0;
    sqlite4FuncDefInsert(&db->aFunc, pBest, 0);
  }

  if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
    return pBest;
  }
  return 0;
}

Changes to src/ctime.c.

295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
#endif
#ifdef SQLITE_OMIT_VIEW
  "OMIT_VIEW",
#endif
#ifdef SQLITE_OMIT_VIRTUALTABLE
  "OMIT_VIRTUALTABLE",
#endif
#ifdef SQLITE_OMIT_WSD
  "OMIT_WSD",
#endif
#ifdef SQLITE_OMIT_XFER_OPT
  "OMIT_XFER_OPT",
#endif
#ifdef SQLITE_PERFORMANCE_TRACE
  "PERFORMANCE_TRACE",
#endif
#ifdef SQLITE_PROXY_DEBUG







<
<
<







295
296
297
298
299
300
301



302
303
304
305
306
307
308
#endif
#ifdef SQLITE_OMIT_VIEW
  "OMIT_VIEW",
#endif
#ifdef SQLITE_OMIT_VIRTUALTABLE
  "OMIT_VIRTUALTABLE",
#endif



#ifdef SQLITE_OMIT_XFER_OPT
  "OMIT_XFER_OPT",
#endif
#ifdef SQLITE_PERFORMANCE_TRACE
  "PERFORMANCE_TRACE",
#endif
#ifdef SQLITE_PROXY_DEBUG

Changes to src/date.c.

1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
....
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125

/*
** This function registered all of the above C functions as SQL
** functions.  This should be the only routine in this file with
** external linkage.
*/
void sqlite4RegisterDateTimeFunctions(sqlite4_env *pEnv){
  static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
#ifndef SQLITE_OMIT_DATETIME_FUNCS
    FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
    FUNCTION(date,             -1, 0, 0, dateFunc      ),
    FUNCTION(time,             -1, 0, 0, timeFunc      ),
    FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
    FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
    FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
................................................................................
#else
    STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
    STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
    STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
#endif
  };
  int i;
  FuncDefHash *pHash = &sqlite4GlobalFunctions;
  FuncDef *aFunc = (FuncDef*)aDateTimeFuncs;

  for(i=0; i<ArraySize(aDateTimeFuncs); i++){
    sqlite4FuncDefInsert(pHash, &aFunc[i]);
  }
}







|







 







|



|


1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
....
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125

/*
** This function registered all of the above C functions as SQL
** functions.  This should be the only routine in this file with
** external linkage.
*/
void sqlite4RegisterDateTimeFunctions(sqlite4_env *pEnv){
  static FuncDef aDateTimeFuncs[] = {
#ifndef SQLITE_OMIT_DATETIME_FUNCS
    FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
    FUNCTION(date,             -1, 0, 0, dateFunc      ),
    FUNCTION(time,             -1, 0, 0, timeFunc      ),
    FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
    FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
    FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
................................................................................
#else
    STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
    STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
    STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
#endif
  };
  int i;
  FuncDefTable *pFuncTab = &pEnv->aGlobalFuncs;
  FuncDef *aFunc = (FuncDef*)aDateTimeFuncs;

  for(i=0; i<ArraySize(aDateTimeFuncs); i++){
    sqlite4FuncDefInsert(pFuncTab, &aFunc[i], 1);
  }
}

Changes to src/fault.c.

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84

85
86
87
88
** hash table will continue to function normally.  So a malloc failure 
** during a hash table resize is a benign fault.
*/

#include "sqliteInt.h"

#ifndef SQLITE_OMIT_BUILTIN_TEST

/*
** Global variables.
*/
typedef struct BenignMallocHooks BenignMallocHooks;
static SQLITE_WSD struct BenignMallocHooks {
  void (*xBenignBegin)(void);
  void (*xBenignEnd)(void);
} sqlite4Hooks = { 0, 0 };

/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
** structure.  If writable static data is unsupported on the target,
** we have to locate the state vector at run-time.  In the more common
** case where writable static data is supported, wsdHooks can refer directly
** to the "sqlite4Hooks" state vector declared above.
*/
#ifdef SQLITE_OMIT_WSD
# define wsdHooksInit \
  BenignMallocHooks *x = sqlite4Hooks;
# define wsdHooks x[0]
#else
# define wsdHooksInit
# define wsdHooks sqlite4Hooks
#endif


/*
** Register hooks to call when sqlite4BeginBenignMalloc() and
** sqlite4EndBenignMalloc() are called, respectively.
*/
void sqlite4BenignMallocHooks(
  sqlite4_env *pEnv,
  void (*xBenignBegin)(void),
  void (*xBenignEnd)(void)
){
  wsdHooksInit;
  wsdHooks.xBenignBegin = xBenignBegin;
  wsdHooks.xBenignEnd = xBenignEnd;
}

/*
** This (sqlite4EndBenignMalloc()) is called by SQLite code to indicate that
** subsequent malloc failures are benign. A call to sqlite4EndBenignMalloc()
** indicates that subsequent malloc failures are non-benign.
*/
void sqlite4BeginBenignMalloc(sqlite4_env *pEnv){
  wsdHooksInit;
  if( wsdHooks.xBenignBegin ){
    wsdHooks.xBenignBegin();
  }
}
void sqlite4EndBenignMalloc(sqlite4_env *pEnv){
  wsdHooksInit;
  if( wsdHooks.xBenignEnd ){
    wsdHooks.xBenignEnd();

  }
}

#endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






|
<
<
|
<

<
<
<
>
|
<
<

23
24
25
26
27
28
29








































30
31
32
33
34
35
36


37

38



39
40


41
** hash table will continue to function normally.  So a malloc failure 
** during a hash table resize is a benign fault.
*/

#include "sqliteInt.h"

#ifndef SQLITE_OMIT_BUILTIN_TEST








































/*
** This (sqlite4EndBenignMalloc()) is called by SQLite code to indicate that
** subsequent malloc failures are benign. A call to sqlite4EndBenignMalloc()
** indicates that subsequent malloc failures are non-benign.
*/
void sqlite4BeginBenignMalloc(sqlite4_env *pEnv){
  if( pEnv->m.xBeginBenign ) pEnv->m.xBeginBenign(pEnv->m.pMemEnv);


}

void sqlite4EndBenignMalloc(sqlite4_env *pEnv){



  if( pEnv->m.xEndBenign ) pEnv->m.xEndBenign(pEnv->m.pMemEnv);
}


#endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */

Changes to src/func.c.

780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
....
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
....
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
*/
static void errlogFunc(
  sqlite4_context *context,
  int argc,
  sqlite4_value **argv
){
  UNUSED_PARAMETER(argc);
  UNUSED_PARAMETER(context);
  sqlite4_log(sqlite4_value_int(argv[0]), "%s", sqlite4_value_text(argv[1]));
}

/*
** Implementation of the sqlite_compileoption_used() function.
** The result is an integer that identifies if the compiler option
** was used to build SQLite.
*/
................................................................................
*/
void sqlite4RegisterGlobalFunctions(sqlite4_env *pEnv){
  /*
  ** The following array holds FuncDef structures for all of the functions
  ** defined in this file.
  **
  ** The array cannot be constant since changes are made to the
  ** FuncDef.pHash elements at start-time.  The elements of this array
  ** are read-only after initialization is complete.
  */
  static SQLITE_WSD FuncDef aBuiltinFunc[] = {
    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
    FUNCTION(trim,               1, 3, 0, trimFunc         ),
    FUNCTION(trim,               2, 3, 0, trimFunc         ),
    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
................................................................................
  #else
    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  #endif
  };

  int i;
  FuncDefHash *pHash = &sqlite4GlobalFunctions;
  FuncDef *aFunc = (FuncDef*)aBuiltinFunc;

  for(i=0; i<ArraySize(aBuiltinFunc); i++){
    sqlite4FuncDefInsert(pHash, &aFunc[i]);
  }
  sqlite4RegisterDateTimeFunctions(pEnv);
#ifndef SQLITE_OMIT_ALTERTABLE
  sqlite4AlterFunctions();
#endif
}







|
|







 







|
<

|







 







|



|



|


780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
....
1513
1514
1515
1516
1517
1518
1519
1520

1521
1522
1523
1524
1525
1526
1527
1528
1529
....
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
*/
static void errlogFunc(
  sqlite4_context *context,
  int argc,
  sqlite4_value **argv
){
  UNUSED_PARAMETER(argc);
  sqlite4_log(sqlite4_context_env(context),
              sqlite4_value_int(argv[0]), "%s", sqlite4_value_text(argv[1]));
}

/*
** Implementation of the sqlite_compileoption_used() function.
** The result is an integer that identifies if the compiler option
** was used to build SQLite.
*/
................................................................................
*/
void sqlite4RegisterGlobalFunctions(sqlite4_env *pEnv){
  /*
  ** The following array holds FuncDef structures for all of the functions
  ** defined in this file.
  **
  ** The array cannot be constant since changes are made to the
  ** FuncDef.pNextName and FuncDef.pSameName elements at start-time.

  */
  static FuncDef aBuiltinFunc[] = {
    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
    FUNCTION(trim,               1, 3, 0, trimFunc         ),
    FUNCTION(trim,               2, 3, 0, trimFunc         ),
    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
................................................................................
  #else
    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  #endif
  };

  int i;
  FuncDefTable *pFuncTab = &pEnv->aGlobalFuncs;
  FuncDef *aFunc = (FuncDef*)aBuiltinFunc;

  for(i=0; i<ArraySize(aBuiltinFunc); i++){
    sqlite4FuncDefInsert(pFuncTab, &aFunc[i], 1);
  }
  sqlite4RegisterDateTimeFunctions(pEnv);
#ifndef SQLITE_OMIT_ALTERTABLE
  sqlite4AlterFunctions(pEnv);
#endif
}

Changes to src/global.c.

125
126
127
128
129
130
131
















132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164




165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
};
#endif

















/*
** The following singleton contains the global configuration for
** the SQLite library.
*/
SQLITE_WSD struct sqlite4_env sqlite4DefaultEnv = {
   sizeof(sqlite4_env),       /* nByte */
   1,                         /* iVersion */
   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
   1,                         /* bCoreMutex */
   SQLITE_THREADSAFE==1,      /* bFullMutex */
   0x7ffffffe,                /* mxStrlen */
   128,                       /* szLookaside */
   500,                       /* nLookaside */
   {0,0,0,0,0,0,0,0},         /* m */
   {0,0,0,0,0,0,0,0,0},       /* mutex */
   (void*)0,                  /* pHeap */
   0,                         /* nHeap */
   0, 0,                      /* mnHeap, mxHeap */
   0,                         /* mxParserStack */
   sqlite4KVStoreOpenLsm,     /* xKVFile */
   sqlite4KVStoreOpenMem,     /* xKVTmp */
   sqlite4OsRandomness,       /* xRandomness */
   sqlite4OsCurrentTime,      /* xCurrentTime */
   /* All the rest should always be initialized to zero */
   0,                         /* isInit */
   0,                         /* inProgress */
   0,                         /* isMutexInit */
   0,                         /* isMallocInit */
   0,                         /* pInitMutex */
   0,                         /* nRefInitMutex */
   0,                         /* xLog */
   0,                         /* pLogArg */
   0,                         /* bLocaltimeFault */




};

/*
** Return the default environment
*/
sqlite4_env *sqlite4_env_default(void){ return &sqlite4DefaultEnv; }


/*
** Hash table for global functions - functions common to all
** database connections.  After initialization, this table is
** read-only.
*/
SQLITE_WSD FuncDefHash sqlite4GlobalFunctions;

/*
** Constant tokens for values 0 and 1.
*/
const Token sqlite4IntTokens[] = {
   { "0", 1 },
   { "1", 1 }
};


/*
** The value of the "pending" byte must be 0x40000000 (1 byte past the
** 1-gibabyte boundary) in a compatible database.  SQLite never uses
** the database page that contains the pending byte.  It never attempts
** to read or write that page.  The pending byte page is set assign
** for use by the VFS layers as space for managing file locks.
**
** During testing, it is often desirable to move the pending byte to
** a different position in the file.  This allows code that has to
** deal with the pending byte to run on files that are much smaller
** than 1 GiB.  The sqlite4_test_control() interface can be used to
** move the pending byte.
**
** IMPORTANT:  Changing the pending byte to any value other than
** 0x40000000 results in an incompatible database file format!
** Changing the pending byte during operating results in undefined
** and dileterious behavior.
*/
#ifndef SQLITE_OMIT_WSD
int sqlite4PendingByte = 0x40000000;
#endif

#include "opcodes.h"
/*
** Properties of opcodes.  The OPFLG_INITIALIZER macro is
** created by mkopcodeh.awk during compilation.  Data is obtained
** from the comments following the "case OP_xxxx:" statements in
** the vdbe.c file.  
*/
const unsigned char sqlite4OpcodeProperty[] = OPFLG_INITIALIZER;







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




|








|
|




|
<




<
<
<
|
|



>
>
>
>








<
<
<
<
<
<
<








<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167

168
169
170
171



172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188







189
190
191
192
193
194
195
196























197
198
199
200
201
202
203
204
  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
};
#endif

/*
** Default factory objects
*/
static KVFactory memFactory = {
   0,
   "temp",
   sqlite4KVStoreOpenMem,
   1
};
KVFactory sqlite4BuiltinFactory = {
   &memFactory,
   "main",
   sqlite4KVStoreOpenLsm,
   1
};

/*
** The following singleton contains the global configuration for
** the SQLite library.
*/
struct sqlite4_env sqlite4DefaultEnv = {
   sizeof(sqlite4_env),       /* nByte */
   1,                         /* iVersion */
   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
   1,                         /* bCoreMutex */
   SQLITE_THREADSAFE==1,      /* bFullMutex */
   0x7ffffffe,                /* mxStrlen */
   128,                       /* szLookaside */
   500,                       /* nLookaside */
   {0,0,0,0,0,0,0,0,0},       /* m */
   {0,0,0,0,0,0,0,0,0,0},     /* mutex */
   (void*)0,                  /* pHeap */
   0,                         /* nHeap */
   0, 0,                      /* mnHeap, mxHeap */
   0,                         /* mxParserStack */
   &sqlite4BuiltinFactory,    /* pFactory */

   sqlite4OsRandomness,       /* xRandomness */
   sqlite4OsCurrentTime,      /* xCurrentTime */
   /* All the rest should always be initialized to zero */
   0,                         /* isInit */



   0,                         /* pPrngMutex */
   0, 0,                      /* prngX, prngY */
   0,                         /* xLog */
   0,                         /* pLogArg */
   0,                         /* bLocaltimeFault */
   0,                         /* pMemMutex */
   {0,0,0,0},                 /* nowValue[] */
   {0,0,0,0},                 /* mxValue[] */
   {0,}                       /* hashGlobalFunc */
};

/*
** Return the default environment
*/
sqlite4_env *sqlite4_env_default(void){ return &sqlite4DefaultEnv; }









/*
** Constant tokens for values 0 and 1.
*/
const Token sqlite4IntTokens[] = {
   { "0", 1 },
   { "1", 1 }
};
























#include "opcodes.h"
/*
** Properties of opcodes.  The OPFLG_INITIALIZER macro is
** created by mkopcodeh.awk during compilation.  Data is obtained
** from the comments following the "case OP_xxxx:" statements in
** the vdbe.c file.  
*/
const unsigned char sqlite4OpcodeProperty[] = OPFLG_INITIALIZER;

Changes to src/kvlsm.c.

391
392
393
394
395
396
397


398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
  KVStore **ppKVStore,        /* OUT: write the new KVStore here */
  const char *zName,          /* Name of the file to open */
  unsigned openFlags          /* Flags */
){

  /* Virtual methods for an LSM data store */
  static const KVStoreMethods kvlsmMethods = {


    kvlsmReplace,
    kvlsmOpenCursor,
    kvlsmSeek,
    kvlsmNextEntry,
    kvlsmPrevEntry,
    kvlsmDelete,
    kvlsmKey,
    kvlsmData,
    kvlsmReset,
    kvlsmCloseCursor,
    kvlsmBegin,
    kvlsmCommitPhaseOne,
    kvlsmCommitPhaseTwo,
    kvlsmRollback,
    kvlsmRevert,
    kvlsmClose,
    kvlsmControl
  };

  KVLsm *pNew;
  int rc = SQLITE_OK;

  pNew = (KVLsm *)sqlite4_malloc(pEnv, sizeof(KVLsm));
  if( pNew==0 ){







>
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|







391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
  KVStore **ppKVStore,        /* OUT: write the new KVStore here */
  const char *zName,          /* Name of the file to open */
  unsigned openFlags          /* Flags */
){

  /* Virtual methods for an LSM data store */
  static const KVStoreMethods kvlsmMethods = {
    1,                          /* iVersion */
    sizeof(KVStoreMethods),     /* szSelf */
    kvlsmReplace,               /* xReplace */
    kvlsmOpenCursor,            /* xOpenCursor */
    kvlsmSeek,                  /* xSeek */
    kvlsmNextEntry,             /* xNext */
    kvlsmPrevEntry,             /* xPrev */
    kvlsmDelete,                /* xDelete */
    kvlsmKey,                   /* xKey */
    kvlsmData,                  /* xData */
    kvlsmReset,                 /* xReset */
    kvlsmCloseCursor,           /* xCloseCursor */
    kvlsmBegin,                 /* xBegin */
    kvlsmCommitPhaseOne,        /* xCommitPhaseOne */
    kvlsmCommitPhaseTwo,        /* xCommitPhaseTwo */
    kvlsmRollback,              /* xRollback */
    kvlsmRevert,                /* xRevert */
    kvlsmClose,                 /* xClose */
    kvlsmControl                /* xControl */
  };

  KVLsm *pNew;
  int rc = SQLITE_OK;

  pNew = (KVLsm *)sqlite4_malloc(pEnv, sizeof(KVLsm));
  if( pNew==0 ){

Changes to src/kvmem.c.

914
915
916
917
918
919
920


921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944

static int kvmemControl(KVStore *pKVStore, int op, void *pArg){
  return SQLITE_NOTFOUND;
}

/* Virtual methods for the in-memory storage engine */
static const KVStoreMethods kvmemMethods = {


  kvmemReplace,
  kvmemOpenCursor,
  kvmemSeek,
  kvmemNextEntry,
  kvmemPrevEntry,
  kvmemDelete,
  kvmemKey,
  kvmemData,
  kvmemReset,
  kvmemCloseCursor,
  kvmemBegin,
  kvmemCommitPhaseOne,
  kvmemCommitPhaseTwo,
  kvmemRollback,
  kvmemRevert,
  kvmemClose,
  kvmemControl
};

/*
** Create a new in-memory storage engine and return a pointer to it.
*/
int sqlite4KVStoreOpenMem(
  sqlite4_env *pEnv,              /* Runtime environment */







>
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|







914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946

static int kvmemControl(KVStore *pKVStore, int op, void *pArg){
  return SQLITE_NOTFOUND;
}

/* Virtual methods for the in-memory storage engine */
static const KVStoreMethods kvmemMethods = {
  1,                        /* iVersion */
  sizeof(KVStoreMethods),   /* szSelf */
  kvmemReplace,             /* xReplace */
  kvmemOpenCursor,          /* xOpenCursor */
  kvmemSeek,                /* xSeek */
  kvmemNextEntry,           /* xNext */
  kvmemPrevEntry,           /* xPrev */
  kvmemDelete,              /* xDelete */
  kvmemKey,                 /* xKey */
  kvmemData,                /* xData */
  kvmemReset,               /* xReset */
  kvmemCloseCursor,         /* xCloseCursor */
  kvmemBegin,               /* xBegin */
  kvmemCommitPhaseOne,      /* xCommitPhaseOne */
  kvmemCommitPhaseTwo,      /* xCommitPhaseTwo */
  kvmemRollback,            /* xRollback */
  kvmemRevert,              /* xRevert */
  kvmemClose,               /* xClose */
  kvmemControl              /* xControl */
};

/*
** Create a new in-memory storage engine and return a pointer to it.
*/
int sqlite4KVStoreOpenMem(
  sqlite4_env *pEnv,              /* Runtime environment */

Changes to src/main.c.

78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
...
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125


126
127
128
129
130
131
132


133
134
135
136
137
138

139
140
141
142
143
144


145







146
147



148

149
150
151

152
153
154
155
156
157

158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
...
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
...
227
228
229
230
231
232
233
234
235
236
237
238
239
240


241
242

243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
...
312
313
314
315
316
317
318

319
320
321
322
323
324
325
...
466
467
468
469
470
471
472









473
474
475




476
477
478
479
480
481
482
483






484
485
486






















487
488
489
490
491
492
493
...
831
832
833
834
835
836
837
838

839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
....
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
....
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813

1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
....
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
....
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
** As long as you do not compile with SQLITE_OMIT_AUTOINIT
** this routine will be called automatically by key routines such as
** sqlite4_open().  
**
** This routine is a no-op except on its very first call for a given
** sqlite4_env object, or for the first call after a call to sqlite4_shutdown.
**
** The first thread to call this routine runs the initialization to
** completion.  If subsequent threads call this routine before the first
** thread has finished the initialization process, then the subsequent
** threads must block until the first thread finishes with the initialization.
**
** The first thread might call this routine recursively.  Recursive
** calls to this routine should not block, of course.  Otherwise the
** initialization process would never complete.
**
** Let X be the first thread to enter this routine.  Let Y be some other
** thread.  Then while the initial invocation of this routine by X is
** incomplete, it is required that:
**
**    *  Calls to this routine from Y must block until the outer-most
**       call by X completes.
**
**    *  Recursive calls to this routine from thread X return immediately
**       without blocking.
*/
int sqlite4_initialize(sqlite4_env *pEnv){
  MUTEX_LOGIC( sqlite4_mutex *pMaster; )       /* The main static mutex */
  int rc;                                      /* Result code */

  if( pEnv==0 ) pEnv = &sqlite4DefaultEnv;

................................................................................
  /* If SQLite is already completely initialized, then this call
  ** to sqlite4_initialize() should be a no-op.  But the initialization
  ** must be complete.  So isInit must not be set until the very end
  ** of this routine.
  */
  if( pEnv->isInit ) return SQLITE_OK;

  /* Make sure the mutex subsystem is initialized.  If unable to 
  ** initialize the mutex subsystem, return early with the error.
  ** If the system is so sick that we are unable to allocate a mutex,
  ** there is not much SQLite is going to be able to do.
  **
  ** The mutex subsystem must take care of serializing its own
  ** initialization.
  */
  rc = sqlite4MutexInit();


  if( rc ) return rc;

  /* Initialize the malloc() system and the recursive pInitMutex mutex.
  ** This operation is protected by the STATIC_MASTER mutex.  Note that
  ** MutexAlloc() is called for a static mutex prior to initializing the
  ** malloc subsystem - this implies that the allocation of a static
  ** mutex must not require support from the malloc subsystem.


  */
  MUTEX_LOGIC( pMaster = sqlite4MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  sqlite4_mutex_enter(pMaster);
  pEnv->isMutexInit = 1;
  if( !pEnv->isMallocInit ){
    rc = sqlite4MallocInit(pEnv);

  }
  if( rc==SQLITE_OK ){
    pEnv->isMallocInit = 1;
    if( !pEnv->pInitMutex ){
      pEnv->pInitMutex =
           sqlite4MutexAlloc(SQLITE_MUTEX_RECURSIVE);


      if( pEnv->bCoreMutex && !pEnv->pInitMutex ){







        rc = SQLITE_NOMEM;
      }



    }

  }
  if( rc==SQLITE_OK ){
    pEnv->nRefInitMutex++;

  }
  sqlite4_mutex_leave(pMaster);

  /* If rc is not SQLITE_OK at this point, then either the malloc
  ** subsystem could not be initialized or the system failed to allocate
  ** the pInitMutex mutex. Return an error in either case.  */

  if( rc!=SQLITE_OK ){
    return rc;
  }

  /* Do the rest of the initialization under the recursive mutex so
  ** that we will be able to handle recursive calls into
  ** sqlite4_initialize().  The recursive calls normally come through
  ** sqlite4_os_init() when it invokes sqlite4_vfs_register(), but other
  ** recursive calls might also be possible.
  */
  sqlite4_mutex_enter(pEnv->pInitMutex);
  if( pEnv->isInit==0 && pEnv->inProgress==0 ){
    FuncDefHash *pHash = &sqlite4GlobalFunctions;
    pEnv->inProgress = 1;
    memset(pHash, 0, sizeof(sqlite4GlobalFunctions));
    sqlite4RegisterGlobalFunctions(pEnv);
    rc = sqlite4OsInit(0);
    pEnv->inProgress = 0;
  }
  sqlite4_mutex_leave(pEnv->pInitMutex);

  /* Go back under the static mutex and clean up the recursive
  ** mutex to prevent a resource leak.
  */
  sqlite4_mutex_enter(pMaster);
  pEnv->nRefInitMutex--;
  if( pEnv->nRefInitMutex<=0 ){
    assert( pEnv->nRefInitMutex==0 );
    sqlite4_mutex_free(pEnv->pInitMutex);
    pEnv->pInitMutex = 0;
  }
  sqlite4_mutex_leave(pMaster);

  /* The following is just a sanity check to make sure SQLite has
  ** been compiled correctly.  It is important to run this code, but
  ** we don't want to run it too often and soak up CPU cycles for no
  ** reason.  So we run it once during initialization.
  */
#ifndef NDEBUG
................................................................................
    assert(sizeof(x)==sizeof(y));
    memcpy(&y, &x, 8);
    assert( sqlite4IsNaN(y) );
  }
#endif
#endif

  /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  ** compile-time option.
  */
#ifdef SQLITE_EXTRA_INIT
  if( rc==SQLITE_OK && pEnv->isInit ){
    int SQLITE_EXTRA_INIT(const char*);
    rc = SQLITE_EXTRA_INIT(0);
  }
#endif

  return rc;
}

/*
** Undo the effects of sqlite4_initialize().  Must not be called while
** there are outstanding database connections or memory allocations or
** while any part of SQLite is otherwise in use in any thread.  This
................................................................................
** routine is not threadsafe.  But it is safe to invoke this routine
** on when SQLite is already shut down.  If SQLite is already shut down
** when this routine is invoked, then this routine is a harmless no-op.
*/
int sqlite4_shutdown(sqlite4_env *pEnv){
  if( pEnv==0 ) pEnv = &sqlite4DefaultEnv;
  if( pEnv->isInit ){
#ifdef SQLITE_EXTRA_SHUTDOWN
    void SQLITE_EXTRA_SHUTDOWN(void);
    SQLITE_EXTRA_SHUTDOWN();
#endif
    /*sqlite4_os_end();*/
    /* sqlite4_reset_auto_extension(); */
    pEnv->isInit = 0;


  }
  if( pEnv->isMallocInit ){

    sqlite4MallocEnd(pEnv);
    pEnv->isMallocInit = 0;
  }

  return SQLITE_OK;
}

/*
** This API allows applications to modify the configuration described by
** an sqlite4_env object.
*/
int sqlite4_config(sqlite4_env *pEnv, int op, ...){
  va_list ap;
  int rc = SQLITE_OK;

  if( pEnv==0 ) pEnv = sqlite4_env_default();

  /* sqlite4_config() shall return SQLITE_MISUSE if it is invoked while
  ** the SQLite library is in use. */
  if( pEnv->isInit ) return SQLITE_MISUSE_BKPT;

  va_start(ap, op);
  switch( op ){
    case SQLITE_CONFIG_SET_KVFACTORY: {
      pEnv->xKVFile = *va_arg(ap, 
          int (*)(sqlite4_env*, KVStore **, const char *, unsigned int)
      );
      break;
    }

    case SQLITE_CONFIG_GET_KVFACTORY: {
      *va_arg(ap, int(**)(sqlite4_env*, KVStore**, const char*, unsigned int)) =
          pEnv->xKVFile;
      break;
    }

    default: {
      rc = SQLITE_ERROR;
      break;
    }
  }
  va_end(ap);
  return rc;
}

/*
** Return the size of an sqlite4_env object
*/
int sqlite4_env_size(void){ return sizeof(sqlite4_env); }

/*
** This API allows applications to modify the configuration described by
................................................................................
    */
    case SQLITE_ENVCONFIG_INIT: {
      /* Disable all mutexing */
      sqlite4_env *pTemplate = va_arg(ap, sqlite4_env*);
      int n = pTemplate->nByte;
      if( n>sizeof(sqlite4_env) ) n = sizeof(sqlite4_env);
      memcpy(pEnv, pTemplate, n);

      pEnv->isInit = 0;
      break;
    }

    /* Mutex configuration options are only available in a threadsafe
    ** compile. 
    */
................................................................................
    /*
    ** sqlite4_env_config(pEnv, SQLITE_ENVCONFIG_KVSTORE_PUSH, zName, xFactory);
    **
    ** Push a new KVStore factory onto the factory stack.  The new factory
    ** takes priority over prior factories.
    */
    case SQLITE_ENVCONFIG_KVSTORE_PUSH: {









      pEnv->xKVFile = *va_arg(ap, 
          int (*)(sqlite4_env*, KVStore **, const char *, unsigned int)
      );




      break;
    }

    /*
    ** sqlite4_env_config(pEnv, SQLITE_ENVCONFIG_KVSTORE_POP, zName);
    **
    ** Remove a KVStore factory from the stack.
    */






    case SQLITE_ENVCONFIG_KVSTORE_POP: {
      *va_arg(ap, int(**)(sqlite4_env*, KVStore**, const char*, unsigned int)) =
          pEnv->xKVFile;






















      break;
    }


    default: {
      rc = SQLITE_ERROR;
      break;
................................................................................
  /* Tell the code in notify.c that the connection no longer holds any
  ** locks and does not require any further unlock-notify callbacks.
  */
  sqlite4ConnectionClosed(db);

  assert( db->nDb<=2 );
  assert( db->aDb==db->aDbStatic );
  for(j=0; j<ArraySize(db->aFunc.a); j++){

    FuncDef *pNext, *pHash, *p;
    for(p=db->aFunc.a[j]; p; p=pHash){
      pHash = p->pHash;
      while( p ){
        functionDestroy(db, p);
        pNext = p->pNext;
        sqlite4DbFree(db, p);
        p = pNext;
      }
    }
  }
  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
    CollSeq *pColl = (CollSeq *)sqliteHashData(i);
    /* Invoke any destructors registered for collation sequence user data. */
    for(j=0; j<3; j++){
................................................................................
#ifndef SQLITE_OMIT_AUTOINIT
  rc = sqlite4_initialize(pEnv);
  if( rc ) return rc;
#endif

  if( pEnv->bCoreMutex==0 ){
    isThreadsafe = 0;
  }else if( flags & SQLITE_OPEN_NOMUTEX ){
    isThreadsafe = 0;
  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
    isThreadsafe = 1;
  }else{
    isThreadsafe = pEnv->bFullMutex;
  }

  /* Allocate the sqlite data structure */
  db = sqlite4MallocZero(pEnv, sizeof(sqlite4) );
  if( db==0 ) goto opendb_out;
  db->pEnv = pEnv;
  if( isThreadsafe ){
    db->mutex = sqlite4MutexAlloc(SQLITE_MUTEX_RECURSIVE);
    if( db->mutex==0 ){
      sqlite4_free(pEnv, db);
      db = 0;
      goto opendb_out;
    }
  }
  sqlite4_mutex_enter(db->mutex);
................................................................................

  /* Also add a UTF-8 case-insensitive collation sequence. */
  createCollation(db, 
      "NOCASE", SQLITE_UTF8, 0, collNocaseCmp, collNocaseMkKey, 0
  );

  /* Parse the filename/URI argument. */
  db->openFlags = flags;
  rc = sqlite4ParseUri(pEnv, zFilename, &flags, &zOpen, &zErrMsg);
  if( rc!=SQLITE_OK ){
    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
    sqlite4Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
    sqlite4_free(pEnv, zErrMsg);
    goto opendb_out;
  }


  /* Open the backend database driver */
  rc = sqlite4KVStoreOpen(db, "main", zOpen, &db->aDb[0].pKV, 0);
  if( rc!=SQLITE_OK ){
    if( rc==SQLITE_IOERR_NOMEM ){
      rc = SQLITE_NOMEM;
    }
    sqlite4Error(db, rc, 0);
    goto opendb_out;
  }
................................................................................
**       to detect when version error conditions occurs.
**
**   2.  Invoke sqlite4_log() to provide the source code location where
**       a low-level error is first detected.
*/
int sqlite4CorruptError(int lineno){
  testcase( sqlite4DefaultEnv.xLog!=0 );
  sqlite4_log(SQLITE_CORRUPT,
              "database corruption at line %d of [%.10s]",
              lineno, 20+sqlite4_sourceid());
  return SQLITE_CORRUPT;
}
int sqlite4MisuseError(int lineno){
  testcase( sqlite4DefaultEnv.xLog!=0 );
  sqlite4_log(SQLITE_MISUSE, 
              "misuse at line %d of [%.10s]",
              lineno, 20+sqlite4_sourceid());
  return SQLITE_MISUSE;
}
int sqlite4CantopenError(int lineno){
  testcase( sqlite4DefaultEnv.xLog!=0 );
  sqlite4_log(SQLITE_CANTOPEN, 
              "cannot open file at line %d of [%.10s]",
              lineno, 20+sqlite4_sourceid());
  return SQLITE_CANTOPEN;
}


/*
................................................................................
*/
int sqlite4_test_control(int op, ...){
  int rc = 0;
#ifndef SQLITE_OMIT_BUILTIN_TEST
  va_list ap;
  va_start(ap, op);
  switch( op ){

    /*
    ** Save the current state of the PRNG.
    */
    case SQLITE_TESTCTRL_PRNG_SAVE: {
      sqlite4PrngSaveState();
      break;
    }

    /*
    ** Restore the state of the PRNG to the last state saved using
    ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
    ** this verb acts like PRNG_RESET.
    */
    case SQLITE_TESTCTRL_PRNG_RESTORE: {
      sqlite4PrngRestoreState();
      break;
    }

    /*
    ** Reset the PRNG back to its uninitialized state.  The next call
    ** to sqlite4_randomness() will reseed the PRNG using a single call
    ** to the xRandomness method of the default VFS.
    */
    case SQLITE_TESTCTRL_PRNG_RESET: {
      sqlite4PrngResetState();
      break;
    }

    /*
    **  sqlite4_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
    **
    ** Register hooks to call to indicate which malloc() failures 
    ** are benign.
    */
    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
      typedef void (*void_function)(void);
      void_function xBenignBegin;
      void_function xBenignEnd;
      xBenignBegin = va_arg(ap, void_function);
      xBenignEnd = va_arg(ap, void_function);
      sqlite4BenignMallocHooks(0, xBenignBegin, xBenignEnd);
      break;
    }

    /*
    **  sqlite4_test_control(SQLITE_TESTCTRL_ASSERT, int X)
    **
    ** This action provides a run-time test to see whether or not
    ** assert() was enabled at compile-time.  If X is true and assert()
    ** is enabled, then the return value is true.  If X is true and
    ** assert() is disabled, then the return value is zero.  If X is







|
|
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







<
|
<
<
<
<
<

|
>
>
|
|
<
<
<
<
<
>
>

<
<
<
<
|
>
|
<
<
<
<
<
>
>
|
>
>
>
>
>
>
>
|
|
>
>
>
|
>
|
<
<
>
|
<
<
<
<
<
>
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<

<
<

<
<
<
<
<
<
<
<
<
<
<
<
<







 







<
<
<
<
<
<
<
<
<
<







 







|
|
|
|
|
|
|
>
>
|
<
>

|

<



<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







>







 







>
>
>
>
>
>
>
>
>
|
|
|
>
>
>
>




|



>
>
>
>
>
>
|
<
<
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







<
>
|
|
|


|

|







 







<
<
<
<









|







 







<







>


|







 







|






|






|







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







78
79
80
81
82
83
84
85
86
87
88














89
90
91
92
93
94
95
..
96
97
98
99
100
101
102

103





104
105
106
107
108
109





110
111
112




113
114
115





116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133


134
135





136
137














138


139













140
141
142
143
144
145
146
...
153
154
155
156
157
158
159










160
161
162
163
164
165
166
...
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183

184
185
186
187

188
189
190






































191
192
193
194
195
196
197
...
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
...
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407


408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
...
774
775
776
777
778
779
780

781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
....
1681
1682
1683
1684
1685
1686
1687




1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
....
1738
1739
1740
1741
1742
1743
1744

1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
....
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
....
2020
2021
2022
2023
2024
2025
2026













































2027
2028
2029
2030
2031
2032
2033
** As long as you do not compile with SQLITE_OMIT_AUTOINIT
** this routine will be called automatically by key routines such as
** sqlite4_open().  
**
** This routine is a no-op except on its very first call for a given
** sqlite4_env object, or for the first call after a call to sqlite4_shutdown.
**
** This routine is not threadsafe.  It should be called from a single
** thread to initialized the library in a multi-threaded system.  Other
** threads should avoid using the sqlite4_env object until after it has
** completely initialized.














*/
int sqlite4_initialize(sqlite4_env *pEnv){
  MUTEX_LOGIC( sqlite4_mutex *pMaster; )       /* The main static mutex */
  int rc;                                      /* Result code */

  if( pEnv==0 ) pEnv = &sqlite4DefaultEnv;

................................................................................
  /* If SQLite is already completely initialized, then this call
  ** to sqlite4_initialize() should be a no-op.  But the initialization
  ** must be complete.  So isInit must not be set until the very end
  ** of this routine.
  */
  if( pEnv->isInit ) return SQLITE_OK;


  /* Initialize the mutex subsystem





  */
  rc = sqlite4MutexInit(pEnv);
  if( rc ){
    sqlite4MallocEnd(pEnv);
    return rc;
  }






  /* Initialize the memory allocation subsystem
  */




  rc = sqlite4MallocInit(pEnv);
  if( rc ) return rc;






  /* Create required mutexes
  */
  if( pEnv->bCoreMutex ){
    pEnv->pMemMutex = sqlite4MutexAlloc(pEnv, SQLITE_MUTEX_FAST);
    pEnv->pPrngMutex = sqlite4MutexAlloc(pEnv, SQLITE_MUTEX_FAST);
    pEnv->pFactoryMutex = sqlite4MutexAlloc(pEnv, SQLITE_MUTEX_FAST);
    if( pEnv->pMemMutex==0
     || pEnv->pPrngMutex==0
     || pEnv->pFactoryMutex==0
    ){
      rc = SQLITE_NOMEM;
    }
  }else{
    pEnv->pMemMutex = 0;
    pEnv->pPrngMutex = 0;
  }
  pEnv->isInit = 1;



  sqlite4OsInit(pEnv);






  /* Register global functions */
  if( rc==SQLITE_OK ){














    sqlite4RegisterGlobalFunctions(pEnv);


  }














  /* The following is just a sanity check to make sure SQLite has
  ** been compiled correctly.  It is important to run this code, but
  ** we don't want to run it too often and soak up CPU cycles for no
  ** reason.  So we run it once during initialization.
  */
#ifndef NDEBUG
................................................................................
    assert(sizeof(x)==sizeof(y));
    memcpy(&y, &x, 8);
    assert( sqlite4IsNaN(y) );
  }
#endif
#endif











  return rc;
}

/*
** Undo the effects of sqlite4_initialize().  Must not be called while
** there are outstanding database connections or memory allocations or
** while any part of SQLite is otherwise in use in any thread.  This
................................................................................
** routine is not threadsafe.  But it is safe to invoke this routine
** on when SQLite is already shut down.  If SQLite is already shut down
** when this routine is invoked, then this routine is a harmless no-op.
*/
int sqlite4_shutdown(sqlite4_env *pEnv){
  if( pEnv==0 ) pEnv = &sqlite4DefaultEnv;
  if( pEnv->isInit ){
    KVFactory *pMkr;
    sqlite4_mutex_free(pEnv->pFactoryMutex);
    sqlite4_mutex_free(pEnv->pPrngMutex);
    sqlite4_mutex_free(pEnv->pMemMutex);
    pEnv->pMemMutex = 0;
    while( (pMkr = pEnv->pFactory)!=0 && pMkr->isPerm==0 ){
      KVFactory *pNext = pMkr->pNext;
      sqlite4_free(pEnv, pMkr);
      pMkr = pNext;
    }

    sqlite4MutexEnd(pEnv);
    sqlite4MallocEnd(pEnv);
    pEnv->isInit = 0;
  }

  return SQLITE_OK;
}







































/*
** Return the size of an sqlite4_env object
*/
int sqlite4_env_size(void){ return sizeof(sqlite4_env); }

/*
** This API allows applications to modify the configuration described by
................................................................................
    */
    case SQLITE_ENVCONFIG_INIT: {
      /* Disable all mutexing */
      sqlite4_env *pTemplate = va_arg(ap, sqlite4_env*);
      int n = pTemplate->nByte;
      if( n>sizeof(sqlite4_env) ) n = sizeof(sqlite4_env);
      memcpy(pEnv, pTemplate, n);
      pEnv->pFactory = &sqlite4BuiltinFactory;
      pEnv->isInit = 0;
      break;
    }

    /* Mutex configuration options are only available in a threadsafe
    ** compile. 
    */
................................................................................
    /*
    ** sqlite4_env_config(pEnv, SQLITE_ENVCONFIG_KVSTORE_PUSH, zName, xFactory);
    **
    ** Push a new KVStore factory onto the factory stack.  The new factory
    ** takes priority over prior factories.
    */
    case SQLITE_ENVCONFIG_KVSTORE_PUSH: {
      const char *zName = va_arg(ap, const char*);
      int nName = sqlite4Strlen30(zName);
      KVFactory *pMkr = sqlite4_malloc(pEnv, sizeof(*pMkr)+nName+1);
      char *z;
      if( pMkr==0 ) return SQLITE_NOMEM;
      z = (char*)&pMkr[1];
      memcpy(z, zName, nName+1);
      memset(pMkr, 0, sizeof(*pMkr));
      pMkr->zName = z;
      pMkr->xFactory = va_arg(ap, 
            int(*)(sqlite4_env*, KVStore **, const char *, unsigned int)
        );
      sqlite4_mutex_enter(pEnv->pFactoryMutex);
      pMkr->pNext = pEnv->pFactory;
      pEnv->pFactory = pMkr;
      sqlite4_mutex_leave(pEnv->pFactoryMutex);
      break;
    }

    /*
    ** sqlite4_env_config(pEnv, SQLITE_ENVCONFIG_KVSTORE_POP, zName, &pxFact);
    **
    ** Remove a KVStore factory from the stack.
    */
    /*
    ** sqlite4_env_config(pEnv, SQLITE_ENVCONFIG_KVSTORE_GET, zName, &pxFact);
    **
    ** Get the current factory pointer with the given name but leave the
    ** factory on the stack.
    */
    case SQLITE_ENVCONFIG_KVSTORE_POP:


    case SQLITE_ENVCONFIG_KVSTORE_GET: {
      const char *zName = va_arg(ap, const char*);
      KVFactory *pMkr, **ppPrev;
      int (**pxFact)(sqlite4_env*,KVStore**,const char*,unsigned);

      pxFact = va_arg(ap,int(**)(sqlite4_env*,KVStore*,const char*,unsigned));
      *pxFact = 0;
      sqlite4_mutex_enter(pEnv->pFactoryMutex);
      ppPrev = &pEnv->pFactory;
      pMkr = *ppPrev;
      while( pMkr && strcmp(zName, pMkr->zName)!=0 ){
        ppPrev = &pMkr->pNext;
        pMkr = *ppPrev;
      }
      if( pMkr ){
        *pxFact = pMkr->xFactory;
        if( op==SQLITE_ENVCONFIG_KVSTORE_POP && pMkr->isPerm==0 ){
          *ppPrev = pMkr->pNext;
          sqlite4_free(pEnv, pMkr);
        }
      }
      sqlite4_mutex_leave(pEnv->pFactoryMutex);
      break;
    }


    default: {
      rc = SQLITE_ERROR;
      break;
................................................................................
  /* Tell the code in notify.c that the connection no longer holds any
  ** locks and does not require any further unlock-notify callbacks.
  */
  sqlite4ConnectionClosed(db);

  assert( db->nDb<=2 );
  assert( db->aDb==db->aDbStatic );

  {
    FuncDef *pNext, *pSame, *p;
    for(p=db->aFunc.pFirst; p; p=pNext){
      pNext = p->pNextName;
      while( p ){
        functionDestroy(db, p);
        pSame = p->pSameName;
        sqlite4DbFree(db, p);
        p = pSame;
      }
    }
  }
  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
    CollSeq *pColl = (CollSeq *)sqliteHashData(i);
    /* Invoke any destructors registered for collation sequence user data. */
    for(j=0; j<3; j++){
................................................................................
#ifndef SQLITE_OMIT_AUTOINIT
  rc = sqlite4_initialize(pEnv);
  if( rc ) return rc;
#endif

  if( pEnv->bCoreMutex==0 ){
    isThreadsafe = 0;




  }else{
    isThreadsafe = pEnv->bFullMutex;
  }

  /* Allocate the sqlite data structure */
  db = sqlite4MallocZero(pEnv, sizeof(sqlite4) );
  if( db==0 ) goto opendb_out;
  db->pEnv = pEnv;
  if( isThreadsafe ){
    db->mutex = sqlite4MutexAlloc(pEnv, SQLITE_MUTEX_RECURSIVE);
    if( db->mutex==0 ){
      sqlite4_free(pEnv, db);
      db = 0;
      goto opendb_out;
    }
  }
  sqlite4_mutex_enter(db->mutex);
................................................................................

  /* Also add a UTF-8 case-insensitive collation sequence. */
  createCollation(db, 
      "NOCASE", SQLITE_UTF8, 0, collNocaseCmp, collNocaseMkKey, 0
  );

  /* Parse the filename/URI argument. */

  rc = sqlite4ParseUri(pEnv, zFilename, &flags, &zOpen, &zErrMsg);
  if( rc!=SQLITE_OK ){
    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
    sqlite4Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
    sqlite4_free(pEnv, zErrMsg);
    goto opendb_out;
  }
  db->openFlags = flags;

  /* Open the backend database driver */
  rc = sqlite4KVStoreOpen(db, "main", zOpen, &db->aDb[0].pKV, flags);
  if( rc!=SQLITE_OK ){
    if( rc==SQLITE_IOERR_NOMEM ){
      rc = SQLITE_NOMEM;
    }
    sqlite4Error(db, rc, 0);
    goto opendb_out;
  }
................................................................................
**       to detect when version error conditions occurs.
**
**   2.  Invoke sqlite4_log() to provide the source code location where
**       a low-level error is first detected.
*/
int sqlite4CorruptError(int lineno){
  testcase( sqlite4DefaultEnv.xLog!=0 );
  sqlite4_log(0, SQLITE_CORRUPT,
              "database corruption at line %d of [%.10s]",
              lineno, 20+sqlite4_sourceid());
  return SQLITE_CORRUPT;
}
int sqlite4MisuseError(int lineno){
  testcase( sqlite4DefaultEnv.xLog!=0 );
  sqlite4_log(0, SQLITE_MISUSE, 
              "misuse at line %d of [%.10s]",
              lineno, 20+sqlite4_sourceid());
  return SQLITE_MISUSE;
}
int sqlite4CantopenError(int lineno){
  testcase( sqlite4DefaultEnv.xLog!=0 );
  sqlite4_log(0, SQLITE_CANTOPEN, 
              "cannot open file at line %d of [%.10s]",
              lineno, 20+sqlite4_sourceid());
  return SQLITE_CANTOPEN;
}


/*
................................................................................
*/
int sqlite4_test_control(int op, ...){
  int rc = 0;
#ifndef SQLITE_OMIT_BUILTIN_TEST
  va_list ap;
  va_start(ap, op);
  switch( op ){













































    /*
    **  sqlite4_test_control(SQLITE_TESTCTRL_ASSERT, int X)
    **
    ** This action provides a run-time test to see whether or not
    ** assert() was enabled at compile-time.  If X is true and assert()
    ** is enabled, then the return value is true.  If X is true and
    ** assert() is disabled, then the return value is zero.  If X is

Changes to src/malloc.c.

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
..
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
...
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
...
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
*************************************************************************
**
** Memory allocation functions used throughout sqlite.
*/
#include "sqliteInt.h"
#include <stdarg.h>

/*
** State information local to the memory allocation subsystem.
*/
static SQLITE_WSD struct Mem0Global {
  sqlite4_mutex *mutex;         /* Mutex to serialize access */
} mem0 = { 0 };

/*
** Initialize the memory allocation subsystem.
*/
int sqlite4MallocInit(sqlite4_env *pEnv){
  if( pEnv->m.xMalloc==0 ){
    sqlite4MemSetDefault(pEnv);
  }
  memset(&mem0, 0, sizeof(mem0));
  if( pEnv->bCoreMutex ){
    mem0.mutex = sqlite4MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  }
  return pEnv->m.xInit(pEnv->m.pAppData);
}

/*
** Deinitialize the memory allocation subsystem.
*/
void sqlite4MallocEnd(sqlite4_env *pEnv){
  if( pEnv->m.xShutdown ){
    pEnv->m.xShutdown(pEnv->m.pAppData);
  }
  memset(&mem0, 0, sizeof(mem0));
}

/*
** Return the amount of memory currently checked out.
*/
sqlite4_uint64 sqlite4_memory_used(sqlite4_env *pEnv){
  sqlite4_uint64 n, mx;
................................................................................
    ** signed integer value might cause an integer overflow inside of the
    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
    ** 255 bytes of overhead.  SQLite itself will never use anything near
    ** this amount.  The only way to reach the limit is with sqlite4_malloc() */
    p = 0;
  }else if( pEnv->bMemstat ){
    int nFull = (n + 7)&~7;
    sqlite4_mutex_enter(mem0.mutex);
    p = pEnv->m.xMalloc(pEnv->m.pAppData, nFull);
    if( p ){
      nFull = sqlite4MallocSize(pEnv, p);
      sqlite4StatusAdd(pEnv, SQLITE_ENVSTATUS_MEMORY_USED, nFull);
      sqlite4StatusAdd(pEnv, SQLITE_ENVSTATUS_MALLOC_COUNT, 1);
    }
    sqlite4StatusSet(pEnv, SQLITE_ENVSTATUS_MALLOC_SIZE, n);
    sqlite4_mutex_leave(mem0.mutex);
  }else{
    p = pEnv->m.xMalloc(pEnv->m.pAppData, n);
  }
  assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
  return p;
}

/*
** This version of the memory allocation is for use by the application.
................................................................................
** Return the size of a memory allocation previously obtained from
** sqlite4Malloc() or sqlite4_malloc().
*/
int sqlite4MallocSize(sqlite4_env *pEnv, void *p){
  assert( sqlite4MemdebugHasType(p, MEMTYPE_HEAP) );
  assert( sqlite4MemdebugNoType(p, MEMTYPE_DB) );
  if( pEnv==0 ) pEnv = &sqlite4DefaultEnv;
  return pEnv->m.xSize(pEnv->m.pAppData, p);
}
int sqlite4DbMallocSize(sqlite4 *db, void *p){
  assert( db==0 || sqlite4_mutex_held(db->mutex) );
  if( db && isLookaside(db, p) ){
    return db->lookaside.sz;
  }else{
    sqlite4_env *pEnv = db->pEnv;
    assert( sqlite4MemdebugHasType(p, MEMTYPE_DB) );
    assert( sqlite4MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
    assert( db!=0 || sqlite4MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
    return pEnv->m.xSize(pEnv->m.pAppData, p);
  }
}

/*
** Free memory previously obtained from sqlite4Malloc().
*/
void sqlite4_free(sqlite4_env *pEnv, void *p){
  if( p==0 ) return;  /* IMP: R-49053-54554 */
  assert( sqlite4MemdebugNoType(p, MEMTYPE_DB) );
  assert( sqlite4MemdebugHasType(p, MEMTYPE_HEAP) );
  if( pEnv==0 ) pEnv = &sqlite4DefaultEnv;
  if( pEnv->bMemstat ){
    sqlite4_mutex_enter(mem0.mutex);
    sqlite4StatusAdd(pEnv,SQLITE_ENVSTATUS_MEMORY_USED,
                     -sqlite4MallocSize(pEnv, p));
    sqlite4StatusAdd(pEnv,SQLITE_ENVSTATUS_MALLOC_COUNT, -1);
    pEnv->m.xFree(pEnv->m.pAppData, p);
    sqlite4_mutex_leave(mem0.mutex);
  }else{
    pEnv->m.xFree(pEnv->m.pAppData, p);
  }
}

/*
** Free memory that might be associated with a particular database
** connection.
*/
................................................................................
  if( nBytes>=0x7fffff00 ){
    /* The 0x7ffff00 limit term is explained in comments on sqlite4Malloc() */
    return 0;
  }
  nOld = sqlite4MallocSize(pEnv, pOld);
  nNew = (nBytes + 7)&~7;
  if( pEnv->bMemstat ){
    sqlite4_mutex_enter(mem0.mutex);
    sqlite4StatusSet(pEnv, SQLITE_ENVSTATUS_MALLOC_SIZE, nBytes);
    assert( sqlite4MemdebugHasType(pOld, MEMTYPE_HEAP) );
    assert( sqlite4MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
    pNew = pEnv->m.xRealloc(pEnv->m.pAppData, pOld, nNew);
    if( pNew ){
      nNew = sqlite4MallocSize(pEnv, pNew);
      sqlite4StatusAdd(pEnv, SQLITE_ENVSTATUS_MEMORY_USED, nNew-nOld);
    }
    sqlite4_mutex_leave(mem0.mutex);
  }else{
    pNew = pEnv->m.xRealloc(pEnv->m.pAppData, pOld, nNew);
  }
  assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
  return pNew;
}

/*
** The public interface to sqlite4Realloc.  Make sure that the memory







<
<
<
<
<
<
<







<
<
<
<
|







|

<







 







|
|






|

|







 







|










|












|



|
|

|







 







|



|




|

|







11
12
13
14
15
16
17







18
19
20
21
22
23
24




25
26
27
28
29
30
31
32
33
34

35
36
37
38
39
40
41
..
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
...
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
...
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
*************************************************************************
**
** Memory allocation functions used throughout sqlite.
*/
#include "sqliteInt.h"
#include <stdarg.h>








/*
** Initialize the memory allocation subsystem.
*/
int sqlite4MallocInit(sqlite4_env *pEnv){
  if( pEnv->m.xMalloc==0 ){
    sqlite4MemSetDefault(pEnv);
  }




  return pEnv->m.xInit(pEnv->m.pMemEnv);
}

/*
** Deinitialize the memory allocation subsystem.
*/
void sqlite4MallocEnd(sqlite4_env *pEnv){
  if( pEnv->m.xShutdown ){
    pEnv->m.xShutdown(pEnv->m.pMemEnv);
  }

}

/*
** Return the amount of memory currently checked out.
*/
sqlite4_uint64 sqlite4_memory_used(sqlite4_env *pEnv){
  sqlite4_uint64 n, mx;
................................................................................
    ** signed integer value might cause an integer overflow inside of the
    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
    ** 255 bytes of overhead.  SQLite itself will never use anything near
    ** this amount.  The only way to reach the limit is with sqlite4_malloc() */
    p = 0;
  }else if( pEnv->bMemstat ){
    int nFull = (n + 7)&~7;
    sqlite4_mutex_enter(pEnv->pMemMutex);
    p = pEnv->m.xMalloc(pEnv->m.pMemEnv, nFull);
    if( p ){
      nFull = sqlite4MallocSize(pEnv, p);
      sqlite4StatusAdd(pEnv, SQLITE_ENVSTATUS_MEMORY_USED, nFull);
      sqlite4StatusAdd(pEnv, SQLITE_ENVSTATUS_MALLOC_COUNT, 1);
    }
    sqlite4StatusSet(pEnv, SQLITE_ENVSTATUS_MALLOC_SIZE, n);
    sqlite4_mutex_leave(pEnv->pMemMutex);
  }else{
    p = pEnv->m.xMalloc(pEnv->m.pMemEnv, n);
  }
  assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
  return p;
}

/*
** This version of the memory allocation is for use by the application.
................................................................................
** Return the size of a memory allocation previously obtained from
** sqlite4Malloc() or sqlite4_malloc().
*/
int sqlite4MallocSize(sqlite4_env *pEnv, void *p){
  assert( sqlite4MemdebugHasType(p, MEMTYPE_HEAP) );
  assert( sqlite4MemdebugNoType(p, MEMTYPE_DB) );
  if( pEnv==0 ) pEnv = &sqlite4DefaultEnv;
  return pEnv->m.xSize(pEnv->m.pMemEnv, p);
}
int sqlite4DbMallocSize(sqlite4 *db, void *p){
  assert( db==0 || sqlite4_mutex_held(db->mutex) );
  if( db && isLookaside(db, p) ){
    return db->lookaside.sz;
  }else{
    sqlite4_env *pEnv = db->pEnv;
    assert( sqlite4MemdebugHasType(p, MEMTYPE_DB) );
    assert( sqlite4MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
    assert( db!=0 || sqlite4MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
    return pEnv->m.xSize(pEnv->m.pMemEnv, p);
  }
}

/*
** Free memory previously obtained from sqlite4Malloc().
*/
void sqlite4_free(sqlite4_env *pEnv, void *p){
  if( p==0 ) return;  /* IMP: R-49053-54554 */
  assert( sqlite4MemdebugNoType(p, MEMTYPE_DB) );
  assert( sqlite4MemdebugHasType(p, MEMTYPE_HEAP) );
  if( pEnv==0 ) pEnv = &sqlite4DefaultEnv;
  if( pEnv->bMemstat ){
    sqlite4_mutex_enter(pEnv->pMemMutex);
    sqlite4StatusAdd(pEnv,SQLITE_ENVSTATUS_MEMORY_USED,
                     -sqlite4MallocSize(pEnv, p));
    sqlite4StatusAdd(pEnv,SQLITE_ENVSTATUS_MALLOC_COUNT, -1);
    pEnv->m.xFree(pEnv->m.pMemEnv, p);
    sqlite4_mutex_leave(pEnv->pMemMutex);
  }else{
    pEnv->m.xFree(pEnv->m.pMemEnv, p);
  }
}

/*
** Free memory that might be associated with a particular database
** connection.
*/
................................................................................
  if( nBytes>=0x7fffff00 ){
    /* The 0x7ffff00 limit term is explained in comments on sqlite4Malloc() */
    return 0;
  }
  nOld = sqlite4MallocSize(pEnv, pOld);
  nNew = (nBytes + 7)&~7;
  if( pEnv->bMemstat ){
    sqlite4_mutex_enter(pEnv->pMemMutex);
    sqlite4StatusSet(pEnv, SQLITE_ENVSTATUS_MALLOC_SIZE, nBytes);
    assert( sqlite4MemdebugHasType(pOld, MEMTYPE_HEAP) );
    assert( sqlite4MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
    pNew = pEnv->m.xRealloc(pEnv->m.pMemEnv, pOld, nNew);
    if( pNew ){
      nNew = sqlite4MallocSize(pEnv, pNew);
      sqlite4StatusAdd(pEnv, SQLITE_ENVSTATUS_MEMORY_USED, nNew-nOld);
    }
    sqlite4_mutex_leave(pEnv->pMemMutex);
  }else{
    pNew = pEnv->m.xRealloc(pEnv->m.pMemEnv, pOld, nNew);
  }
  assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
  return pNew;
}

/*
** The public interface to sqlite4Realloc.  Make sure that the memory

Changes to src/mem0.c.

52
53
54
55
56
57
58

59
60
61
     sqlite4MemInit,
     sqlite4MemShutdown,
     0, 
     0,
     0
  };
  pEnv->m = defaultMethods;

}

#endif /* SQLITE_ZERO_MALLOC */







>



52
53
54
55
56
57
58
59
60
61
62
     sqlite4MemInit,
     sqlite4MemShutdown,
     0, 
     0,
     0
  };
  pEnv->m = defaultMethods;
  pEnv->m.pMemEnv = (void*)pEnv;
}

#endif /* SQLITE_ZERO_MALLOC */

Changes to src/mem1.c.

112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
...
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
...
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
...
275
276
277
278
279
280
281

282
283
284
*/
static void *sqlite4MemMalloc(void *NotUsed, sqlite4_size_t nByte){
#ifdef SQLITE_MALLOCSIZE
  void *p = SQLITE_MALLOC( nByte );
  UNUSED_PARAMETER(NotUsed);
  if( p==0 ){
    testcase( sqlite4DefaultEnv.xLog!=0 );
    sqlite4_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  }
  return p;
#else
  sqlite4_int64 *p;
  assert( nByte>0 );
  UNUSED_PARAMETER(NotUsed);
  nByte = ROUND8(nByte);
  p = SQLITE_MALLOC( nByte+8 );
  if( p ){
    p[0] = nByte;
    p++;
  }else{
    testcase( sqlite4DefaultEnv.xLog!=0 );
    sqlite4_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  }
  return (void *)p;
#endif
}

/*
** Like free() but works for allocations obtained from sqlite4MemMalloc()
................................................................................
*/
static void *sqlite4MemRealloc(void *NotUsed, void *pPrior, int nByte){
#ifdef SQLITE_MALLOCSIZE
  void *p = SQLITE_REALLOC(pPrior, nByte);
  UNUSED_PARAMETER(NotUsed);
  if( p==0 ){
    testcase( sqlite4DefaultEnv.xLog!=0 );
    sqlite4_log(SQLITE_NOMEM,
      "failed memory resize %u to %u bytes",
      SQLITE_MALLOCSIZE(pPrior), nByte);
  }
  return p;
#else
  sqlite4_int64 *p = (sqlite4_int64*)pPrior;
  assert( pPrior!=0 && nByte>0 );
................................................................................
  p--;
  p = SQLITE_REALLOC(p, nByte+8 );
  if( p ){
    p[0] = nByte;
    p++;
  }else{
    testcase( sqlite4DefaultEnv.xLog!=0 );
    sqlite4_log(SQLITE_NOMEM,
      "failed memory resize %u to %u bytes",
      sqlite4MemSize(pPrior), nByte);
  }
  return (void*)p;
#endif
}

................................................................................
     sqlite4MemInit,
     sqlite4MemShutdown,
     0,
     0,
     0
  };
  pEnv->m = defaultMethods;

}

#endif /* SQLITE_SYSTEM_MALLOC */







|













|







 







|







 







|







 







>



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
...
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
...
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
...
275
276
277
278
279
280
281
282
283
284
285
*/
static void *sqlite4MemMalloc(void *NotUsed, sqlite4_size_t nByte){
#ifdef SQLITE_MALLOCSIZE
  void *p = SQLITE_MALLOC( nByte );
  UNUSED_PARAMETER(NotUsed);
  if( p==0 ){
    testcase( sqlite4DefaultEnv.xLog!=0 );
    sqlite4_log(0,SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  }
  return p;
#else
  sqlite4_int64 *p;
  assert( nByte>0 );
  UNUSED_PARAMETER(NotUsed);
  nByte = ROUND8(nByte);
  p = SQLITE_MALLOC( nByte+8 );
  if( p ){
    p[0] = nByte;
    p++;
  }else{
    testcase( sqlite4DefaultEnv.xLog!=0 );
    sqlite4_log(0,SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  }
  return (void *)p;
#endif
}

/*
** Like free() but works for allocations obtained from sqlite4MemMalloc()
................................................................................
*/
static void *sqlite4MemRealloc(void *NotUsed, void *pPrior, int nByte){
#ifdef SQLITE_MALLOCSIZE
  void *p = SQLITE_REALLOC(pPrior, nByte);
  UNUSED_PARAMETER(NotUsed);
  if( p==0 ){
    testcase( sqlite4DefaultEnv.xLog!=0 );
    sqlite4_log(0,SQLITE_NOMEM,
      "failed memory resize %u to %u bytes",
      SQLITE_MALLOCSIZE(pPrior), nByte);
  }
  return p;
#else
  sqlite4_int64 *p = (sqlite4_int64*)pPrior;
  assert( pPrior!=0 && nByte>0 );
................................................................................
  p--;
  p = SQLITE_REALLOC(p, nByte+8 );
  if( p ){
    p[0] = nByte;
    p++;
  }else{
    testcase( sqlite4DefaultEnv.xLog!=0 );
    sqlite4_log(0,SQLITE_NOMEM,
      "failed memory resize %u to %u bytes",
      sqlite4MemSize(pPrior), nByte);
  }
  return (void*)p;
#endif
}

................................................................................
     sqlite4MemInit,
     sqlite4MemShutdown,
     0,
     0,
     0
  };
  pEnv->m = defaultMethods;
  pEnv->m.pMemEnv = (void*)pEnv;
}

#endif /* SQLITE_SYSTEM_MALLOC */

Changes to src/mem2.c.

182
183
184
185
186
187
188
189
190

191
192
193
194
195

196
197
198
199
200
201
202
203
204

205
206
207
208
209
210
211
...
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
...
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
  pHdr = sqlite4MemsysGetHeader(p);
  return pHdr->iSize;
}

/*
** Initialize the memory allocation subsystem.
*/
static int sqlite4MemInit(void *pMem){
  assert( pMem==(void*)&mem2 );

  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  if( !sqlite4DefaultEnv.bMemstat ){
    /* If memory status is enabled, then the malloc.c wrapper will already
    ** hold the STATIC_MEM mutex when the routines here are invoked. */
    mem2.mutex = sqlite4MutexAlloc(SQLITE_MUTEX_STATIC_MEM);

  }
  return SQLITE_OK;
}

/*
** Deinitialize the memory allocation subsystem.
*/
static void sqlite4MemShutdown(void *pMem){
  assert( pMem==(void*)&mem2 );

  mem2.mutex = 0;
}

/*
** Fill a buffer with pseudo-random bytes.  This is used to preset
** the content of a new memory allocation to unpredictable values and
** to clear the content of a freed allocation to unpredictable values.
................................................................................
** allocation p.  Also return true if p==NULL.
**
** This routine is designed for use within an assert() statement, to
** verify the type of an allocation.  For example:
**
**     assert( sqlite4MemdebugHasType(p, MEMTYPE_DB) );
*/
int sqlite4MemdebugHasType(void *p, u8 eType){
  int rc = 1;
  if( p && sqlite4DefaultEnv.m.xMalloc==sqlite4MemMalloc ){
    struct MemBlockHdr *pHdr;
    pHdr = sqlite4MemsysGetHeader(p);
    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
    if( (pHdr->eType&eType)==0 ){
      rc = 0;
................................................................................
** allocation p.  Also return true if p==NULL.
**
** This routine is designed for use within an assert() statement, to
** verify the type of an allocation.  For example:
**
**     assert( sqlite4MemdebugNoType(p, MEMTYPE_DB) );
*/
int sqlite4MemdebugNoType(void *p, u8 eType){
  int rc = 1;
  if( p && sqlite4DefaultEnv.m.xMalloc==sqlite4MemMalloc ){
    struct MemBlockHdr *pHdr;
    pHdr = sqlite4MemsysGetHeader(p);
    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
    if( (pHdr->eType&eType)!=0 ){
      rc = 0;







|
|
>

|
<
<
|
>

|





|
|
>







 







|







 







|







182
183
184
185
186
187
188
189
190
191
192
193


194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
...
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
...
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
  pHdr = sqlite4MemsysGetHeader(p);
  return pHdr->iSize;
}

/*
** Initialize the memory allocation subsystem.
*/
static int sqlite4MemInit(void *pMallocEnv){
  sqlite4_env *pEnv = (sqlite4_env*)pMallocEnv;
  int rc = SQLITE_OK;
  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  if( !pEnv->bMemstat ){


    mem2.mutex = sqlite4MutexAlloc(pEnv, SQLITE_MUTEX_FAST);
    if( mem2.mutex==0 && pEnv->bCoreMutex ) rc = SQLITE_NOMEM;
  }
  return rc;
}

/*
** Deinitialize the memory allocation subsystem.
*/
static void sqlite4MemShutdown(void *NotUsed){
  UNUSED_PARAMETER(NotUsed);
  sqlite4_mutex_free(mem2.mutex);
  mem2.mutex = 0;
}

/*
** Fill a buffer with pseudo-random bytes.  This is used to preset
** the content of a new memory allocation to unpredictable values and
** to clear the content of a freed allocation to unpredictable values.
................................................................................
** allocation p.  Also return true if p==NULL.
**
** This routine is designed for use within an assert() statement, to
** verify the type of an allocation.  For example:
**
**     assert( sqlite4MemdebugHasType(p, MEMTYPE_DB) );
*/
int sqlite4MemdebugHasType(const void *p, u8 eType){
  int rc = 1;
  if( p && sqlite4DefaultEnv.m.xMalloc==sqlite4MemMalloc ){
    struct MemBlockHdr *pHdr;
    pHdr = sqlite4MemsysGetHeader(p);
    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
    if( (pHdr->eType&eType)==0 ){
      rc = 0;
................................................................................
** allocation p.  Also return true if p==NULL.
**
** This routine is designed for use within an assert() statement, to
** verify the type of an allocation.  For example:
**
**     assert( sqlite4MemdebugNoType(p, MEMTYPE_DB) );
*/
int sqlite4MemdebugNoType(const void *p, u8 eType){
  int rc = 1;
  if( p && sqlite4DefaultEnv.m.xMalloc==sqlite4MemMalloc ){
    struct MemBlockHdr *pHdr;
    pHdr = sqlite4MemsysGetHeader(p);
    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
    if( (pHdr->eType&eType)!=0 ){
      rc = 0;

Changes to src/mem5.c.

261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  ** block.  If not, then split a block of the next larger power of
  ** two in order to create a new free block of size iLogsize.
  */
  for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
  if( iBin>LOGMAX ){
    testcase( sqlite4DefaultEnv.xLog!=0 );
    sqlite4_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
    return 0;
  }
  i = memsys5UnlinkFirst(iBin);
  while( iBin>iLogsize ){
    int newSize;

    iBin--;







|







261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  ** block.  If not, then split a block of the next larger power of
  ** two in order to create a new free block of size iLogsize.
  */
  for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
  if( iBin>LOGMAX ){
    testcase( sqlite4DefaultEnv.xLog!=0 );
    sqlite4_log(0,SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
    return 0;
  }
  i = memsys5UnlinkFirst(iBin);
  while( iBin>iLogsize ){
    int newSize;

    iBin--;

Changes to src/mutex.c.

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82

83
84
85
86

87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
**
*************************************************************************
** This file contains the C functions that implement mutexes.
**
** This file contains code that is common across all mutex implementations.
*/
#include "sqliteInt.h"

#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
/*
** For debugging purposes, record when the mutex subsystem is initialized
** and uninitialized so that we can assert() if there is an attempt to
** allocate a mutex while the system is uninitialized.
*/
static SQLITE_WSD int mutexIsInit = 0;
#endif /* SQLITE_DEBUG */


#ifndef SQLITE_MUTEX_OMIT
/*
** Initialize the mutex system.
*/
int sqlite4MutexInit(void){ 
  int rc = SQLITE_OK;
  if( !sqlite4DefaultEnv.mutex.xMutexAlloc ){
    /* If the xMutexAlloc method has not been set, then the user did not
    ** install a mutex implementation via sqlite4_config() prior to 
    ** sqlite4_initialize() being called. This block copies pointers to
    ** the default implementation into the sqlite4DefaultEnv structure.
    */
    sqlite4_mutex_methods const *pFrom;
    sqlite4_mutex_methods *pTo = &sqlite4DefaultEnv.mutex;

    if( sqlite4DefaultEnv.bCoreMutex ){
      pFrom = sqlite4DefaultMutex();
    }else{
      pFrom = sqlite4NoopMutex();
    }
    memcpy(pTo, pFrom, offsetof(sqlite4_mutex_methods, xMutexAlloc));
    memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
           sizeof(*pTo) - offsetof(sqlite4_mutex_methods, xMutexFree));
    pTo->xMutexAlloc = pFrom->xMutexAlloc;

  }
  rc = sqlite4DefaultEnv.mutex.xMutexInit();

#ifdef SQLITE_DEBUG
  mutexIsInit = 1;
#endif

  return rc;
}

/*
** Shutdown the mutex system. This call frees resources allocated by
** sqlite4MutexInit().
*/
int sqlite4MutexEnd(void){
  int rc = SQLITE_OK;
  if( sqlite4DefaultEnv.mutex.xMutexEnd ){
    rc = sqlite4DefaultEnv.mutex.xMutexEnd();
  }

#ifdef SQLITE_DEBUG
  mutexIsInit = 0;
#endif

  return rc;
}

/*
** Retrieve a pointer to a static mutex or allocate a new dynamic one.
*/
sqlite4_mutex *sqlite4_mutex_alloc(int id){

#ifndef SQLITE_OMIT_AUTOINIT
  if( sqlite4_initialize(0) ) return 0;
#endif
  return sqlite4DefaultEnv.mutex.xMutexAlloc(id);

}

sqlite4_mutex *sqlite4MutexAlloc(int id){
  if( !sqlite4DefaultEnv.bCoreMutex ){
    return 0;
  }
  assert( mutexIsInit );
  return sqlite4DefaultEnv.mutex.xMutexAlloc(id);
}

/*
** Free a dynamic mutex.
*/
void sqlite4_mutex_free(sqlite4_mutex *p){
  if( p ){
    sqlite4DefaultEnv.mutex.xMutexFree(p);
  }
}

/*
** Obtain the mutex p. If some other thread already has the mutex, block
** until it can be obtained.
*/
void sqlite4_mutex_enter(sqlite4_mutex *p){
  if( p ){
    sqlite4DefaultEnv.mutex.xMutexEnter(p);
  }
}

/*
** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
*/
int sqlite4_mutex_try(sqlite4_mutex *p){
  int rc = SQLITE_OK;
  if( p ){
    return sqlite4DefaultEnv.mutex.xMutexTry(p);
  }
  return rc;
}

/*
** The sqlite4_mutex_leave() routine exits a mutex that was previously
** entered by the same thread.  The behavior is undefined if the mutex 
** is not currently entered. If a NULL pointer is passed as an argument
** this function is a no-op.
*/
void sqlite4_mutex_leave(sqlite4_mutex *p){
  if( p ){
    sqlite4DefaultEnv.mutex.xMutexLeave(p);
  }
}

#ifndef NDEBUG
/*
** The sqlite4_mutex_held() and sqlite4_mutex_notheld() routine are
** intended for use inside assert() statements.
*/
int sqlite4_mutex_held(sqlite4_mutex *p){
  return p==0 || sqlite4DefaultEnv.mutex.xMutexHeld(p);
}
int sqlite4_mutex_notheld(sqlite4_mutex *p){
  return p==0 || sqlite4DefaultEnv.mutex.xMutexNotheld(p);
}
#endif

#endif /* !defined(SQLITE_MUTEX_OMIT) */







<
<
<
<
<
<
<
<
<
<





|

|
<
<
<
<
<
<
<
<
|
|

|

<
<
<
<
>

|
<
<
<
<
<







|

|
|

<
<
<
<
<






|
>

|

<
>


|
|


<
|







|









|










|












|









|


|




10
11
12
13
14
15
16










17
18
19
20
21
22
23
24








25
26
27
28
29




30
31
32





33
34
35
36
37
38
39
40
41
42
43
44





45
46
47
48
49
50
51
52
53
54
55

56
57
58
59
60
61
62

63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
**
*************************************************************************
** This file contains the C functions that implement mutexes.
**
** This file contains code that is common across all mutex implementations.
*/
#include "sqliteInt.h"











#ifndef SQLITE_MUTEX_OMIT
/*
** Initialize the mutex system.
*/
int sqlite4MutexInit(sqlite4_env *pEnv){
  int rc = SQLITE_OK;
  if( !pEnv->mutex.xMutexAlloc ){








    if( pEnv->bCoreMutex ){
      pEnv->mutex = *sqlite4DefaultMutex();
    }else{
      pEnv->mutex = *sqlite4NoopMutex();
    }




    pEnv->mutex.pMutexEnv = pEnv;
  }
  rc = pEnv->mutex.xMutexInit(pEnv->mutex.pMutexEnv);





  return rc;
}

/*
** Shutdown the mutex system. This call frees resources allocated by
** sqlite4MutexInit().
*/
int sqlite4MutexEnd(sqlite4_env *pEnv){
  int rc = SQLITE_OK;
  if( pEnv->mutex.xMutexEnd ){
    rc = pEnv->mutex.xMutexEnd(pEnv->mutex.pMutexEnv);
  }





  return rc;
}

/*
** Retrieve a pointer to a static mutex or allocate a new dynamic one.
*/
sqlite4_mutex *sqlite4_mutex_alloc(sqlite4_env *pEnv, int id){
  if( pEnv==0 ) pEnv = &sqlite4DefaultEnv;
#ifndef SQLITE_OMIT_AUTOINIT
  if( sqlite4_initialize(pEnv) ) return 0;
#endif

  return pEnv->mutex.xMutexAlloc(pEnv->mutex.pMutexEnv, id);
}

sqlite4_mutex *sqlite4MutexAlloc(sqlite4_env *pEnv, int id){
  if( !pEnv->bCoreMutex ){
    return 0;
  }

  return pEnv->mutex.xMutexAlloc(pEnv->mutex.pMutexEnv, id);
}

/*
** Free a dynamic mutex.
*/
void sqlite4_mutex_free(sqlite4_mutex *p){
  if( p ){
    p->pMutexMethods->xMutexFree(p);
  }
}

/*
** Obtain the mutex p. If some other thread already has the mutex, block
** until it can be obtained.
*/
void sqlite4_mutex_enter(sqlite4_mutex *p){
  if( p ){
    p->pMutexMethods->xMutexEnter(p);
  }
}

/*
** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
*/
int sqlite4_mutex_try(sqlite4_mutex *p){
  int rc = SQLITE_OK;
  if( p ){
    return p->pMutexMethods->xMutexTry(p);
  }
  return rc;
}

/*
** The sqlite4_mutex_leave() routine exits a mutex that was previously
** entered by the same thread.  The behavior is undefined if the mutex 
** is not currently entered. If a NULL pointer is passed as an argument
** this function is a no-op.
*/
void sqlite4_mutex_leave(sqlite4_mutex *p){
  if( p ){
    p->pMutexMethods->xMutexLeave(p);
  }
}

#ifndef NDEBUG
/*
** The sqlite4_mutex_held() and sqlite4_mutex_notheld() routine are
** intended for use inside assert() statements.
*/
int sqlite4_mutex_held(sqlite4_mutex *p){
  return p==0 || p->pMutexMethods->xMutexHeld(p);
}
int sqlite4_mutex_notheld(sqlite4_mutex *p){
  return p==0 || p->pMutexMethods->xMutexNotheld(p);
}
#endif

#endif /* !defined(SQLITE_MUTEX_OMIT) */

Changes to src/mutex.h.

50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#  endif
#endif

#ifdef SQLITE_MUTEX_OMIT
/*
** If this is a no-op implementation, implement everything as macros.
*/
#define sqlite4_mutex_alloc(X)    ((sqlite4_mutex*)8)
#define sqlite4_mutex_free(X)
#define sqlite4_mutex_enter(X)    
#define sqlite4_mutex_try(X)      SQLITE_OK
#define sqlite4_mutex_leave(X)    
#define sqlite4_mutex_held(X)     ((void)(X),1)
#define sqlite4_mutex_notheld(X)  ((void)(X),1)
#define sqlite4MutexAlloc(X)      ((sqlite4_mutex*)8)
#define sqlite4MutexInit()        SQLITE_OK
#define sqlite4MutexEnd()
#define MUTEX_LOGIC(X)
#else
#define MUTEX_LOGIC(X)            X
#endif /* defined(SQLITE_MUTEX_OMIT) */







|






|
|
|




50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#  endif
#endif

#ifdef SQLITE_MUTEX_OMIT
/*
** If this is a no-op implementation, implement everything as macros.
*/
#define sqlite4_mutex_alloc(X,Y)  ((sqlite4_mutex*)8)
#define sqlite4_mutex_free(X)
#define sqlite4_mutex_enter(X)    
#define sqlite4_mutex_try(X)      SQLITE_OK
#define sqlite4_mutex_leave(X)    
#define sqlite4_mutex_held(X)     ((void)(X),1)
#define sqlite4_mutex_notheld(X)  ((void)(X),1)
#define sqlite4MutexAlloc(X,Y)    ((sqlite4_mutex*)8)
#define sqlite4MutexInit(E)       SQLITE_OK
#define sqlite4MutexEnd(E)
#define MUTEX_LOGIC(X)
#else
#define MUTEX_LOGIC(X)            X
#endif /* defined(SQLITE_MUTEX_OMIT) */

Changes to src/mutex_noop.c.

31
32
33
34
35
36
37
38
39
40

41
42
43
44
45
46
47
..
54
55
56
57
58
59
60
61
62
63
64
65

66
67
68
69
70
71
72
..
73
74
75
76
77
78
79
80
81


82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
...
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
...
181
182
183
184
185
186
187
188
189
190

191
192
193
194
195
196
197

#ifndef SQLITE_DEBUG
/*
** Stub routines for all mutex methods.
**
** This routines provide no mutual exclusion or error checking.
*/
static int noopMutexInit(void){ return SQLITE_OK; }
static int noopMutexEnd(void){ return SQLITE_OK; }
static sqlite4_mutex *noopMutexAlloc(int id){ 

  UNUSED_PARAMETER(id);
  return (sqlite4_mutex*)8; 
}
static void noopMutexFree(sqlite4_mutex *p){ UNUSED_PARAMETER(p); return; }
static void noopMutexEnter(sqlite4_mutex *p){ UNUSED_PARAMETER(p); return; }
static int noopMutexTry(sqlite4_mutex *p){
  UNUSED_PARAMETER(p);
................................................................................
    noopMutexInit,
    noopMutexEnd,
    noopMutexAlloc,
    noopMutexFree,
    noopMutexEnter,
    noopMutexTry,
    noopMutexLeave,

    0,
    0,
  };


  return &sMutex;
}
#endif /* !SQLITE_DEBUG */

#ifdef SQLITE_DEBUG
/*
** In this implementation, error checking is provided for testing
................................................................................
** and debugging purposes.  The mutexes still do not provide any
** mutual exclusion.
*/

/*
** The mutex object
*/
typedef struct sqlite4_debug_mutex {
  int id;     /* The mutex type */


  int cnt;    /* Number of entries without a matching leave */
} sqlite4_debug_mutex;

/*
** The sqlite4_mutex_held() and sqlite4_mutex_notheld() routine are
** intended for use inside assert() statements.
*/
static int debugMutexHeld(sqlite4_mutex *pX){
  sqlite4_debug_mutex *p = (sqlite4_debug_mutex*)pX;
  return p==0 || p->cnt>0;
}
static int debugMutexNotheld(sqlite4_mutex *pX){
  sqlite4_debug_mutex *p = (sqlite4_debug_mutex*)pX;
  return p==0 || p->cnt==0;
}

/*
** Initialize and deinitialize the mutex subsystem.
*/
static int debugMutexInit(void){ return SQLITE_OK; }
static int debugMutexEnd(void){ return SQLITE_OK; }

/*
** The sqlite4_mutex_alloc() routine allocates a new
** mutex and returns a pointer to it.  If it returns NULL
** that means that a mutex could not be allocated. 
*/
static sqlite4_mutex *debugMutexAlloc(int id){
  static sqlite4_debug_mutex aStatic[6];
  sqlite4_debug_mutex *pNew = 0;
  switch( id ){
    case SQLITE_MUTEX_FAST:
    case SQLITE_MUTEX_RECURSIVE: {
      pNew = sqlite4Malloc(0, sizeof(*pNew));
      if( pNew ){
        pNew->id = id;
        pNew->cnt = 0;
      }
      break;
    }
    default: {
      assert( id-2 >= 0 );
      assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
      pNew = &aStatic[id-2];
      pNew->id = id;
      break;
    }
  }
  return (sqlite4_mutex*)pNew;
}

/*
** This routine deallocates a previously allocated mutex.
*/
static void debugMutexFree(sqlite4_mutex *pX){
  sqlite4_debug_mutex *p = (sqlite4_debug_mutex*)pX;
  assert( p->cnt==0 );
  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  sqlite4_free(0, p);
}

/*
** The sqlite4_mutex_enter() and sqlite4_mutex_try() routines attempt
** to enter a mutex.  If another thread is already within the mutex,
** sqlite4_mutex_enter() will block and sqlite4_mutex_try() will return
** SQLITE_BUSY.  The sqlite4_mutex_try() interface returns SQLITE_OK
................................................................................
** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
** be entered multiple times by the same thread.  In such cases the,
** mutex must be exited an equal number of times before another thread
** can enter.  If the same thread tries to enter any other kind of mutex
** more than once, the behavior is undefined.
*/
static void debugMutexEnter(sqlite4_mutex *pX){
  sqlite4_debug_mutex *p = (sqlite4_debug_mutex*)pX;
  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  p->cnt++;
}
static int debugMutexTry(sqlite4_mutex *pX){
  sqlite4_debug_mutex *p = (sqlite4_debug_mutex*)pX;
  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  p->cnt++;
  return SQLITE_OK;
}

/*
** The sqlite4_mutex_leave() routine exits a mutex that was
** previously entered by the same thread.  The behavior
** is undefined if the mutex is not currently entered or
** is not currently allocated.  SQLite will never do either.
*/
static void debugMutexLeave(sqlite4_mutex *pX){
  sqlite4_debug_mutex *p = (sqlite4_debug_mutex*)pX;
  assert( debugMutexHeld(pX) );
  p->cnt--;
  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
}

sqlite4_mutex_methods const *sqlite4NoopMutex(void){
  static const sqlite4_mutex_methods sMutex = {
................................................................................
    debugMutexInit,
    debugMutexEnd,
    debugMutexAlloc,
    debugMutexFree,
    debugMutexEnter,
    debugMutexTry,
    debugMutexLeave,

    debugMutexHeld,
    debugMutexNotheld

  };

  return &sMutex;
}
#endif /* SQLITE_DEBUG */

/*







|
|
|
>







 







<


<
|
>







 







|
|
>
>
|
|






|



|






|
|






|
<
|
<
<
<
|
|
|
|
<
<
<
<
<
<
<
|
<
<








|

<
|







 







|




|












|







 







<

|
>







31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
..
55
56
57
58
59
60
61

62
63

64
65
66
67
68
69
70
71
72
..
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111

112



113
114
115
116







117


118
119
120
121
122
123
124
125
126
127

128
129
130
131
132
133
134
135
...
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
...
169
170
171
172
173
174
175

176
177
178
179
180
181
182
183
184
185

#ifndef SQLITE_DEBUG
/*
** Stub routines for all mutex methods.
**
** This routines provide no mutual exclusion or error checking.
*/
static int noopMutexInit(void *p){ UNUSED_PARAMETER(p); return SQLITE_OK; }
static int noopMutexEnd(void *p){ UNUSED_PARAMETER(p); return SQLITE_OK; }
static sqlite4_mutex *noopMutexAlloc(sqlite4_env *pEnv, int id){ 
  UNUSED_PARAMETER(pEnv);
  UNUSED_PARAMETER(id);
  return (sqlite4_mutex*)8; 
}
static void noopMutexFree(sqlite4_mutex *p){ UNUSED_PARAMETER(p); return; }
static void noopMutexEnter(sqlite4_mutex *p){ UNUSED_PARAMETER(p); return; }
static int noopMutexTry(sqlite4_mutex *p){
  UNUSED_PARAMETER(p);
................................................................................
    noopMutexInit,
    noopMutexEnd,
    noopMutexAlloc,
    noopMutexFree,
    noopMutexEnter,
    noopMutexTry,
    noopMutexLeave,

    0,
    0,

    0
  };
  return &sMutex;
}
#endif /* !SQLITE_DEBUG */

#ifdef SQLITE_DEBUG
/*
** In this implementation, error checking is provided for testing
................................................................................
** and debugging purposes.  The mutexes still do not provide any
** mutual exclusion.
*/

/*
** The mutex object
*/
typedef struct sqlite4DebugMutex {
  sqlite4_mutex base;    /* Base class. Must be first */
  sqlite4_env *pEnv;     /* Run-time environment */
  int id;                /* Type of mutex */
  int cnt;               /* Number of entries without a matching leave */
} sqlite4DebugMutex;

/*
** The sqlite4_mutex_held() and sqlite4_mutex_notheld() routine are
** intended for use inside assert() statements.
*/
static int debugMutexHeld(sqlite4_mutex *pX){
  sqlite4DebugMutex *p = (sqlite4DebugMutex*)pX;
  return p==0 || p->cnt>0;
}
static int debugMutexNotheld(sqlite4_mutex *pX){
  sqlite4DebugMutex *p = (sqlite4DebugMutex*)pX;
  return p==0 || p->cnt==0;
}

/*
** Initialize and deinitialize the mutex subsystem.
*/
static int debugMutexInit(void *p){ UNUSED_PARAMETER(p); return SQLITE_OK; }
static int debugMutexEnd(void *p){ UNUSED_PARAMETER(p); return SQLITE_OK; }

/*
** The sqlite4_mutex_alloc() routine allocates a new
** mutex and returns a pointer to it.  If it returns NULL
** that means that a mutex could not be allocated. 
*/
static sqlite4_mutex *debugMutexAlloc(sqlite4_env *pEnv, int id){

  sqlite4DebugMutex *pNew = 0;



  pNew = sqlite4Malloc(pEnv, sizeof(*pNew));
  if( pNew ){
    pNew->id = id;
    pNew->cnt = 0;







    pNew->pEnv = pEnv;


  }
  return (sqlite4_mutex*)pNew;
}

/*
** This routine deallocates a previously allocated mutex.
*/
static void debugMutexFree(sqlite4_mutex *pX){
  sqlite4DebugMutex *p = (sqlite4DebugMutex*)pX;
  assert( p->cnt==0 );

  sqlite4_free(p->pEnv, p);
}

/*
** The sqlite4_mutex_enter() and sqlite4_mutex_try() routines attempt
** to enter a mutex.  If another thread is already within the mutex,
** sqlite4_mutex_enter() will block and sqlite4_mutex_try() will return
** SQLITE_BUSY.  The sqlite4_mutex_try() interface returns SQLITE_OK
................................................................................
** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
** be entered multiple times by the same thread.  In such cases the,
** mutex must be exited an equal number of times before another thread
** can enter.  If the same thread tries to enter any other kind of mutex
** more than once, the behavior is undefined.
*/
static void debugMutexEnter(sqlite4_mutex *pX){
  sqlite4DebugMutex *p = (sqlite4DebugMutex*)pX;
  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  p->cnt++;
}
static int debugMutexTry(sqlite4_mutex *pX){
  sqlite4DebugMutex *p = (sqlite4DebugMutex*)pX;
  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  p->cnt++;
  return SQLITE_OK;
}

/*
** The sqlite4_mutex_leave() routine exits a mutex that was
** previously entered by the same thread.  The behavior
** is undefined if the mutex is not currently entered or
** is not currently allocated.  SQLite will never do either.
*/
static void debugMutexLeave(sqlite4_mutex *pX){
  sqlite4DebugMutex *p = (sqlite4DebugMutex*)pX;
  assert( debugMutexHeld(pX) );
  p->cnt--;
  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
}

sqlite4_mutex_methods const *sqlite4NoopMutex(void){
  static const sqlite4_mutex_methods sMutex = {
................................................................................
    debugMutexInit,
    debugMutexEnd,
    debugMutexAlloc,
    debugMutexFree,
    debugMutexEnter,
    debugMutexTry,
    debugMutexLeave,

    debugMutexHeld,
    debugMutexNotheld, 
    0
  };

  return &sMutex;
}
#endif /* SQLITE_DEBUG */

/*

Changes to src/mutex_unix.c.

34
35
36
37
38
39
40
41

42
43
44
45
46
47
48
49
50

51
52
53
54
55
56
57
58
59
60
..
66
67
68
69
70
71
72
73

74
75
76

77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
...
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
...
151
152
153
154
155
156
157

158
159
160
161
162
163
164
165
166
167


168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190


191
192
193

194
195
196
197
198
199
200
201
202
203
204
205
206
207
208

209
210
211
212
213
214
215
216
...
243
244
245
246
247
248
249
250
251

252
253
254
255
256
257
258
259
...
300
301
302
303
304
305
306
307

308
309
310
311
312
313
314
315
...
334
335
336
337
338
339
340
341
342
343
344
345

346
347
348
349
350
351
#else
# define SQLITE_MUTEX_NREF 0
#endif

/*
** Each recursive mutex is an instance of the following structure.
*/
struct sqlite4_mutex {

  pthread_mutex_t mutex;     /* Mutex controlling the lock */
#if SQLITE_MUTEX_NREF
  int id;                    /* Mutex type */
  volatile int nRef;         /* Number of entrances */
  volatile pthread_t owner;  /* Thread that is within this mutex */
  int trace;                 /* True to trace changes */
#endif
};
#if SQLITE_MUTEX_NREF

#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
#else
#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
#endif

/*
** The sqlite4_mutex_held() and sqlite4_mutex_notheld() routine are
** intended for use only inside assert() statements.  On some platforms,
** there might be race conditions that can cause these routines to
** deliver incorrect results.  In particular, if pthread_equal() is
................................................................................
**
** On those platforms where pthread_equal() is not atomic, SQLite
** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
** make sure no assert() statements are evaluated and hence these
** routines are never called.
*/
#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
static int pthreadMutexHeld(sqlite4_mutex *p){

  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
}
static int pthreadMutexNotheld(sqlite4_mutex *p){

  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
}
#endif

/*
** Initialize and deinitialize the mutex subsystem.
*/
static int pthreadMutexInit(void){ return SQLITE_OK; }
static int pthreadMutexEnd(void){ return SQLITE_OK; }

/*
** The sqlite4_mutex_alloc() routine allocates a new
** mutex and returns a pointer to it.  If it returns NULL
** that means that a mutex could not be allocated.  SQLite
** will unwind its stack and return an error.  The argument
** to sqlite4_mutex_alloc() is one of these integer constants:
................................................................................
**
** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
** or SQLITE_MUTEX_RECURSIVE) is used then sqlite4_mutex_alloc()
** returns a different mutex on every call.  But for the static 
** mutex types, the same mutex is returned on every call that has
** the same type number.
*/
static sqlite4_mutex *pthreadMutexAlloc(int iType){
  static sqlite4_mutex staticMutexes[] = {
    SQLITE3_MUTEX_INITIALIZER,
    SQLITE3_MUTEX_INITIALIZER,
    SQLITE3_MUTEX_INITIALIZER,
    SQLITE3_MUTEX_INITIALIZER,
    SQLITE3_MUTEX_INITIALIZER,
    SQLITE3_MUTEX_INITIALIZER
  };
  sqlite4_mutex *p;
  switch( iType ){
    case SQLITE_MUTEX_RECURSIVE: {
      p = sqlite4MallocZero(0, sizeof(*p) );
      if( p ){
#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
        /* If recursive mutexes are not available, we will have to
        ** build our own.  See below. */
        pthread_mutex_init(&p->mutex, 0);
#else
        /* Use a recursive mutex if it is available */
................................................................................
        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
        pthread_mutex_init(&p->mutex, &recursiveAttr);
        pthread_mutexattr_destroy(&recursiveAttr);
#endif
#if SQLITE_MUTEX_NREF
        p->id = iType;
#endif

      }
      break;
    }
    case SQLITE_MUTEX_FAST: {
      p = sqlite4MallocZero(0, sizeof(*p) );
      if( p ){
#if SQLITE_MUTEX_NREF
        p->id = iType;
#endif
        pthread_mutex_init(&p->mutex, 0);


      }
      break;
    }
    default: {
      assert( iType-2 >= 0 );
      assert( iType-2 < ArraySize(staticMutexes) );
      p = &staticMutexes[iType-2];
#if SQLITE_MUTEX_NREF
      p->id = iType;
#endif
      break;
    }
  }
  return p;
}


/*
** This routine deallocates a previously
** allocated mutex.  SQLite is careful to deallocate every
** mutex that it allocates.
*/
static void pthreadMutexFree(sqlite4_mutex *p){


  assert( p->nRef==0 );
  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  pthread_mutex_destroy(&p->mutex);

  sqlite4_free(0, p);
}

/*
** The sqlite4_mutex_enter() and sqlite4_mutex_try() routines attempt
** to enter a mutex.  If another thread is already within the mutex,
** sqlite4_mutex_enter() will block and sqlite4_mutex_try() will return
** SQLITE_BUSY.  The sqlite4_mutex_try() interface returns SQLITE_OK
** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
** be entered multiple times by the same thread.  In such cases the,
** mutex must be exited an equal number of times before another thread
** can enter.  If the same thread tries to enter any other kind of mutex
** more than once, the behavior is undefined.
*/
static void pthreadMutexEnter(sqlite4_mutex *p){

  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );

#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  /* If recursive mutexes are not available, then we have to grow
  ** our own.  This implementation assumes that pthread_equal()
  ** is atomic - that it cannot be deceived into thinking self
  ** and p->owner are equal if p->owner changes between two values
  ** that are not equal to self while the comparison is taking place.
................................................................................

#ifdef SQLITE_DEBUG
  if( p->trace ){
    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  }
#endif
}
static int pthreadMutexTry(sqlite4_mutex *p){
  int rc;

  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );

#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  /* If recursive mutexes are not available, then we have to grow
  ** our own.  This implementation assumes that pthread_equal()
  ** is atomic - that it cannot be deceived into thinking self
  ** and p->owner are equal if p->owner changes between two values
  ** that are not equal to self while the comparison is taking place.
................................................................................

/*
** The sqlite4_mutex_leave() routine exits a mutex that was
** previously entered by the same thread.  The behavior
** is undefined if the mutex is not currently entered or
** is not currently allocated.  SQLite will never do either.
*/
static void pthreadMutexLeave(sqlite4_mutex *p){

  assert( pthreadMutexHeld(p) );
#if SQLITE_MUTEX_NREF
  p->nRef--;
  if( p->nRef==0 ) p->owner = 0;
#endif
  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );

#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
................................................................................
    pthreadMutexAlloc,
    pthreadMutexFree,
    pthreadMutexEnter,
    pthreadMutexTry,
    pthreadMutexLeave,
#ifdef SQLITE_DEBUG
    pthreadMutexHeld,
    pthreadMutexNotheld
#else
    0,
    0
#endif

  };

  return &sMutex;
}

#endif /* SQLITE_MUTEX_PTHREADS */







|
>







|

>
|

|







 







|
>


|
>







|
|







 







|
|
<
<
<
<
<
<
<
|


|







 







>




|





>
>




|
<
<
<
<
<



|








|
>
>



>
|













|
>
|







 







|

>
|







 







|
>
|







 







|


|

>






34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
..
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
...
126
127
128
129
130
131
132
133
134







135
136
137
138
139
140
141
142
143
144
145
...
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172





173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
...
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
...
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
...
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
#else
# define SQLITE_MUTEX_NREF 0
#endif

/*
** Each recursive mutex is an instance of the following structure.
*/
typedef struct sqlite4UnixMutex {
  sqlite4_mutex base;        /* Base class.  Must be first */
  pthread_mutex_t mutex;     /* Mutex controlling the lock */
#if SQLITE_MUTEX_NREF
  int id;                    /* Mutex type */
  volatile int nRef;         /* Number of entrances */
  volatile pthread_t owner;  /* Thread that is within this mutex */
  int trace;                 /* True to trace changes */
#endif
} sqlite4UnixMutex;
#if SQLITE_MUTEX_NREF
#define SQLITE3_MUTEX_INITIALIZER \
  { 0, PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
#else
#define SQLITE3_MUTEX_INITIALIZER { 0, PTHREAD_MUTEX_INITIALIZER }
#endif

/*
** The sqlite4_mutex_held() and sqlite4_mutex_notheld() routine are
** intended for use only inside assert() statements.  On some platforms,
** there might be race conditions that can cause these routines to
** deliver incorrect results.  In particular, if pthread_equal() is
................................................................................
**
** On those platforms where pthread_equal() is not atomic, SQLite
** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
** make sure no assert() statements are evaluated and hence these
** routines are never called.
*/
#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
static int pthreadMutexHeld(sqlite4_mutex *pMutex){
  sqlite4UnixMutex *p = (sqlite4UnixMutex*)pMutex;
  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
}
static int pthreadMutexNotheld(sqlite4_mutex *pMutex){
  sqlite4UnixMutex *p = (sqlite4UnixMutex*)pMutex;
  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
}
#endif

/*
** Initialize and deinitialize the mutex subsystem.
*/
static int pthreadMutexInit(void *p){ UNUSED_PARAMETER(p); return SQLITE_OK; }
static int pthreadMutexEnd(void *p){ UNUSED_PARAMETER(p); return SQLITE_OK; }

/*
** The sqlite4_mutex_alloc() routine allocates a new
** mutex and returns a pointer to it.  If it returns NULL
** that means that a mutex could not be allocated.  SQLite
** will unwind its stack and return an error.  The argument
** to sqlite4_mutex_alloc() is one of these integer constants:
................................................................................
**
** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
** or SQLITE_MUTEX_RECURSIVE) is used then sqlite4_mutex_alloc()
** returns a different mutex on every call.  But for the static 
** mutex types, the same mutex is returned on every call that has
** the same type number.
*/
static sqlite4_mutex *pthreadMutexAlloc(void *pMutexEnv, int iType){
  sqlite4_env *pEnv = (sqlite4_env*)pMutexEnv;







  sqlite4UnixMutex *p;
  switch( iType ){
    case SQLITE_MUTEX_RECURSIVE: {
      p = sqlite4MallocZero(pEnv, sizeof(*p) );
      if( p ){
#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
        /* If recursive mutexes are not available, we will have to
        ** build our own.  See below. */
        pthread_mutex_init(&p->mutex, 0);
#else
        /* Use a recursive mutex if it is available */
................................................................................
        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
        pthread_mutex_init(&p->mutex, &recursiveAttr);
        pthread_mutexattr_destroy(&recursiveAttr);
#endif
#if SQLITE_MUTEX_NREF
        p->id = iType;
#endif
        p->base.pMutexMethods = &pEnv->mutex;
      }
      break;
    }
    case SQLITE_MUTEX_FAST: {
      p = sqlite4MallocZero(pEnv, sizeof(*p) );
      if( p ){
#if SQLITE_MUTEX_NREF
        p->id = iType;
#endif
        pthread_mutex_init(&p->mutex, 0);
        p->base.pMutexMethods = &pEnv->mutex;
        assert( p->base.pMutexMethods->pMutexEnv==(void*)pEnv );
      }
      break;
    }
    default: {
      p = 0;





      break;
    }
  }
  return (sqlite4_mutex*)p;
}


/*
** This routine deallocates a previously
** allocated mutex.  SQLite is careful to deallocate every
** mutex that it allocates.
*/
static void pthreadMutexFree(sqlite4_mutex *pMutex){
  sqlite4UnixMutex *p = (sqlite4UnixMutex*)pMutex;
  sqlite4_env *pEnv;
  assert( p->nRef==0 );
  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  pthread_mutex_destroy(&p->mutex);
  pEnv = (sqlite4_env*)p->base.pMutexMethods->pMutexEnv;
  sqlite4_free(pEnv, p);
}

/*
** The sqlite4_mutex_enter() and sqlite4_mutex_try() routines attempt
** to enter a mutex.  If another thread is already within the mutex,
** sqlite4_mutex_enter() will block and sqlite4_mutex_try() will return
** SQLITE_BUSY.  The sqlite4_mutex_try() interface returns SQLITE_OK
** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
** be entered multiple times by the same thread.  In such cases the,
** mutex must be exited an equal number of times before another thread
** can enter.  If the same thread tries to enter any other kind of mutex
** more than once, the behavior is undefined.
*/
static void pthreadMutexEnter(sqlite4_mutex *pMutex){
  sqlite4UnixMutex *p = (sqlite4UnixMutex*)pMutex;
  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(pMutex) );

#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  /* If recursive mutexes are not available, then we have to grow
  ** our own.  This implementation assumes that pthread_equal()
  ** is atomic - that it cannot be deceived into thinking self
  ** and p->owner are equal if p->owner changes between two values
  ** that are not equal to self while the comparison is taking place.
................................................................................

#ifdef SQLITE_DEBUG
  if( p->trace ){
    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  }
#endif
}
static int pthreadMutexTry(sqlite4_mutex *pMutex){
  int rc;
  sqlite4UnixMutex *p = (sqlite4UnixMutex*)pMutex;
  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(pMutex) );

#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  /* If recursive mutexes are not available, then we have to grow
  ** our own.  This implementation assumes that pthread_equal()
  ** is atomic - that it cannot be deceived into thinking self
  ** and p->owner are equal if p->owner changes between two values
  ** that are not equal to self while the comparison is taking place.
................................................................................

/*
** The sqlite4_mutex_leave() routine exits a mutex that was
** previously entered by the same thread.  The behavior
** is undefined if the mutex is not currently entered or
** is not currently allocated.  SQLite will never do either.
*/
static void pthreadMutexLeave(sqlite4_mutex *pMutex){
  sqlite4UnixMutex *p = (sqlite4UnixMutex*)pMutex;
  assert( pthreadMutexHeld(pMutex) );
#if SQLITE_MUTEX_NREF
  p->nRef--;
  if( p->nRef==0 ) p->owner = 0;
#endif
  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );

#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
................................................................................
    pthreadMutexAlloc,
    pthreadMutexFree,
    pthreadMutexEnter,
    pthreadMutexTry,
    pthreadMutexLeave,
#ifdef SQLITE_DEBUG
    pthreadMutexHeld,
    pthreadMutexNotheld,
#else
    0,
    0,
#endif
    0
  };

  return &sMutex;
}

#endif /* SQLITE_MUTEX_PTHREADS */

Changes to src/os.c.

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31













32


























33


















34
35
36
37
38
39
40
41
42
43
44
45
46

47
48
** This file contains OS interface code that is common to all
** architectures.
*/
#define _SQLITE_OS_C_ 1
#include "sqliteInt.h"
#undef _SQLITE_OS_C_

int sqlite4OsRandomness(sqlite4_env *pEnv, int nByte, unsigned char *zBufOut){
  memset(zBufOut, 0, nByte);
  return SQLITE_OK;
}

/*
** The following variable, if set to a non-zero value, is interpreted as
** the number of seconds since 1970 and is used to set the result of
** sqlite4OsCurrentTime() during testing.
*/
unsigned int sqlite4_current_time = 0; /* Fake system time */
int sqlite4OsCurrentTime(sqlite4_env *pEnv, sqlite4_uint64 *pTimeOut){













  UNUSED_PARAMETER(pEnv);


























  *pTimeOut = (sqlite4_uint64)sqlite4_current_time * 1000;


















  return SQLITE_OK;
}

/*
** This function is a wrapper around the OS specific implementation of
** sqlite4_os_init(). The purpose of the wrapper is to provide the
** ability to simulate a malloc failure, so that the handling of an
** error in sqlite4_os_init() by the upper layers can be tested.
*/
int sqlite4OsInit(sqlite4_env *pEnv){
  void *p = sqlite4_malloc(pEnv, 10);
  if( p==0 ) return SQLITE_NOMEM;
  sqlite4_free(pEnv, p);

  return SQLITE_OK; /*sqlite4_os_init();*/
}







|
|
|
<








>
>
>
>
>
>
>
>
>
>
>
>
>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>













>


13
14
15
16
17
18
19
20
21
22

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
** This file contains OS interface code that is common to all
** architectures.
*/
#define _SQLITE_OS_C_ 1
#include "sqliteInt.h"
#undef _SQLITE_OS_C_

#if SQLITE_OS_UNIX
#include <sys/time.h>
#endif


/*
** The following variable, if set to a non-zero value, is interpreted as
** the number of seconds since 1970 and is used to set the result of
** sqlite4OsCurrentTime() during testing.
*/
unsigned int sqlite4_current_time = 0; /* Fake system time */
int sqlite4OsCurrentTime(sqlite4_env *pEnv, sqlite4_uint64 *pTimeOut){
  int rc = SQLITE_OK;
  if( sqlite4_current_time ){
    *pTimeOut = (sqlite4_uint64)sqlite4_current_time * 1000;
    return SQLITE_OK;
  }
#if SQLITE_OS_UNIX
  static const sqlite4_int64 unixEpoch = 24405875*(sqlite4_int64)8640000;
  struct timeval sNow;
  if( gettimeofday(&sNow, 0)==0 ){
    *pTimeOut = unixEpoch + 1000*(sqlite4_int64)sNow.tv_sec + sNow.tv_usec/1000;
  }else{
    rc = SQLITE_ERROR;
  }
  UNUSED_PARAMETER(pEnv);
#endif
#if SQLITE_OS_WIN
  FILETIME ft;
  static const sqlite4_int64 winFiletimeEpoch =
                                 23058135*(sqlite4_int64)8640000;
  /* 2^32 - to avoid use of LL and warnings in gcc */
  static const sqlite4_int64 max32BitValue = 
      (sqlite4_int64)2000000000 + (sqlite4_int64)2000000000
         + (sqlite4_int64)294967296;
  GetSystemTimeAsFileTime( &ft );
  *pTimeOut = winFiletimeEpoch +
                ((((sqlite4_int64)ft.dwHighDateTime)*max32BitValue) + 
                   (sqlite4_int64)ft.dwLowDateTime)/(sqlite4_int64)10000;
  UNUSED_PARAMETER(pEnv);
#endif
  return rc;
}

/*
** Write nByte bytes of randomness into zBufOut[].  This is used to initialize
** the PRNGs.  nByte will always be 8.
*/
int sqlite4OsRandomness(sqlite4_env *pEnv, int nByte, unsigned char *zBufOut){
  static sqlite4_uint64 cnt = 0;
  unsigned char *p;
  int i;
  sqlite4_uint64 now;
  sqlite4_uint64 x = 0;

#if 0 && SQLITE_OS_UNIX
  int fd = open("/dev/urandom", O_RDONLY, 0);
  if( fd>=0 ){
    read(fd, zBufOut, nByte);
    close(fd);
  }
  x = getpid();
#endif
  sqlite4OsCurrentTime(pEnv, &now);
  x ^= now;
  memset(zBufOut, 0, nByte);
  cnt++;
  x ^= cnt;
  p = (unsigned char*)&x;
  for(i=0; i<8; i++) zBufOut[i%nByte] ^= p[i];
    
  return SQLITE_OK;
}

/*
** This function is a wrapper around the OS specific implementation of
** sqlite4_os_init(). The purpose of the wrapper is to provide the
** ability to simulate a malloc failure, so that the handling of an
** error in sqlite4_os_init() by the upper layers can be tested.
*/
int sqlite4OsInit(sqlite4_env *pEnv){
  void *p = sqlite4_malloc(pEnv, 10);
  if( p==0 ) return SQLITE_NOMEM;
  sqlite4_free(pEnv, p);
  sqlite4OsRandomness(pEnv, 8, (unsigned char*)&pEnv->prngX);
  return SQLITE_OK; /*sqlite4_os_init();*/
}

Changes to src/printf.c.

921
922
923
924
925
926
927
928





929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944

945
946
947
948
949
950
951
952
953
** We house it in a separate routine from sqlite4_log() to avoid using
** stack space on small-stack systems when logging is disabled.
**
** sqlite4_log() must render into a static buffer.  It cannot dynamically
** allocate memory because it might be called while the memory allocator
** mutex is held.
*/
static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){





  StrAccum acc;                          /* String accumulator */
  char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */

  sqlite4StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
  acc.useMalloc = 0;
  sqlite4VXPrintf(&acc, 0, zFormat, ap);
  sqlite4DefaultEnv.xLog(sqlite4DefaultEnv.pLogArg, iErrCode,
                           sqlite4StrAccumFinish(&acc));
}

/*
** Format and write a message to the log if logging is enabled.
*/
void sqlite4_log(int iErrCode, const char *zFormat, ...){
  va_list ap;                             /* Vararg list */
  if( sqlite4DefaultEnv.xLog ){

    va_start(ap, zFormat);
    renderLogMsg(iErrCode, zFormat, ap);
    va_end(ap);
  }
}

#if defined(SQLITE_DEBUG)
/*
** A version of printf() that understands %lld.  Used for debugging.







|
>
>
>
>
>






<
|





|

|
>

|







921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939

940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
** We house it in a separate routine from sqlite4_log() to avoid using
** stack space on small-stack systems when logging is disabled.
**
** sqlite4_log() must render into a static buffer.  It cannot dynamically
** allocate memory because it might be called while the memory allocator
** mutex is held.
*/
static void renderLogMsg(
  sqlite4_env *pEnv,                     /* Run-time environment */
  int iErrCode,                          /* Error code */
  const char *zFormat,                   /* Error format string */
  va_list ap                             /* Arguments */
){
  StrAccum acc;                          /* String accumulator */
  char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */

  sqlite4StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
  acc.useMalloc = 0;
  sqlite4VXPrintf(&acc, 0, zFormat, ap);

  pEnv->xLog(pEnv->pLogArg, iErrCode, sqlite4StrAccumFinish(&acc));
}

/*
** Format and write a message to the log if logging is enabled.
*/
void sqlite4_log(sqlite4_env *pEnv, int iErrCode, const char *zFormat, ...){
  va_list ap;                             /* Vararg list */
  if( pEnv==0 ) pEnv = &sqlite4DefaultEnv;
  if( pEnv->xLog ){
    va_start(ap, zFormat);
    renderLogMsg(pEnv, iErrCode, zFormat, ap);
    va_end(ap);
  }
}

#if defined(SQLITE_DEBUG)
/*
** A version of printf() that understands %lld.  Used for debugging.

Changes to src/random.c.

14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109

110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
**
** Random numbers are used by some of the database backends in order
** to generate random integer keys for tables or random filenames.
*/
#include "sqliteInt.h"


/* All threads share a single random number generator.
** This structure is the current state of the generator.
*/
static SQLITE_WSD struct sqlite4PrngType {
  unsigned char isInit;          /* True if initialized */
  unsigned char i, j;            /* State variables */
  unsigned char s[256];          /* State variables */
} sqlite4Prng;

/*
** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
** must be held while executing this routine.
**
** Why not just use a library random generator like lrand48() for this?
** Because the OP_NewRowid opcode in the VDBE depends on having a very
** good source of random numbers.  The lrand48() library function may
** well be good enough.  But maybe not.  Or maybe lrand48() has some
** subtle problems on some systems that could cause problems.  It is hard
** to know.  To minimize the risk of problems due to bad lrand48()
** implementations, SQLite uses this random number generator based
** on RC4, which we know works very well.
**
** (Later):  Actually, OP_NewRowid does not depend on a good source of
** randomness any more.  But we will leave this code in all the same.
*/
static u8 randomByte(void){
  unsigned char t;





  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  ** state vector.  If writable static data is unsupported on the target,
  ** we have to locate the state vector at run-time.  In the more common
  ** case where writable static data is supported, wsdPrng can refer directly
  ** to the "sqlite4Prng" state vector declared above.
  */
#ifdef SQLITE_OMIT_WSD
  struct sqlite4PrngType *p = sqlite4Prng;
# define wsdPrng p[0]
#else
# define wsdPrng sqlite4Prng
#endif


  /* Initialize the state of the random number generator once,
  ** the first time this routine is called.  The seed value does
  ** not need to contain a lot of randomness since we are not
  ** trying to do secure encryption or anything like that...
  **
  ** Nothing in this file or anywhere else in SQLite does any kind of
  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
  ** number generator) not as an encryption device.
  */
  if( !wsdPrng.isInit ){
    int i;
    char k[256];
    wsdPrng.j = 0;
    wsdPrng.i = 0;
    sqlite4OsRandomness(0, 256, k);
    for(i=0; i<256; i++){
      wsdPrng.s[i] = (u8)i;
    }
    for(i=0; i<256; i++){
      wsdPrng.j += wsdPrng.s[i] + k[i];
      t = wsdPrng.s[wsdPrng.j];
      wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
      wsdPrng.s[i] = t;
    }
    wsdPrng.isInit = 1;
  }

  /* Generate and return single random byte
  */
  wsdPrng.i++;
  t = wsdPrng.s[wsdPrng.i];
  wsdPrng.j += t;
  wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  wsdPrng.s[wsdPrng.j] = t;
  t += wsdPrng.s[wsdPrng.i];
  return wsdPrng.s[t];
}

/*
** Return N random bytes.
*/
void sqlite4_randomness(sqlite4_env *pEnv, int N, void *pBuf){
  unsigned char *zBuf = pBuf;
#if SQLITE_THREADSAFE
  sqlite4_mutex *mutex = sqlite4MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
#endif

  sqlite4_mutex_enter(mutex);
  while( N-- ){
    *(zBuf++) = randomByte();
  }
  sqlite4_mutex_leave(mutex);
}

#ifndef SQLITE_OMIT_BUILTIN_TEST
/*
** For testing purposes, we sometimes want to preserve the state of
** PRNG and restore the PRNG to its saved state at a later time, or
** to reset the PRNG to its initial state.  These routines accomplish
** those tasks.
**
** The sqlite4_test_control() interface calls these routines to
** control the PRNG.
*/
static SQLITE_WSD struct sqlite4PrngType sqlite4SavedPrng;
void sqlite4PrngSaveState(void){
  memcpy(&sqlite4SavedPrng, &sqlite4Prng, sizeof(sqlite4Prng));
}
void sqlite4PrngRestoreState(void){
  memcpy(&sqlite4Prng, &sqlite4SavedPrng, sizeof(sqlite4Prng));
}
void sqlite4PrngResetState(void){
  sqlite4Prng.isInit = 0;
}
#endif /* SQLITE_OMIT_BUILTIN_TEST */







<
<
<
<
<
<
<
<
<

|

<
<
<
<
<
<
<
<
<
<
<
<

|
<
>
>
>
|

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<





<
<
<
>
|

|

|

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
14
15
16
17
18
19
20









21
22
23












24
25

26
27
28
29
30




















































31
32
33
34
35



36
37
38
39
40
41
42






















**
** Random numbers are used by some of the database backends in order
** to generate random integer keys for tables or random filenames.
*/
#include "sqliteInt.h"











/*
** Get a single 8-bit random value from the PRNG.  The Mutex
** must be held while executing this routine.












*/
static u8 randomByte(sqlite4_env *pEnv){

  pEnv->prngX = (pEnv->prngX>>1) ^ ((-(pEnv->prngX&1)) & 0xd0000001);
  pEnv->prngY = pEnv->prngY*1103515245 + 12345;
  return (u8)((pEnv->prngX ^ pEnv->prngY)&0xff);
}





















































/*
** Return N random bytes.
*/
void sqlite4_randomness(sqlite4_env *pEnv, int N, void *pBuf){
  unsigned char *zBuf = pBuf;



  if( pEnv==0 ) pEnv = &sqlite4DefaultEnv;
  sqlite4_mutex_enter(pEnv->pPrngMutex);
  while( N-- ){
    *(zBuf++) = randomByte(pEnv);
  }
  sqlite4_mutex_leave(pEnv->pPrngMutex);
}






















Changes to src/shell.c.

2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
....
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
....
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
  }else

  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
    static const struct {
       const char *zCtrlName;   /* Name of a test-control option */
       int ctrlCode;            /* Integer code for that option */
    } aCtrl[] = {
      { "prng_save",             SQLITE_TESTCTRL_PRNG_SAVE              },
      { "prng_restore",          SQLITE_TESTCTRL_PRNG_RESTORE           },
      { "prng_reset",            SQLITE_TESTCTRL_PRNG_RESET             },
      { "fault_install",         SQLITE_TESTCTRL_FAULT_INSTALL          },
      { "benign_malloc_hooks",   SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS    },
      { "pending_byte",          SQLITE_TESTCTRL_PENDING_BYTE           },
      { "assert",                SQLITE_TESTCTRL_ASSERT                 },
      { "always",                SQLITE_TESTCTRL_ALWAYS                 },
      { "reserve",               SQLITE_TESTCTRL_RESERVE                },
      { "optimizations",         SQLITE_TESTCTRL_OPTIMIZATIONS          },
      { "iskeyword",             SQLITE_TESTCTRL_ISKEYWORD              },
    };
    int testctrl = -1;
    int rc = 0;
    int i, n;
    open_db(p);
................................................................................
            printf("%d (0x%08x)\n", rc, rc);
          } else {
            fprintf(stderr,"Error: testctrl %s takes a single int option\n",
                    azArg[1]);
          }
          break;

        /* sqlite4_test_control(int) */
        case SQLITE_TESTCTRL_PRNG_SAVE:           
        case SQLITE_TESTCTRL_PRNG_RESTORE:        
        case SQLITE_TESTCTRL_PRNG_RESET:
          if( nArg==2 ){
            rc = sqlite4_test_control(testctrl);
            printf("%d (0x%08x)\n", rc, rc);
          } else {
            fprintf(stderr,"Error: testctrl %s takes no options\n", azArg[1]);
          }
          break;

        /* sqlite4_test_control(int, uint) */
        case SQLITE_TESTCTRL_PENDING_BYTE:        
          if( nArg==3 ){
            unsigned int opt = (unsigned int)atoi(azArg[2]);        
            rc = sqlite4_test_control(testctrl, opt);
            printf("%d (0x%08x)\n", rc, rc);
          } else {
            fprintf(stderr,"Error: testctrl %s takes a single unsigned"
                           " int option\n", azArg[1]);
          }
          break;
          
        /* sqlite4_test_control(int, int) */
        case SQLITE_TESTCTRL_ASSERT:              
        case SQLITE_TESTCTRL_ALWAYS:              
          if( nArg==3 ){
            int opt = atoi(azArg[2]);        
            rc = sqlite4_test_control(testctrl, opt);
            printf("%d (0x%08x)\n", rc, rc);
................................................................................
            fprintf(stderr,"Error: testctrl %s takes a single char * option\n",
                            azArg[1]);
          }
          break;
#endif

        case SQLITE_TESTCTRL_FAULT_INSTALL:       
        case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: 
        default:
          fprintf(stderr,"Error: CLI support for testctrl %s not implemented\n",
                  azArg[1]);
          break;
      }
    }
  }else







<
<
<

<
<


<







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







<







2117
2118
2119
2120
2121
2122
2123



2124


2125
2126

2127
2128
2129
2130
2131
2132
2133
....
2161
2162
2163
2164
2165
2166
2167
























2168
2169
2170
2171
2172
2173
2174
....
2189
2190
2191
2192
2193
2194
2195

2196
2197
2198
2199
2200
2201
2202
  }else

  if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){
    static const struct {
       const char *zCtrlName;   /* Name of a test-control option */
       int ctrlCode;            /* Integer code for that option */
    } aCtrl[] = {



      { "fault_install",         SQLITE_TESTCTRL_FAULT_INSTALL          },


      { "assert",                SQLITE_TESTCTRL_ASSERT                 },
      { "always",                SQLITE_TESTCTRL_ALWAYS                 },

      { "optimizations",         SQLITE_TESTCTRL_OPTIMIZATIONS          },
      { "iskeyword",             SQLITE_TESTCTRL_ISKEYWORD              },
    };
    int testctrl = -1;
    int rc = 0;
    int i, n;
    open_db(p);
................................................................................
            printf("%d (0x%08x)\n", rc, rc);
          } else {
            fprintf(stderr,"Error: testctrl %s takes a single int option\n",
                    azArg[1]);
          }
          break;

























        /* sqlite4_test_control(int, int) */
        case SQLITE_TESTCTRL_ASSERT:              
        case SQLITE_TESTCTRL_ALWAYS:              
          if( nArg==3 ){
            int opt = atoi(azArg[2]);        
            rc = sqlite4_test_control(testctrl, opt);
            printf("%d (0x%08x)\n", rc, rc);
................................................................................
            fprintf(stderr,"Error: testctrl %s takes a single char * option\n",
                            azArg[1]);
          }
          break;
#endif

        case SQLITE_TESTCTRL_FAULT_INSTALL:       

        default:
          fprintf(stderr,"Error: CLI support for testctrl %s not implemented\n",
                  azArg[1]);
          break;
      }
    }
  }else

Changes to src/sqlite.h.in.

119
120
121
122
123
124
125

126
127
128
129
130
131
132
...
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524


525
526
527
528
529
530
531
532
533
534
535
536
537




538
539
540
541
542
543
544
...
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
...
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
...
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
...
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
....
3673
3674
3675
3676
3677
3678
3679



3680
3681
3682
3683
3684
3685
3686
....
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761

3762
3763
3764
3765
3766
3767
3768
....
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
....
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
....
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874

3875
3876
3877
3878
3879
3880
3881
....
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
....
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
....
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
....
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
....
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
....
4509
4510
4511
4512
4513
4514
4515





























































































4516
4517
4518
4519
4520
4521
4522
#define SQLITE_ENVCONFIG_MALLOC        7   /* sqlite4_mem_methods* */
#define SQLITE_ENVCONFIG_GETMALLOC     8   /* sqlite4_mem_methods* */
#define SQLITE_ENVCONFIG_MEMSTATUS     9   /* boolean */
#define SQLITE_ENVCONFIG_LOOKASIDE    10   /* size, count */
#define SQLITE_ENVCONFIG_LOG          11   /* xLog, pArg */
#define SQLITE_ENVCONFIG_KVSTORE_PUSH 12   /* name, factory */
#define SQLITE_ENVCONFIG_KVSTORE_POP  13   /* name */



/*
** CAPIREF: Compile-Time Library Version Numbers
**
** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite4.h header
** evaluates to a string literal that is the SQLite version in the
................................................................................
**
** These bit values are intended for use as options in the
** [sqlite4_open()] interface
*/
#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite4_open() */
#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite4_open() */
#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite4_open() */
#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
#define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
#define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite4_open() */
#define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
#define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
#define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
#define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
#define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
#define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite4_open() */
#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite4_open() */
#define SQLITE_OPEN_WAL              0x00080000  /* VFS only */

/* Reserved:                         0x00F00000 */




/*
** CAPIREF: Mutex Handle
**
** The mutex module within SQLite defines [sqlite4_mutex] to be an
** abstract type for a mutex object.  The SQLite core never looks
** at the internal representation of an [sqlite4_mutex].  It only
** deals with pointers to the [sqlite4_mutex] object.
**
** Mutexes are created using [sqlite4_mutex_alloc()].
*/
typedef struct sqlite4_mutex sqlite4_mutex;





/*
** CAPIREF: Initialize The SQLite Library
**
** ^The sqlite4_initialize(A) routine initializes an sqlite4_env object A.
** ^The sqlite4_shutdown(A) routine
** deallocates any resources that were allocated by sqlite4_initialize(A).
................................................................................
** of SQLite may require this.  In other words, the behavior exhibited
** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
** default behavior in some future release of SQLite.
*/
int sqlite4_initialize(sqlite4_env*);
int sqlite4_shutdown(sqlite4_env*);

/*
** CAPIREF: Configuring The SQLite Library
**
** The sqlite4_config() interface is used to make configuration
** changes to an [sqlite4_env] object that describes the run-time
** environment used by SQLite4.
** The default sqlite4_env is recommended for most
** applications and so this routine is usually not necessary.  It is
** provided to support rare applications with unusual needs.
**
** The sqlite4_config() interface is not threadsafe.  The application
** must insure that no other SQLite interfaces are used with the same
** sqlite4_env object while sqlite4_config() is running.  Furthermore,
** sqlite4_config() may only be invoked prior to library initialization using
** [sqlite4_initialize()] or after shutdown by [sqlite4_shutdown()].
** ^If sqlite4_config() is called after [sqlite4_initialize()] and before
** [sqlite4_shutdown()] then it will return SQLITE_MISUSE.
** Note, however, that ^sqlite4_config() can be called as part of the
** implementation of an application-defined [sqlite4_os_init()].
**
** The first argument to sqlite4_config() is an integer
** [configuration option] that determines
** what property of SQLite is to be configured.  Subsequent arguments
** vary depending on the [configuration option]
** in the first argument.
**
** ^When a configuration option is set, sqlite4_config() returns [SQLITE_OK].
** ^If the option is unknown or SQLite is unable to set the option
** then this routine returns a non-zero [error code].
*/
int sqlite4_config(sqlite4_env *pEnv, int, ...);

/*
** CAPIREF: Configure database connections
**
** The sqlite4_db_config() interface is used to make configuration
** changes to a [database connection].  The interface is similar to
** [sqlite4_config()] except that the changes apply to a single
** [database connection] (specified in the first argument).
**
** The second argument to sqlite4_db_config(D,V,...)  is the
** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code 
** that indicates what aspect of the [database connection] is being configured.
** Subsequent arguments vary depending on the configuration verb.
**
................................................................................
** CAPIREF: Memory Allocation Routines
**
** An instance of this object defines the interface between SQLite
** and low-level memory allocation routines.
**
** This object is used in only one place in the SQLite interface.
** A pointer to an instance of this object is the argument to
** [sqlite4_config()] when the configuration option is
** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
** By creating an instance of this object
** and passing it to [sqlite4_config]([SQLITE_CONFIG_MALLOC])
** during configuration, an application can specify an alternative
** memory allocation subsystem for SQLite to use for all of its
** dynamic memory needs.
**
** Note that SQLite comes with several [built-in memory allocators]
** that are perfectly adequate for the overwhelming majority of applications
** and that this object is only useful to a tiny minority of applications
................................................................................
** or [sqlite4_realloc()] first calls xRoundup.  If xRoundup returns 0, 
** that causes the corresponding memory allocation to fail.
**
** The xInit method initializes the memory allocator.  (For example,
** it might allocate any require mutexes or initialize internal data
** structures.  The xShutdown method is invoked (indirectly) by
** [sqlite4_shutdown()] and should deallocate any resources acquired
** by xInit.  The pAppData pointer is used as the only parameter to
** xInit and xShutdown.
**
** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
** the xInit method, so the xInit method need not be threadsafe.  The
** xShutdown method is only called from [sqlite4_shutdown()] so it does
** not need to be threadsafe either.  For all other methods, SQLite
** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
................................................................................
  void (*xFree)(void*,void*);             /* Free a prior allocation */
  void *(*xRealloc)(void*,void*,int);     /* Resize an allocation */
  sqlite4_size_t (*xSize)(void*,void*);   /* Return the size of an allocation */
  int (*xInit)(void*);                    /* Initialize the memory allocator */
  void (*xShutdown)(void*);               /* Deinitialize the allocator */
  void (*xBeginBenign)(void*);            /* Enter a benign malloc region */
  void (*xEndBenign)(void*);              /* Leave a benign malloc region */
  void *pAppData;                         /* 1st argument to all routines */
};

/*
** CAPIREF: Configuration Options
** KEYWORDS: {configuration option}
**
** These constants are the available integer configuration options that
** can be passed as the first argument to the [sqlite4_config()] interface.
**
** New configuration options may be added in future releases of SQLite.
** Existing configuration options might be discontinued.  Applications
** should check the return code from [sqlite4_config()] to make sure that
** the call worked.  The [sqlite4_config()] interface will return a
** non-zero [error code] if a discontinued or unsupported configuration option
** is invoked.
**
** <dl>
** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
** <dd>There are no arguments to this option.  ^This option sets the
** [threading mode] to Single-thread.  In other words, it disables
** all mutexing and puts SQLite into a mode where it can only be used
** by a single thread.   ^If SQLite is compiled with
** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
** it is not possible to change the [threading mode] from its default
** value of Single-thread and so [sqlite4_config()] will return 
** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
** configuration option.</dd>
**
** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
** <dd>There are no arguments to this option.  ^This option sets the
** [threading mode] to Multi-thread.  In other words, it disables
** mutexing on [database connection] and [prepared statement] objects.
** The application is responsible for serializing access to
** [database connections] and [prepared statements].  But other mutexes
** are enabled so that SQLite will be safe to use in a multi-threaded
** environment as long as no two threads attempt to use the same
** [database connection] at the same time.  ^If SQLite is compiled with
** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
** it is not possible to set the Multi-thread [threading mode] and
** [sqlite4_config()] will return [SQLITE_ERROR] if called with the
** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
**
** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
** <dd>There are no arguments to this option.  ^This option sets the
** [threading mode] to Serialized. In other words, this option enables
** all mutexes including the recursive
** mutexes on [database connection] and [prepared statement] objects.
** In this mode (which is the default when SQLite is compiled with
** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
** to [database connections] and [prepared statements] so that the
** application is free to use the same [database connection] or the
** same [prepared statement] in different threads at the same time.
** ^If SQLite is compiled with
** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
** it is not possible to set the Serialized [threading mode] and
** [sqlite4_config()] will return [SQLITE_ERROR] if called with the
** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
**
** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
** <dd> ^(This option takes a single argument which is a pointer to an
** instance of the [sqlite4_mem_methods] structure.  The argument specifies
** alternative low-level memory allocation routines to be used in place of
** the memory allocation routines built into SQLite.)^ ^SQLite makes
** its own private copy of the content of the [sqlite4_mem_methods] structure
** before the [sqlite4_config()] call returns.</dd>
**
** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
** <dd> ^(This option takes a single argument which is a pointer to an
** instance of the [sqlite4_mem_methods] structure.  The [sqlite4_mem_methods]
** structure is filled with the currently defined memory allocation routines.)^
** This option can be used to overload the default memory allocation
** routines with a wrapper that simulations memory allocation failure or
** tracks memory usage, for example. </dd>
**
** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
** <dd> ^This option takes single argument of type int, interpreted as a 
** boolean, which enables or disables the collection of memory allocation 
** statistics. ^(When memory allocation statistics are disabled, the 
** following SQLite interfaces become non-operational:
**   <ul>
**   <li> [sqlite4_memory_used()]
**   <li> [sqlite4_memory_highwater()]
**   <li> [sqlite4_soft_heap_limit64()]
**   <li> [sqlite4_status()]
**   </ul>)^
** ^Memory allocation statistics are enabled by default unless SQLite is
** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
** allocation statistics are disabled by default.
** </dd>
**
** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
** <dd> ^This option specifies a static memory buffer that SQLite will use
** for all of its dynamic memory allocation needs beyond those provided
** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
** There are three arguments: An 8-byte aligned pointer to the memory,
** the number of bytes in the memory buffer, and the minimum allocation size.
** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
** to using its default memory allocator (the system malloc() implementation),
** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
** allocator is engaged to handle all of SQLites memory allocation needs.
** The first pointer (the memory pointer) must be aligned to an 8-byte
** boundary or subsequent behavior of SQLite will be undefined.
** The minimum allocation size is capped at 2**12. Reasonable values
** for the minimum allocation size are 2**5 through 2**8.</dd>
**
** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
** <dd> ^(This option takes a single argument which is a pointer to an
** instance of the [sqlite4_mutex_methods] structure.  The argument specifies
** alternative low-level mutex routines to be used in place
** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
** content of the [sqlite4_mutex_methods] structure before the call to
** [sqlite4_config()] returns. ^If SQLite is compiled with
** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
** the entire mutexing subsystem is omitted from the build and hence calls to
** [sqlite4_config()] with the SQLITE_CONFIG_MUTEX configuration option will
** return [SQLITE_ERROR].</dd>
**
** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
** <dd> ^(This option takes a single argument which is a pointer to an
** instance of the [sqlite4_mutex_methods] structure.  The
** [sqlite4_mutex_methods]
** structure is filled with the currently defined mutex routines.)^
** This option can be used to overload the default mutex allocation
** routines with a wrapper used to track mutex usage for performance
** profiling or testing, for example.   ^If SQLite is compiled with
** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
** the entire mutexing subsystem is omitted from the build and hence calls to
** [sqlite4_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
** return [SQLITE_ERROR].</dd>
**
** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
** <dd> ^(This option takes two arguments that determine the default
** memory allocation for the lookaside memory allocator on each
** [database connection].  The first argument is the
** size of each lookaside buffer slot and the second is the number of
** slots allocated to each database connection.)^  ^(This option sets the
** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
** verb to [sqlite4_db_config()] can be used to change the lookaside
** configuration on individual connections.)^ </dd>
**
** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
** function with a call signature of void(*)(void*,int,const char*), 
** and a pointer to void. ^If the function pointer is not NULL, it is
** invoked by [sqlite4_log()] to process each logging event.  ^If the
** function pointer is NULL, the [sqlite4_log()] interface becomes a no-op.
** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
** passed through as the first parameter to the application-defined logger
** function whenever that function is invoked.  ^The second parameter to
** the logger function is a copy of the first parameter to the corresponding
** [sqlite4_log()] call and is intended to be a [result code] or an
** [extended result code].  ^The third parameter passed to the logger is
** log message after formatting via [sqlite4_snprintf()].
** The SQLite logging interface is not reentrant; the logger function
** supplied by the application must not invoke any SQLite interface.
** In a multi-threaded application, the application-defined logger
** function must be threadsafe. </dd>
**
** </dl>
*/
#define SQLITE_CONFIG_SET_KVFACTORY 20 /* int(*)(KVStore**,const char*,u32) */
#define SQLITE_CONFIG_GET_KVFACTORY 21 /* int(**)(KVStore**,const char*,u32) */

/*
** CAPIREF: Database Connection Configuration Options
**
** These constants are the available integer configuration options that
** can be passed as the second argument to the [sqlite4_db_config()] interface.
**
................................................................................
** of the new function always causes an exception to be thrown.  So
** the new function is not good for anything by itself.  Its only
** purpose is to be a placeholder function that can be overloaded
** by a [virtual table].
*/
int sqlite4_overload_function(sqlite4*, const char *zFuncName, int nArg);




/*
** CAPIREF: Mutexes
**
** The SQLite core uses these routines for thread
** synchronization. Though they are intended for internal
** use by SQLite, code that links against SQLite is
** permitted to use any of these routines.
................................................................................
** and SQLITE_MUTEX_W32 implementations
** are appropriate for use on Unix and Windows.
**
** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
** implementation is included with the library. In this case the
** application must supply a custom mutex implementation using the
** [SQLITE_CONFIG_MUTEX] option of the sqlite4_config() function
** before calling sqlite4_initialize() or any other public sqlite4_
** function that calls sqlite4_initialize().)^
**
** ^The sqlite4_mutex_alloc() routine allocates a new
** mutex and returns a pointer to it. ^If it returns NULL
** that means that a mutex could not be allocated.  ^SQLite
** will unwind its stack and return an error.  ^(The argument
** to sqlite4_mutex_alloc() is one of these integer constants:
**
** <ul>
** <li>  SQLITE_MUTEX_FAST
** <li>  SQLITE_MUTEX_RECURSIVE
** <li>  SQLITE_MUTEX_STATIC_MASTER
** <li>  SQLITE_MUTEX_STATIC_MEM
** <li>  SQLITE_MUTEX_STATIC_MEM2
** <li>  SQLITE_MUTEX_STATIC_PRNG
** <li>  SQLITE_MUTEX_STATIC_LRU
** <li>  SQLITE_MUTEX_STATIC_LRU2
** </ul>)^
**
** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
** cause sqlite4_mutex_alloc() to create
** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
** The mutex implementation does not need to make a distinction
** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
** not want to.  ^SQLite will only request a recursive mutex in
** cases where it really needs one.  ^If a faster non-recursive mutex
** implementation is available on the host platform, the mutex subsystem
** might return such a mutex in response to SQLITE_MUTEX_FAST.
**
** ^The other allowed parameters to sqlite4_mutex_alloc() (anything other
** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
** a pointer to a static preexisting mutex.  ^Six static mutexes are
** used by the current version of SQLite.  Future versions of SQLite
** may add additional static mutexes.  Static mutexes are for internal
** use by SQLite only.  Applications that use SQLite mutexes should
** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
** SQLITE_MUTEX_RECURSIVE.
**
** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
** or SQLITE_MUTEX_RECURSIVE) is used then sqlite4_mutex_alloc()
** returns a different mutex on every call.  ^But for the static
** mutex types, the same mutex is returned on every call that has
** the same type number.
**
** ^The sqlite4_mutex_free() routine deallocates a previously
** allocated dynamic mutex.  ^SQLite is careful to deallocate every
** dynamic mutex that it allocates.  The dynamic mutexes must not be in
** use when they are deallocated.  Attempting to deallocate a static
** mutex results in undefined behavior.  ^SQLite never deallocates
** a static mutex.

**
** ^The sqlite4_mutex_enter() and sqlite4_mutex_try() routines attempt
** to enter a mutex.  ^If another thread is already within the mutex,
** sqlite4_mutex_enter() will block and sqlite4_mutex_try() will return
** SQLITE_BUSY.  ^The sqlite4_mutex_try() interface returns [SQLITE_OK]
** upon successful entry.  ^(Mutexes created using
** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
................................................................................
**
** ^If the argument to sqlite4_mutex_enter(), sqlite4_mutex_try(), or
** sqlite4_mutex_leave() is a NULL pointer, then all three routines
** behave as no-ops.
**
** See also: [sqlite4_mutex_held()] and [sqlite4_mutex_notheld()].
*/
sqlite4_mutex *sqlite4_mutex_alloc(int);
void sqlite4_mutex_free(sqlite4_mutex*);
void sqlite4_mutex_enter(sqlite4_mutex*);
int sqlite4_mutex_try(sqlite4_mutex*);
void sqlite4_mutex_leave(sqlite4_mutex*);

/*
** CAPIREF: Mutex Methods Object
................................................................................
** used to allocate and use mutexes.
**
** Usually, the default mutex implementations provided by SQLite are
** sufficient, however the user has the option of substituting a custom
** implementation for specialized deployments or systems for which SQLite
** does not provide a suitable implementation. In this case, the user
** creates and populates an instance of this structure to pass
** to sqlite4_config() along with the [SQLITE_CONFIG_MUTEX] option.
** Additionally, an instance of this structure can be used as an
** output variable when querying the system for the current mutex
** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
**
** ^The xMutexInit method defined by this structure is invoked as
** part of system initialization by the sqlite4_initialize() function.
** ^The xMutexInit routine is called by SQLite exactly once for each
................................................................................
** ^SQLite will invoke the xMutexEnd() method when [sqlite4_shutdown()] is
** called, but only if the prior call to xMutexInit returned SQLITE_OK.
** If xMutexInit fails in any way, it is expected to clean up after itself
** prior to returning.
*/
typedef struct sqlite4_mutex_methods sqlite4_mutex_methods;
struct sqlite4_mutex_methods {
  int (*xMutexInit)(void);
  int (*xMutexEnd)(void);
  sqlite4_mutex *(*xMutexAlloc)(int);
  void (*xMutexFree)(sqlite4_mutex *);
  void (*xMutexEnter)(sqlite4_mutex *);
  int (*xMutexTry)(sqlite4_mutex *);
  void (*xMutexLeave)(sqlite4_mutex *);
  int (*xMutexHeld)(sqlite4_mutex *);
  int (*xMutexNotheld)(sqlite4_mutex *);

};

/*
** CAPIREF: Mutex Verification Routines
**
** The sqlite4_mutex_held() and sqlite4_mutex_notheld() routines
** are intended for use inside assert() statements.  ^The SQLite core
................................................................................
**
** The set of static mutexes may change from one SQLite release to the
** next.  Applications that override the built-in mutex logic must be
** prepared to accommodate additional static mutexes.
*/
#define SQLITE_MUTEX_FAST             0
#define SQLITE_MUTEX_RECURSIVE        1
#define SQLITE_MUTEX_STATIC_MASTER    2
#define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite4_malloc() */
#define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
#define SQLITE_MUTEX_STATIC_OPEN      4  /* NOT USED */
#define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite4_random() */
#define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
#define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
#define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite4PageMalloc() */

/*
** CAPIREF: Retrieve the mutex for a database connection
**
** ^This interface returns a pointer the [sqlite4_mutex] object that 
** serializes access to the [database connection] given in the argument
** when the [threading mode] is Serialized.
................................................................................
** database identified by the second argument. ^The name of the database 
** is "main" for the main database or "temp" for the TEMP database, or the 
** name that appears after the AS keyword for databases that were added 
** using the [ATTACH] SQL command. ^A NULL pointer can be used in place 
** of "main" to refer to the main database file.
**
** ^The third and fourth parameters to this routine are passed directly 
** through to the second and third parameters of the KVStoreMethods.xControl 
** method. ^The return value of the xControl call becomes the return value 
** of this routine.
**
** ^If the second parameter (zDbName) does not match the name of any
** open database file, then SQLITE_ERROR is returned.  ^This error
** code is not remembered and will not be recalled by [sqlite4_errcode()]
** or [sqlite4_errmsg()]. The underlying xControl method might also return 
** SQLITE_ERROR. There is no way to distinguish between an incorrect zDbName 
** and an SQLITE_ERROR return from the underlying xControl method.
................................................................................
** as the first argument to [sqlite4_test_control()].
**
** These parameters and their meanings are subject to change
** without notice.  These values are for testing purposes only.
** Applications should not use any of these parameters or the
** [sqlite4_test_control()] interface.
*/
#define SQLITE_TESTCTRL_FIRST                    5
#define SQLITE_TESTCTRL_PRNG_SAVE                5
#define SQLITE_TESTCTRL_PRNG_RESTORE             6
#define SQLITE_TESTCTRL_PRNG_RESET               7
#define SQLITE_TESTCTRL_FAULT_INSTALL            9
#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
#define SQLITE_TESTCTRL_PENDING_BYTE            11
#define SQLITE_TESTCTRL_ASSERT                  12
#define SQLITE_TESTCTRL_ALWAYS                  13
#define SQLITE_TESTCTRL_RESERVE                 14
#define SQLITE_TESTCTRL_OPTIMIZATIONS           15
#define SQLITE_TESTCTRL_ISKEYWORD               16
#define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
#define SQLITE_TESTCTRL_EXPLAIN_STMT            19
#define SQLITE_TESTCTRL_LAST                    19

/*
** CAPIREF: SQLite Runtime Status
**
** ^This interface is used to retrieve runtime status information
** about the performance of SQLite, and optionally to reset various
** highwater marks.  ^The first argument is an integer code for
................................................................................
*/
int sqlite4_strnicmp(const char *, const char *, int);

/*
** CAPIREF: Error Logging Interface
**
** ^The [sqlite4_log()] interface writes a message into the error log
** established by the [SQLITE_CONFIG_LOG] option to [sqlite4_config()].
** ^If logging is enabled, the zFormat string and subsequent arguments are
** used with [sqlite4_snprintf()] to generate the final output string.
**
** The sqlite4_log() interface is intended for use by extensions such as
** virtual tables, collating functions, and SQL functions.  While there is
** nothing to prevent an application from calling sqlite4_log(), doing so
** is considered bad form.
................................................................................
**
** To avoid deadlocks and other threading problems, the sqlite4_log() routine
** will not use dynamically allocated memory.  The log message is stored in
** a fixed-length buffer on the stack.  If the log message is longer than
** a few hundred characters, it will be truncated to the length of the
** buffer.
*/
void sqlite4_log(int iErrCode, const char *zFormat, ...);

/*
** CAPIREF: Virtual Table Interface Configuration
**
** This function may be called by either the [xConnect] or [xCreate] method
** of a [virtual table] implementation to configure
** various facets of the virtual table interface.
................................................................................
** [SQLITE_ABORT] is also a [result code].
*/
#define SQLITE_ROLLBACK 1
/* #define SQLITE_IGNORE 2 // Also used by sqlite4_authorizer() callback */
#define SQLITE_FAIL     3
/* #define SQLITE_ABORT 4  // Also an error code */
#define SQLITE_REPLACE  5






























































































/*
** CAPI4REF: Representation Of Numbers
**
** Every number in SQLite is represented in memory by an instance of
** the following object.
*/







>







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<

<
>
>













>
>
>
>







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<





|







 







|
|

|







 







|







 







|


<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







>
>
>







 







|












<
<
<
<
<
<


<
<
|








<
<
<
<
<
<
<
<
<
<
<
<
<
<
<

<
<
<
<
<
>







 







|







 







|







 







|
|
|






>







 







<
<
<
<
<
<
<
<







 







|
|
|







 







|
<
<
<
|
<
<
|
|
|
|
|
|
|
|







 







|







 







|







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
...
503
504
505
506
507
508
509














510

511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
...
572
573
574
575
576
577
578
































579
580
581
582
583
584
585
586
587
588
589
590
591
...
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
...
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
...
671
672
673
674
675
676
677
678
679
680


































































































































































681
682
683
684
685
686
687
....
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
....
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522






3523
3524


3525
3526
3527
3528
3529
3530
3531
3532
3533















3534





3535
3536
3537
3538
3539
3540
3541
3542
....
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
....
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
....
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
....
3691
3692
3693
3694
3695
3696
3697








3698
3699
3700
3701
3702
3703
3704
....
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
....
3775
3776
3777
3778
3779
3780
3781
3782



3783


3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
....
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
....
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
....
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
#define SQLITE_ENVCONFIG_MALLOC        7   /* sqlite4_mem_methods* */
#define SQLITE_ENVCONFIG_GETMALLOC     8   /* sqlite4_mem_methods* */
#define SQLITE_ENVCONFIG_MEMSTATUS     9   /* boolean */
#define SQLITE_ENVCONFIG_LOOKASIDE    10   /* size, count */
#define SQLITE_ENVCONFIG_LOG          11   /* xLog, pArg */
#define SQLITE_ENVCONFIG_KVSTORE_PUSH 12   /* name, factory */
#define SQLITE_ENVCONFIG_KVSTORE_POP  13   /* name */
#define SQLITE_ENVCONFIG_KVSTORE_GET  14   /* name, *factor */


/*
** CAPIREF: Compile-Time Library Version Numbers
**
** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite4.h header
** evaluates to a string literal that is the SQLite version in the
................................................................................
**
** These bit values are intended for use as options in the
** [sqlite4_open()] interface
*/
#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite4_open() */
#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite4_open() */
#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite4_open() */
















/* NB:  The above must not overlap with the SQLITE_KVOPEN_xxxxx flags
** defined below */


/*
** CAPIREF: Mutex Handle
**
** The mutex module within SQLite defines [sqlite4_mutex] to be an
** abstract type for a mutex object.  The SQLite core never looks
** at the internal representation of an [sqlite4_mutex].  It only
** deals with pointers to the [sqlite4_mutex] object.
**
** Mutexes are created using [sqlite4_mutex_alloc()].
*/
typedef struct sqlite4_mutex sqlite4_mutex;
struct sqlite4_mutex {
  struct sqlite4_mutex_methods *pMutexMethods;
  /* Subclasses will typically add additional fields */
};

/*
** CAPIREF: Initialize The SQLite Library
**
** ^The sqlite4_initialize(A) routine initializes an sqlite4_env object A.
** ^The sqlite4_shutdown(A) routine
** deallocates any resources that were allocated by sqlite4_initialize(A).
................................................................................
** of SQLite may require this.  In other words, the behavior exhibited
** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
** default behavior in some future release of SQLite.
*/
int sqlite4_initialize(sqlite4_env*);
int sqlite4_shutdown(sqlite4_env*);

































/*
** CAPIREF: Configure database connections
**
** The sqlite4_db_config() interface is used to make configuration
** changes to a [database connection].  The interface is similar to
** [sqlite4_env_config()] except that the changes apply to a single
** [database connection] (specified in the first argument).
**
** The second argument to sqlite4_db_config(D,V,...)  is the
** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code 
** that indicates what aspect of the [database connection] is being configured.
** Subsequent arguments vary depending on the configuration verb.
**
................................................................................
** CAPIREF: Memory Allocation Routines
**
** An instance of this object defines the interface between SQLite
** and low-level memory allocation routines.
**
** This object is used in only one place in the SQLite interface.
** A pointer to an instance of this object is the argument to
** [sqlite4_env_config()] when the configuration option is
** [SQLITE_ENVCONFIG_MALLOC] or [SQLITE_ENVCONFIG_GETMALLOC].  
** By creating an instance of this object
** and passing it to [sqlite4_env_config]([SQLITE_ENVCONFIG_MALLOC])
** during configuration, an application can specify an alternative
** memory allocation subsystem for SQLite to use for all of its
** dynamic memory needs.
**
** Note that SQLite comes with several [built-in memory allocators]
** that are perfectly adequate for the overwhelming majority of applications
** and that this object is only useful to a tiny minority of applications
................................................................................
** or [sqlite4_realloc()] first calls xRoundup.  If xRoundup returns 0, 
** that causes the corresponding memory allocation to fail.
**
** The xInit method initializes the memory allocator.  (For example,
** it might allocate any require mutexes or initialize internal data
** structures.  The xShutdown method is invoked (indirectly) by
** [sqlite4_shutdown()] and should deallocate any resources acquired
** by xInit.  The pMemEnv pointer is used as the only parameter to
** xInit and xShutdown.
**
** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
** the xInit method, so the xInit method need not be threadsafe.  The
** xShutdown method is only called from [sqlite4_shutdown()] so it does
** not need to be threadsafe either.  For all other methods, SQLite
** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
................................................................................
  void (*xFree)(void*,void*);             /* Free a prior allocation */
  void *(*xRealloc)(void*,void*,int);     /* Resize an allocation */
  sqlite4_size_t (*xSize)(void*,void*);   /* Return the size of an allocation */
  int (*xInit)(void*);                    /* Initialize the memory allocator */
  void (*xShutdown)(void*);               /* Deinitialize the allocator */
  void (*xBeginBenign)(void*);            /* Enter a benign malloc region */
  void (*xEndBenign)(void*);              /* Leave a benign malloc region */
  void *pMemEnv;                         /* 1st argument to all routines */
};




































































































































































/*
** CAPIREF: Database Connection Configuration Options
**
** These constants are the available integer configuration options that
** can be passed as the second argument to the [sqlite4_db_config()] interface.
**
................................................................................
** of the new function always causes an exception to be thrown.  So
** the new function is not good for anything by itself.  Its only
** purpose is to be a placeholder function that can be overloaded
** by a [virtual table].
*/
int sqlite4_overload_function(sqlite4*, const char *zFuncName, int nArg);

/*
** 

/*
** CAPIREF: Mutexes
**
** The SQLite core uses these routines for thread
** synchronization. Though they are intended for internal
** use by SQLite, code that links against SQLite is
** permitted to use any of these routines.
................................................................................
** and SQLITE_MUTEX_W32 implementations
** are appropriate for use on Unix and Windows.
**
** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
** implementation is included with the library. In this case the
** application must supply a custom mutex implementation using the
** [SQLITE_CONFIG_MUTEX] option of the sqlite4_env_config() function
** before calling sqlite4_initialize() or any other public sqlite4_
** function that calls sqlite4_initialize().)^
**
** ^The sqlite4_mutex_alloc() routine allocates a new
** mutex and returns a pointer to it. ^If it returns NULL
** that means that a mutex could not be allocated.  ^SQLite
** will unwind its stack and return an error.  ^(The argument
** to sqlite4_mutex_alloc() is one of these integer constants:
**
** <ul>
** <li>  SQLITE_MUTEX_FAST
** <li>  SQLITE_MUTEX_RECURSIVE






** </ul>)^
**


** ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
** The mutex implementation does not need to make a distinction
** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
** not want to.  ^SQLite will only request a recursive mutex in
** cases where it really needs one.  ^If a faster non-recursive mutex
** implementation is available on the host platform, the mutex subsystem
** might return such a mutex in response to SQLITE_MUTEX_FAST.
**















** ^The sqlite4_mutex_free() routine deallocates a previously





** allocated mutex. 
**
** ^The sqlite4_mutex_enter() and sqlite4_mutex_try() routines attempt
** to enter a mutex.  ^If another thread is already within the mutex,
** sqlite4_mutex_enter() will block and sqlite4_mutex_try() will return
** SQLITE_BUSY.  ^The sqlite4_mutex_try() interface returns [SQLITE_OK]
** upon successful entry.  ^(Mutexes created using
** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
................................................................................
**
** ^If the argument to sqlite4_mutex_enter(), sqlite4_mutex_try(), or
** sqlite4_mutex_leave() is a NULL pointer, then all three routines
** behave as no-ops.
**
** See also: [sqlite4_mutex_held()] and [sqlite4_mutex_notheld()].
*/
sqlite4_mutex *sqlite4_mutex_alloc(sqlite4_env*, int);
void sqlite4_mutex_free(sqlite4_mutex*);
void sqlite4_mutex_enter(sqlite4_mutex*);
int sqlite4_mutex_try(sqlite4_mutex*);
void sqlite4_mutex_leave(sqlite4_mutex*);

/*
** CAPIREF: Mutex Methods Object
................................................................................
** used to allocate and use mutexes.
**
** Usually, the default mutex implementations provided by SQLite are
** sufficient, however the user has the option of substituting a custom
** implementation for specialized deployments or systems for which SQLite
** does not provide a suitable implementation. In this case, the user
** creates and populates an instance of this structure to pass
** to sqlite4_env_config() along with the [SQLITE_CONFIG_MUTEX] option.
** Additionally, an instance of this structure can be used as an
** output variable when querying the system for the current mutex
** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
**
** ^The xMutexInit method defined by this structure is invoked as
** part of system initialization by the sqlite4_initialize() function.
** ^The xMutexInit routine is called by SQLite exactly once for each
................................................................................
** ^SQLite will invoke the xMutexEnd() method when [sqlite4_shutdown()] is
** called, but only if the prior call to xMutexInit returned SQLITE_OK.
** If xMutexInit fails in any way, it is expected to clean up after itself
** prior to returning.
*/
typedef struct sqlite4_mutex_methods sqlite4_mutex_methods;
struct sqlite4_mutex_methods {
  int (*xMutexInit)(void*);
  int (*xMutexEnd)(void*);
  sqlite4_mutex *(*xMutexAlloc)(void*,int);
  void (*xMutexFree)(sqlite4_mutex *);
  void (*xMutexEnter)(sqlite4_mutex *);
  int (*xMutexTry)(sqlite4_mutex *);
  void (*xMutexLeave)(sqlite4_mutex *);
  int (*xMutexHeld)(sqlite4_mutex *);
  int (*xMutexNotheld)(sqlite4_mutex *);
  void *pMutexEnv;
};

/*
** CAPIREF: Mutex Verification Routines
**
** The sqlite4_mutex_held() and sqlite4_mutex_notheld() routines
** are intended for use inside assert() statements.  ^The SQLite core
................................................................................
**
** The set of static mutexes may change from one SQLite release to the
** next.  Applications that override the built-in mutex logic must be
** prepared to accommodate additional static mutexes.
*/
#define SQLITE_MUTEX_FAST             0
#define SQLITE_MUTEX_RECURSIVE        1









/*
** CAPIREF: Retrieve the mutex for a database connection
**
** ^This interface returns a pointer the [sqlite4_mutex] object that 
** serializes access to the [database connection] given in the argument
** when the [threading mode] is Serialized.
................................................................................
** database identified by the second argument. ^The name of the database 
** is "main" for the main database or "temp" for the TEMP database, or the 
** name that appears after the AS keyword for databases that were added 
** using the [ATTACH] SQL command. ^A NULL pointer can be used in place 
** of "main" to refer to the main database file.
**
** ^The third and fourth parameters to this routine are passed directly 
** through to the second and third parameters of the
** sqlite4_kv_methods.xControl method. ^The return value of the xControl
** call becomes the return value of this routine.
**
** ^If the second parameter (zDbName) does not match the name of any
** open database file, then SQLITE_ERROR is returned.  ^This error
** code is not remembered and will not be recalled by [sqlite4_errcode()]
** or [sqlite4_errmsg()]. The underlying xControl method might also return 
** SQLITE_ERROR. There is no way to distinguish between an incorrect zDbName 
** and an SQLITE_ERROR return from the underlying xControl method.
................................................................................
** as the first argument to [sqlite4_test_control()].
**
** These parameters and their meanings are subject to change
** without notice.  These values are for testing purposes only.
** Applications should not use any of these parameters or the
** [sqlite4_test_control()] interface.
*/
#define SQLITE_TESTCTRL_FIRST                    1



#define SQLITE_TESTCTRL_FAULT_INSTALL            2


#define SQLITE_TESTCTRL_ASSERT                   3
#define SQLITE_TESTCTRL_ALWAYS                   4
#define SQLITE_TESTCTRL_RESERVE                  5
#define SQLITE_TESTCTRL_OPTIMIZATIONS            6
#define SQLITE_TESTCTRL_ISKEYWORD                7
#define SQLITE_TESTCTRL_LOCALTIME_FAULT          8
#define SQLITE_TESTCTRL_EXPLAIN_STMT             9
#define SQLITE_TESTCTRL_LAST                     9

/*
** CAPIREF: SQLite Runtime Status
**
** ^This interface is used to retrieve runtime status information
** about the performance of SQLite, and optionally to reset various
** highwater marks.  ^The first argument is an integer code for
................................................................................
*/
int sqlite4_strnicmp(const char *, const char *, int);

/*
** CAPIREF: Error Logging Interface
**
** ^The [sqlite4_log()] interface writes a message into the error log
** established by the [SQLITE_CONFIG_LOG] option to [sqlite4_env_config()].
** ^If logging is enabled, the zFormat string and subsequent arguments are
** used with [sqlite4_snprintf()] to generate the final output string.
**
** The sqlite4_log() interface is intended for use by extensions such as
** virtual tables, collating functions, and SQL functions.  While there is
** nothing to prevent an application from calling sqlite4_log(), doing so
** is considered bad form.
................................................................................
**
** To avoid deadlocks and other threading problems, the sqlite4_log() routine
** will not use dynamically allocated memory.  The log message is stored in
** a fixed-length buffer on the stack.  If the log message is longer than
** a few hundred characters, it will be truncated to the length of the
** buffer.
*/
void sqlite4_log(sqlite4_env*, int iErrCode, const char *zFormat, ...);

/*
** CAPIREF: Virtual Table Interface Configuration
**
** This function may be called by either the [xConnect] or [xCreate] method
** of a [virtual table] implementation to configure
** various facets of the virtual table interface.
................................................................................
** [SQLITE_ABORT] is also a [result code].
*/
#define SQLITE_ROLLBACK 1
/* #define SQLITE_IGNORE 2 // Also used by sqlite4_authorizer() callback */
#define SQLITE_FAIL     3
/* #define SQLITE_ABORT 4  // Also an error code */
#define SQLITE_REPLACE  5


/*
** CAPI4REF:  Length of a key-value storage key or data field
**
** The length of the key or data for a key-value storage entry is
** stored in a variable of this type.
*/
typedef int sqlite4_kvsize;

/*
** CAPI4REF: Key-Value Storage Engine Object
**
** An instance of a subclass of the following object defines a
** connection to a storage engine.
*/
typedef struct sqlite4_kvstore sqlite4_kvstore;
struct sqlite4_kvstore {
  const struct sqlite4_kv_methods *pStoreVfunc;  /* Methods */
  sqlite4_env *pEnv;                      /* Runtime environment for kvstore */
  int iTransLevel;                        /* Current transaction level */
  unsigned kvId;                          /* Unique ID used for tracing */
  unsigned fTrace;                        /* True to enable tracing */
  char zKVName[12];                       /* Used for debugging */
  /* Subclasses will typically append additional fields */
};

/*
** CAPI4REF:  Key-Value Storage Engine Cursor Object
**
** An instance of a subclass of the following object defines a cursor
** used to scan through a key-value storage engine.
*/
typedef struct sqlite4_kvcursor sqlite4_kvcursor;
struct sqlite4_kvcursor {
  sqlite4_kvstore *pStore;                /* The owner of this cursor */
  const struct sqlite4_kv_methods *pStoreVfunc;  /* Methods */
  sqlite4_env *pEnv;                      /* Runtime environment  */
  int iTransLevel;                        /* Current transaction level */
  unsigned curId;                         /* Unique ID for tracing */
  unsigned fTrace;                        /* True to enable tracing */
  /* Subclasses will typically add additional fields */
};

/*
** CAPI4REF: Key-value storage engine virtual method table
**
** A Key-Value storage engine is defined by an instance of the following
** object.
*/
struct sqlite4_kv_methods {
  int iVersion;
  int szSelf;
  int (*xReplace)(
         sqlite4_kvstore*,
         const unsigned char *pKey, sqlite4_kvsize nKey,
         const unsigned char *pData, sqlite4_kvsize nData);
  int (*xOpenCursor)(sqlite4_kvstore*, sqlite4_kvcursor**);
  int (*xSeek)(sqlite4_kvcursor*,
               const unsigned char *pKey, sqlite4_kvsize nKey, int dir);
  int (*xNext)(sqlite4_kvcursor*);
  int (*xPrev)(sqlite4_kvcursor*);
  int (*xDelete)(sqlite4_kvcursor*);
  int (*xKey)(sqlite4_kvcursor*,
              const unsigned char **ppKey, sqlite4_kvsize *pnKey);
  int (*xData)(sqlite4_kvcursor*, sqlite4_kvsize ofst, sqlite4_kvsize n,
               const unsigned char **ppData, sqlite4_kvsize *pnData);
  int (*xReset)(sqlite4_kvcursor*);
  int (*xCloseCursor)(sqlite4_kvcursor*);
  int (*xBegin)(sqlite4_kvstore*, int);
  int (*xCommitPhaseOne)(sqlite4_kvstore*, int);
  int (*xCommitPhaseTwo)(sqlite4_kvstore*, int);
  int (*xRollback)(sqlite4_kvstore*, int);
  int (*xRevert)(sqlite4_kvstore*, int);
  int (*xClose)(sqlite4_kvstore*);
  int (*xControl)(sqlite4_kvstore*, int, void*);
};
typedef struct sqlite4_kv_methods sqlite4_kv_methods;

/*
** CAPI4REF: Key-value storage engine open flags
**
** Allowed values to the flags parameter of an sqlite4_kvstore object
** factory.
**
** The flags parameter to the sqlite4_kvstore factory (the fourth parameter)
** is an OR-ed combination of these values and the
** [SQLITE_OPEN_READONLY | SQLITE_OPEN_xxxxx] flags that appear as 
** arguments to [sqlite4_open()].
*/
#define SQLITE_KVOPEN_TEMPORARY       0x00010000  /* A temporary database */
#define SQLITE_KVOPEN_NO_TRANSACTIONS 0x00020000  /* No transactions needed */


/*
** CAPI4REF: Representation Of Numbers
**
** Every number in SQLite is represented in memory by an instance of
** the following object.
*/

Changes to src/sqliteInt.h.

556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
...
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
...
648
649
650
651
652
653
654


































655
656
657
658
659
660
661
...
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
...
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
...
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
....
2384
2385
2386
2387
2388
2389
2390










2391
2392
2393
2394
2395
2396
2397
....
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423

2424
2425

2426
2427
2428
2429
2430
2431
2432
....
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
....
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
....
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
....
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213

/*
** A convenience macro that returns the number of elements in
** an array.
*/
#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))

/*
** Mark instances of static data that needs to be folded into the
** environment structure.
*/
#define SQLITE_WSD 

/*
** The following macros are used to suppress compiler warnings and to
** make it clear to human readers when a function parameter is deliberately 
** left unused within the body of a function. This usually happens when
** a function is called via a function pointer. For example the 
** implementation of an SQL aggregate step callback may not use the
** parameter indicating the number of arguments passed to the aggregate,
................................................................................
typedef struct Schema Schema;
typedef struct Expr Expr;
typedef struct ExprList ExprList;
typedef struct ExprSpan ExprSpan;
typedef struct FKey FKey;
typedef struct FuncDestructor FuncDestructor;
typedef struct FuncDef FuncDef;
typedef struct FuncDefHash FuncDefHash;
typedef struct IdList IdList;
typedef struct Index Index;
typedef struct IndexSample IndexSample;
typedef struct KeyClass KeyClass;
typedef struct KeyInfo KeyInfo;
typedef struct Lookaside Lookaside;
typedef struct LookasideSlot LookasideSlot;
................................................................................
struct Db {
  char *zName;         /* Name of this database */
  KVStore *pKV;        /* KV store for the database file */
  u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
  u8 chngFlag;         /* True if modified */
  Schema *pSchema;     /* Pointer to database schema (possibly shared) */
};



































/*
** An instance of the following structure stores a database schema.
**
** Most Schema objects are associated with a database file.  The exception is
** the Schema for the TEMP databaes (sqlite4.aDb[1]) which is free-standing.
** 
................................................................................
  void *pStart;           /* First byte of available memory space */
  void *pEnd;             /* First byte past end of available space */
};
struct LookasideSlot {
  LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
};

/*
** A hash table for function definitions.
**
** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
** Collisions are on the FuncDef.pHash chain.
*/
struct FuncDefHash {
  FuncDef *a[23];       /* Hash table for functions */
};

/*
** Each database connection is an instance of the following structure.
**
** The sqlite.lastRowid records the last insert rowid generated by an
** insert statement.  Inserts on views do not affect its value.  Each
** trigger has its own context, so that lastRowid can be updated inside
** triggers as usual.  The previous value will be restored once the trigger
................................................................................
#ifndef SQLITE_OMIT_VIRTUALTABLE
  Hash aModule;                 /* populated by sqlite4_create_module() */
  VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
  VTable **aVTrans;             /* Virtual tables with open transactions */
  int nVTrans;                  /* Allocated size of aVTrans */
  VTable *pDisconnect;    /* Disconnect these in next sqlite4_prepare() */
#endif
  FuncDefHash aFunc;            /* Hash table of connection functions */
  Hash aCollSeq;                /* All collating sequences */
  Db aDbStatic[2];              /* Static space for the 2 default backends */
  Savepoint *pSavepoint;        /* List of active savepoints */
  int nSavepoint;               /* Number of open savepoints */
  int nStatement;               /* Number of nested statement-transactions  */
  i64 nDeferredCons;            /* Net deferred constraints this transaction. */
  int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
................................................................................
*/
#define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
#define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
#define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
#define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
#define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */

/*
** Each SQL function is defined by an instance of the following
** structure.  A pointer to this structure is stored in the sqlite.aFunc
** hash table.  When multiple functions have the same name, the hash table
** points to a linked list of these structures.
*/
struct FuncDef {
  i16 nArg;            /* Number of arguments.  -1 means unlimited */
  u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
  u8 flags;            /* Some combination of SQLITE_FUNC_* */
  void *pUserData;     /* User data parameter */
  FuncDef *pNext;      /* Next function with same name */
  void (*xFunc)(sqlite4_context*,int,sqlite4_value**); /* Regular function */
  void (*xStep)(sqlite4_context*,int,sqlite4_value**); /* Aggregate step */
  void (*xFinalize)(sqlite4_context*);                /* Aggregate finalizer */
  char *zName;         /* SQL name of the function. */
  FuncDef *pHash;      /* Next with a different name but the same hash */
  FuncDestructor *pDestructor;   /* Reference counted destructor function */
};

/*
** This structure encapsulates a user-function destructor callback (as
** configured using create_function_v2()) and a reference counter. When
** create_function_v2() is called to create a function with a destructor,
** a single object of this type is allocated. FuncDestructor.nRef is set to 
** the number of FuncDef objects created (either 1 or 3, depending on whether
** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
................................................................................
typedef struct {
  sqlite4 *db;        /* The database being initialized */
  int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
  char **pzErrMsg;    /* Error message stored here */
  int rc;             /* Result code stored here */
} InitData;











/*
** An instance of this structure defines the run-time environment.
*/
struct sqlite4_env {
  int nByte;                        /* Size of this object in bytes */
  int iVersion;                     /* Version number of this structure */
  int bMemstat;                     /* True to enable memory status */
................................................................................
  int nLookaside;                   /* Default lookaside buffer count */
  sqlite4_mem_methods m;            /* Low-level memory allocation interface */
  sqlite4_mutex_methods mutex;      /* Low-level mutex interface */
  void *pHeap;                      /* Heap storage space */
  int nHeap;                        /* Size of pHeap[] */
  int mnReq, mxReq;                 /* Min and max heap requests sizes */
  int mxParserStack;                /* maximum depth of the parser stack */
  int (*xKVFile)(sqlite4_env*, KVStore**, const char*, unsigned int);
  int (*xKVTmp)(sqlite4_env*, KVStore**, const char*, unsigned int);
  int (*xRandomness)(sqlite4_env*, int, unsigned char*);
  int (*xCurrentTime)(sqlite4_env*, sqlite4_uint64*);
  /* The above might be initialized to non-zero.  The following need to always
  ** initially be zero, however. */
  int isInit;                       /* True after initialization has finished */
  int inProgress;                   /* True while initialization in progress */
  int isMutexInit;                  /* True after mutexes are initialized */
  int isMallocInit;                 /* True after malloc is initialized */
  sqlite4_mutex *pInitMutex;        /* Mutex used by sqlite4_initialize() */
  int nRefInitMutex;                /* Number of users of pInitMutex */
  void (*xLog)(void*,int,const char*); /* Function for logging */
  void *pLogArg;                       /* First argument to xLog() */
  int bLocaltimeFault;              /* True to fail localtime() calls */

  sqlite4_uint64 nowValue[4];       /* sqlite4_env_status() current values */
  sqlite4_uint64 mxValue[4];        /* sqlite4_env_status() max values */

};

/*
** Context pointer passed down through the tree-walk.
*/
struct Walker {
  int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
................................................................................
const sqlite4_mem_methods *sqlite4MemGetMemsys5(void);
#endif


#ifndef SQLITE_MUTEX_OMIT
  sqlite4_mutex_methods const *sqlite4DefaultMutex(void);
  sqlite4_mutex_methods const *sqlite4NoopMutex(void);
  sqlite4_mutex *sqlite4MutexAlloc(int);
  int sqlite4MutexInit(void);
  int sqlite4MutexEnd(void);
#endif

void sqlite4StatusAdd(sqlite4_env*, int, sqlite4_int64);
void sqlite4StatusSet(sqlite4_env*, int, sqlite4_uint64);

#ifndef SQLITE_OMIT_FLOATING_POINT
  int sqlite4IsNaN(double);
................................................................................
void sqlite4MayAbort(Parse*);
void sqlite4HaltConstraint(Parse*, int, char*, int);
Expr *sqlite4ExprDup(sqlite4*,Expr*,int);
ExprList *sqlite4ExprListDup(sqlite4*,ExprList*,int);
SrcList *sqlite4SrcListDup(sqlite4*,SrcList*,int);
IdList *sqlite4IdListDup(sqlite4*,IdList*);
Select *sqlite4SelectDup(sqlite4*,Select*,int);
void sqlite4FuncDefInsert(FuncDefHash*, FuncDef*);
FuncDef *sqlite4FindFunction(sqlite4*,const char*,int,int,u8,int);
void sqlite4RegisterBuiltinFunctions(sqlite4*);
void sqlite4RegisterDateTimeFunctions(sqlite4_env*);
void sqlite4RegisterGlobalFunctions(sqlite4_env*);
int sqlite4SafetyCheckOk(sqlite4*);
int sqlite4SafetyCheckSickOrOk(sqlite4*);
void sqlite4ChangeCookie(Parse*, int);
................................................................................
int sqlite4ValueFromExpr(sqlite4 *, Expr *, u8, u8, sqlite4_value **);
void sqlite4ValueApplyAffinity(sqlite4_value *, u8, u8);
#ifndef SQLITE_AMALGAMATION
extern const unsigned char sqlite4OpcodeProperty[];
extern const unsigned char sqlite4UpperToLower[];
extern const unsigned char sqlite4CtypeMap[];
extern const Token sqlite4IntTokens[];
extern SQLITE_WSD struct sqlite4_env sqlite4DefaultEnv;
extern SQLITE_WSD FuncDefHash sqlite4GlobalFunctions;
#ifndef SQLITE_OMIT_WSD
extern int sqlite4PendingByte;
#endif
#endif
void sqlite4RootPageMoved(sqlite4*, int, int, int);
void sqlite4Reindex(Parse*, Token*, Token*);
void sqlite4AlterFunctions(void);
void sqlite4AlterRenameTable(Parse*, SrcList*, Token*);
int sqlite4GetToken(const unsigned char *, int *);
void sqlite4NestedParse(Parse*, const char*, ...);
void sqlite4ExpirePreparedStatements(sqlite4*);
int sqlite4CodeSubselect(Parse *, Expr *, int, int);
void sqlite4SelectPrep(Parse*, Select*, NameContext*);
int sqlite4ResolveExprNames(NameContext*, Expr*);
................................................................................
** this constraint. 
**
** All of this is no-op for a production build.  It only comes into
** play when the SQLITE_MEMDEBUG compile-time option is used.
*/
#ifdef SQLITE_MEMDEBUG
  void sqlite4MemdebugSetType(void*,u8);
  int sqlite4MemdebugHasType(void*,u8);
  int sqlite4MemdebugNoType(void*,u8);
#else
# define sqlite4MemdebugSetType(X,Y)  /* no-op */
# define sqlite4MemdebugHasType(X,Y)  1
# define sqlite4MemdebugNoType(X,Y)   1
#endif
#define MEMTYPE_HEAP       0x01  /* General heap allocations */
#define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
#define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
#define MEMTYPE_DB         0x10  /* Uses sqlite4DbMalloc, not sqlite_malloc */

#endif /* _SQLITEINT_H_ */







<
<
<
<
<
<







 







|







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







<
<
<
<
<
<
<
<
<
<







 







|







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







>
>
>
>
>
>
>
>
>
>







 







|
<





|
|
|
<
<



>


>







 







|
|
|







 







|







 







|
|
<
<
<



|







 







|
|











556
557
558
559
560
561
562






563
564
565
566
567
568
569
...
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
...
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
...
770
771
772
773
774
775
776










777
778
779
780
781
782
783
...
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
...
949
950
951
952
953
954
955




















956
957
958
959
960
961
962
....
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
....
2410
2411
2412
2413
2414
2415
2416
2417

2418
2419
2420
2421
2422
2423
2424
2425


2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
....
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
....
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
....
2954
2955
2956
2957
2958
2959
2960
2961
2962



2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
....
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217

/*
** A convenience macro that returns the number of elements in
** an array.
*/
#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))







/*
** The following macros are used to suppress compiler warnings and to
** make it clear to human readers when a function parameter is deliberately 
** left unused within the body of a function. This usually happens when
** a function is called via a function pointer. For example the 
** implementation of an SQL aggregate step callback may not use the
** parameter indicating the number of arguments passed to the aggregate,
................................................................................
typedef struct Schema Schema;
typedef struct Expr Expr;
typedef struct ExprList ExprList;
typedef struct ExprSpan ExprSpan;
typedef struct FKey FKey;
typedef struct FuncDestructor FuncDestructor;
typedef struct FuncDef FuncDef;
typedef struct FuncDefTable FuncDefTable;
typedef struct IdList IdList;
typedef struct Index Index;
typedef struct IndexSample IndexSample;
typedef struct KeyClass KeyClass;
typedef struct KeyInfo KeyInfo;
typedef struct Lookaside Lookaside;
typedef struct LookasideSlot LookasideSlot;
................................................................................
struct Db {
  char *zName;         /* Name of this database */
  KVStore *pKV;        /* KV store for the database file */
  u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
  u8 chngFlag;         /* True if modified */
  Schema *pSchema;     /* Pointer to database schema (possibly shared) */
};

/*
** Each SQL function is defined by an instance of the following
** structure.  A pointer to this structure is stored in the sqlite.aFunc
** hash table.  When multiple functions have the same name, the hash table
** points to a linked list of these structures.
*/
struct FuncDef {
  i16 nArg;            /* Number of arguments.  -1 means unlimited */
  u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
  u8 flags;            /* Some combination of SQLITE_FUNC_* */
  void *pUserData;     /* User data parameter */
  FuncDef *pSameName;  /* Next with a different name but the same hash */
  void (*xFunc)(sqlite4_context*,int,sqlite4_value**); /* Regular function */
  void (*xStep)(sqlite4_context*,int,sqlite4_value**); /* Aggregate step */
  void (*xFinalize)(sqlite4_context*);                /* Aggregate finalizer */
  char *zName;         /* SQL name of the function. */
  FuncDef *pNextName;  /* Next function with a different name */
  FuncDestructor *pDestructor;   /* Reference counted destructor function */
};

/*
** A table of SQL functions.  
**
** The content is a linked list of FuncDef structures with branches.  When
** there are two or more FuncDef objects with the same name, they are 
** connected using FuncDef.pSameName.  FuncDef objects with different names
** are connected using FuncDef.pNextName.
*/
struct FuncDefTable {
  FuncDef *pFirst;     /* First function definition */
  FuncDef *pLast;      /* Last function definition */
  FuncDef *pSame;      /* Tail of pSameName list for pLast */
};

/*
** An instance of the following structure stores a database schema.
**
** Most Schema objects are associated with a database file.  The exception is
** the Schema for the TEMP databaes (sqlite4.aDb[1]) which is free-standing.
** 
................................................................................
  void *pStart;           /* First byte of available memory space */
  void *pEnd;             /* First byte past end of available space */
};
struct LookasideSlot {
  LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
};











/*
** Each database connection is an instance of the following structure.
**
** The sqlite.lastRowid records the last insert rowid generated by an
** insert statement.  Inserts on views do not affect its value.  Each
** trigger has its own context, so that lastRowid can be updated inside
** triggers as usual.  The previous value will be restored once the trigger
................................................................................
#ifndef SQLITE_OMIT_VIRTUALTABLE
  Hash aModule;                 /* populated by sqlite4_create_module() */
  VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
  VTable **aVTrans;             /* Virtual tables with open transactions */
  int nVTrans;                  /* Allocated size of aVTrans */
  VTable *pDisconnect;    /* Disconnect these in next sqlite4_prepare() */
#endif
  FuncDefTable aFunc;            /* Hash table of connection functions */
  Hash aCollSeq;                /* All collating sequences */
  Db aDbStatic[2];              /* Static space for the 2 default backends */
  Savepoint *pSavepoint;        /* List of active savepoints */
  int nSavepoint;               /* Number of open savepoints */
  int nStatement;               /* Number of nested statement-transactions  */
  i64 nDeferredCons;            /* Net deferred constraints this transaction. */
  int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
................................................................................
*/
#define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
#define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
#define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
#define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
#define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */





















/*
** This structure encapsulates a user-function destructor callback (as
** configured using create_function_v2()) and a reference counter. When
** create_function_v2() is called to create a function with a destructor,
** a single object of this type is allocated. FuncDestructor.nRef is set to 
** the number of FuncDef objects created (either 1 or 3, depending on whether
** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
................................................................................
typedef struct {
  sqlite4 *db;        /* The database being initialized */
  int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
  char **pzErrMsg;    /* Error message stored here */
  int rc;             /* Result code stored here */
} InitData;

/*
** A pluggable storage engine
*/
typedef struct KVFactory {
  struct KVFactory *pNext;          /* Next in list of them all */
  const char *zName;                /* Name of this factory */
  int (*xFactory)(sqlite4_env*,sqlite4_kvstore**,const char*,unsigned);
  int isPerm;                       /* True if a built-in.  Cannot be popped */
} KVFactory;

/*
** An instance of this structure defines the run-time environment.
*/
struct sqlite4_env {
  int nByte;                        /* Size of this object in bytes */
  int iVersion;                     /* Version number of this structure */
  int bMemstat;                     /* True to enable memory status */
................................................................................
  int nLookaside;                   /* Default lookaside buffer count */
  sqlite4_mem_methods m;            /* Low-level memory allocation interface */
  sqlite4_mutex_methods mutex;      /* Low-level mutex interface */
  void *pHeap;                      /* Heap storage space */
  int nHeap;                        /* Size of pHeap[] */
  int mnReq, mxReq;                 /* Min and max heap requests sizes */
  int mxParserStack;                /* maximum depth of the parser stack */
  KVFactory *pFactory;              /* List of factories */

  int (*xRandomness)(sqlite4_env*, int, unsigned char*);
  int (*xCurrentTime)(sqlite4_env*, sqlite4_uint64*);
  /* The above might be initialized to non-zero.  The following need to always
  ** initially be zero, however. */
  int isInit;                       /* True after initialization has finished */
  sqlite4_mutex *pFactoryMutex;     /* Mutex for pFactory */
  sqlite4_mutex *pPrngMutex;        /* Mutex for the PRNG */
  u32 prngX, prngY;                 /* State of the PRNG */


  void (*xLog)(void*,int,const char*); /* Function for logging */
  void *pLogArg;                       /* First argument to xLog() */
  int bLocaltimeFault;              /* True to fail localtime() calls */
  sqlite4_mutex *pMemMutex;         /* Mutex for nowValue[] and mxValue[] */
  sqlite4_uint64 nowValue[4];       /* sqlite4_env_status() current values */
  sqlite4_uint64 mxValue[4];        /* sqlite4_env_status() max values */
  FuncDefTable aGlobalFuncs;        /* Lookup table of global functions */
};

/*
** Context pointer passed down through the tree-walk.
*/
struct Walker {
  int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
................................................................................
const sqlite4_mem_methods *sqlite4MemGetMemsys5(void);
#endif


#ifndef SQLITE_MUTEX_OMIT
  sqlite4_mutex_methods const *sqlite4DefaultMutex(void);
  sqlite4_mutex_methods const *sqlite4NoopMutex(void);
  sqlite4_mutex *sqlite4MutexAlloc(sqlite4_env*,int);
  int sqlite4MutexInit(sqlite4_env*);
  int sqlite4MutexEnd(sqlite4_env*);
#endif

void sqlite4StatusAdd(sqlite4_env*, int, sqlite4_int64);
void sqlite4StatusSet(sqlite4_env*, int, sqlite4_uint64);

#ifndef SQLITE_OMIT_FLOATING_POINT
  int sqlite4IsNaN(double);
................................................................................
void sqlite4MayAbort(Parse*);
void sqlite4HaltConstraint(Parse*, int, char*, int);
Expr *sqlite4ExprDup(sqlite4*,Expr*,int);
ExprList *sqlite4ExprListDup(sqlite4*,ExprList*,int);
SrcList *sqlite4SrcListDup(sqlite4*,SrcList*,int);
IdList *sqlite4IdListDup(sqlite4*,IdList*);
Select *sqlite4SelectDup(sqlite4*,Select*,int);
void sqlite4FuncDefInsert(FuncDefTable*, FuncDef*, int);
FuncDef *sqlite4FindFunction(sqlite4*,const char*,int,int,u8,int);
void sqlite4RegisterBuiltinFunctions(sqlite4*);
void sqlite4RegisterDateTimeFunctions(sqlite4_env*);
void sqlite4RegisterGlobalFunctions(sqlite4_env*);
int sqlite4SafetyCheckOk(sqlite4*);
int sqlite4SafetyCheckSickOrOk(sqlite4*);
void sqlite4ChangeCookie(Parse*, int);
................................................................................
int sqlite4ValueFromExpr(sqlite4 *, Expr *, u8, u8, sqlite4_value **);
void sqlite4ValueApplyAffinity(sqlite4_value *, u8, u8);
#ifndef SQLITE_AMALGAMATION
extern const unsigned char sqlite4OpcodeProperty[];
extern const unsigned char sqlite4UpperToLower[];
extern const unsigned char sqlite4CtypeMap[];
extern const Token sqlite4IntTokens[];
extern struct sqlite4_env sqlite4DefaultEnv;
extern struct KVFactory sqlite4BuiltinFactory;



#endif
void sqlite4RootPageMoved(sqlite4*, int, int, int);
void sqlite4Reindex(Parse*, Token*, Token*);
void sqlite4AlterFunctions(sqlite4_env*);
void sqlite4AlterRenameTable(Parse*, SrcList*, Token*);
int sqlite4GetToken(const unsigned char *, int *);
void sqlite4NestedParse(Parse*, const char*, ...);
void sqlite4ExpirePreparedStatements(sqlite4*);
int sqlite4CodeSubselect(Parse *, Expr *, int, int);
void sqlite4SelectPrep(Parse*, Select*, NameContext*);
int sqlite4ResolveExprNames(NameContext*, Expr*);
................................................................................
** this constraint. 
**
** All of this is no-op for a production build.  It only comes into
** play when the SQLITE_MEMDEBUG compile-time option is used.
*/
#ifdef SQLITE_MEMDEBUG
  void sqlite4MemdebugSetType(void*,u8);
  int sqlite4MemdebugHasType(const void*,u8);
  int sqlite4MemdebugNoType(const void*,u8);
#else
# define sqlite4MemdebugSetType(X,Y)  /* no-op */
# define sqlite4MemdebugHasType(X,Y)  1
# define sqlite4MemdebugNoType(X,Y)   1
#endif
#define MEMTYPE_HEAP       0x01  /* General heap allocations */
#define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
#define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
#define MEMTYPE_DB         0x10  /* Uses sqlite4DbMalloc, not sqlite_malloc */

#endif /* _SQLITEINT_H_ */

Changes to src/storage.c.

84
85
86
87
88
89
90



91
92
93





94
95
96

97
98

99
100











101
102
103
104
105
106
107
  const char *zUri,        /* URI for this database */
  KVStore **ppKVStore,     /* Write the new KVStore object here */
  unsigned flags           /* Option flags */
){
  KVStore *pNew = 0;
  int rc;
  sqlite4_env *pEnv = &sqlite4DefaultEnv;  /* OR db->pEnv */




  if( zUri && zUri[0] 
   && pEnv->xKVFile 





   && memcmp(":memory:", zUri, 8)
  ){
    rc = pEnv->xKVFile(pEnv, &pNew, zUri, flags);

  }else{
    rc = pEnv->xKVTmp(pEnv, &pNew, zUri, flags);

  }












  *ppKVStore = pNew;
  if( pNew ){
    sqlite4_randomness(pEnv, sizeof(pNew->kvId), &pNew->kvId);
    sqlite4_snprintf(pNew->zKVName, sizeof(pNew->zKVName),
                     "%s", zName);
    pNew->fTrace = (db->flags & SQLITE_KvTrace)!=0;
    kvTrace(pNew, "open(%s,%d,0x%04x)", zUri, pNew->kvId, flags);







>
>
>

<
<
>
>
>
>
>
|
<
<
>
|
<
>
|
|
>
>
>
>
>
>
>
>
>
>
>







84
85
86
87
88
89
90
91
92
93
94


95
96
97
98
99
100


101
102

103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
  const char *zUri,        /* URI for this database */
  KVStore **ppKVStore,     /* Write the new KVStore object here */
  unsigned flags           /* Option flags */
){
  KVStore *pNew = 0;
  int rc;
  sqlite4_env *pEnv = &sqlite4DefaultEnv;  /* OR db->pEnv */
  const char *zStorageName;
  KVFactory *pMkr;
  int (*xFactory)(sqlite4_env*,sqlite4_kvstore**,const char*,unsigned);



  if( (flags & SQLITE_KVOPEN_TEMPORARY)!=0 || zUri==0 || zUri[0]==0 ){
    zStorageName = "temp";
  }else{
    zStorageName = sqlite4_uri_parameter(zName, "kv");
    if( zStorageName==0 ){
      if( memcmp(":memory:", zUri, 8)==0 ){


        zStorageName = "temp";
      }else{

        zStorageName = "main";
      }
    }
  }
  *ppKVStore = 0;
  sqlite4_mutex_enter(pEnv->pFactoryMutex);
  for(pMkr=pEnv->pFactory; pMkr && strcmp(zStorageName,pMkr->zName);
      pMkr=pMkr->pNext){}
  xFactory = pMkr ? pMkr->xFactory : 0;
  sqlite4_mutex_leave(pEnv->pFactoryMutex);
  if( xFactory==0 ){
    return SQLITE_ERROR;
  }
  rc = xFactory(pEnv, &pNew, zUri, flags);
  *ppKVStore = pNew;
  if( pNew ){
    sqlite4_randomness(pEnv, sizeof(pNew->kvId), &pNew->kvId);
    sqlite4_snprintf(pNew->zKVName, sizeof(pNew->zKVName),
                     "%s", zName);
    pNew->fTrace = (db->flags & SQLITE_KvTrace)!=0;
    kvTrace(pNew, "open(%s,%d,0x%04x)", zUri, pNew->kvId, flags);

Changes to src/storage.h.

120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
** had not been deleted.  Two cursors can be pointing to the same entry and
** one cursor can xDelete and the other cursor is expected to continue
** functioning normally, including responding correctly to subsequent
** xNext and xPrev calls.
*/

/* Typedefs of datatypes */
typedef struct KVStore KVStore;
typedef struct KVStoreMethods KVStoreMethods;
typedef struct KVCursor KVCursor;
typedef unsigned char KVByteArray;
typedef int KVSize;

/*
** A Key-Value storage engine is defined by an instance of the following
** structures:
*/
struct KVStoreMethods {
  int (*xReplace)(KVStore*, const KVByteArray *pKey, KVSize nKey,
                            const KVByteArray *pData, KVSize nData);
  int (*xOpenCursor)(KVStore*, KVCursor**);
  int (*xSeek)(KVCursor*, const KVByteArray *pKey, KVSize nKey, int dir);
  int (*xNext)(KVCursor*);
  int (*xPrev)(KVCursor*);
  int (*xDelete)(KVCursor*);
  int (*xKey)(KVCursor*, const KVByteArray **ppKey, KVSize *pnKey);
  int (*xData)(KVCursor*, KVSize ofst, KVSize n,
                          const KVByteArray **ppData, KVSize *pnData);
  int (*xReset)(KVCursor*);
  int (*xCloseCursor)(KVCursor*);
  int (*xBegin)(KVStore*, int);
  int (*xCommitPhaseOne)(KVStore*, int);
  int (*xCommitPhaseTwo)(KVStore*, int);
  int (*xRollback)(KVStore*, int);
  int (*xRevert)(KVStore*, int);
  int (*xClose)(KVStore*);
  int (*xControl)(KVStore*, int, void *);
};
struct KVStore {
  const KVStoreMethods *pStoreVfunc;    /* Virtual method table */
  sqlite4_env *pEnv;                    /* Runtime environment for this store */
  int iTransLevel;                      /* Current transaction level */
  u16 kvId;                             /* Unique ID used for tracing */
  u8 fTrace;                            /* True to enable tracing */
  char zKVName[12];                     /* Used for debugging */
  /* Subclasses will typically append additional fields */
};

/*
** Base class for cursors
*/
struct KVCursor {
  KVStore *pStore;                    /* The owner of this cursor */
  const KVStoreMethods *pStoreVfunc;  /* Methods */
  sqlite4_env *pEnv;                  /* Runtime environment for this cursor */
  int iTransLevel;                    /* Current transaction level */
  u16 curId;                          /* Unique ID for tracing */
  u8 fTrace;                          /* True to enable tracing */
  /* Subclasses will typically add additional fields */
};

/*
** Valid flags for sqlite4KVStorageOpen()
*/
#define SQLITE_KVOPEN_TEMPORARY       0x0001  /* A temporary database */
#define SQLITE_KVOPEN_NO_TRANSACTIONS 0x0002  /* No transactions will be used */

int sqlite4KVStoreOpenMem(sqlite4_env*, KVStore**, const char *, unsigned);
int sqlite4KVStoreOpenLsm(sqlite4_env*, KVStore**, const char *, unsigned);
int sqlite4KVStoreOpen(
  sqlite4*,
  const char *zLabel, 
  const char *zUri,







|
|
|

|

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







120
121
122
123
124
125
126
127
128
129
130
131
132





















































133
134
135
136
137
138
139
** had not been deleted.  Two cursors can be pointing to the same entry and
** one cursor can xDelete and the other cursor is expected to continue
** functioning normally, including responding correctly to subsequent
** xNext and xPrev calls.
*/

/* Typedefs of datatypes */
typedef struct sqlite4_kvstore KVStore;
typedef struct sqlite4_kv_methods KVStoreMethods;
typedef struct sqlite4_kvcursor KVCursor;
typedef unsigned char KVByteArray;
typedef sqlite4_kvsize KVSize;























































int sqlite4KVStoreOpenMem(sqlite4_env*, KVStore**, const char *, unsigned);
int sqlite4KVStoreOpenLsm(sqlite4_env*, KVStore**, const char *, unsigned);
int sqlite4KVStoreOpen(
  sqlite4*,
  const char *zLabel, 
  const char *zUri,

Changes to src/tclsqlite.c.

2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
....
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
  int flags;
  Tcl_DString translatedFilename;
#ifdef SQLITE_HAS_CODEC
  void *pKey = 0;
  int nKey = 0;
#endif

  /* In normal use, each TCL interpreter runs in a single thread.  So
  ** by default, we can turn of mutexing on SQLite database connections.
  ** However, for testing purposes it is useful to have mutexes turned
  ** on.  So, by default, mutexes default off.  But if compiled with
  ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on.
  */
#ifdef SQLITE_TCL_DEFAULT_FULLMUTEX
  flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
#else
  flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX;
#endif

  if( objc==2 ){
    zArg = Tcl_GetStringFromObj(objv[1], 0);
    if( strcmp(zArg,"-version")==0 ){
      Tcl_AppendResult(interp,sqlite4_libversion(),0);
      return TCL_OK;
    }
    if( strcmp(zArg,"-has-codec")==0 ){
................................................................................
      int b;
      if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
      if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
        flags |= SQLITE_OPEN_CREATE;
      }else{
        flags &= ~SQLITE_OPEN_CREATE;
      }
    }else if( strcmp(zArg, "-nomutex")==0 ){
      int b;
      if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
      if( b ){
        flags |= SQLITE_OPEN_NOMUTEX;
        flags &= ~SQLITE_OPEN_FULLMUTEX;
      }else{
        flags &= ~SQLITE_OPEN_NOMUTEX;
      }
    }else if( strcmp(zArg, "-fullmutex")==0 ){
      int b;
      if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
      if( b ){
        flags |= SQLITE_OPEN_FULLMUTEX;
        flags &= ~SQLITE_OPEN_NOMUTEX;
      }else{
        flags &= ~SQLITE_OPEN_FULLMUTEX;
      }
    }else{
      Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
      return TCL_ERROR;
    }
  }
  if( objc<3 || (objc&1)!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, 







<
<
<
<
<
<
<
<
<
|
<
<







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







2229
2230
2231
2232
2233
2234
2235









2236


2237
2238
2239
2240
2241
2242
2243
....
2271
2272
2273
2274
2275
2276
2277


















2278
2279
2280
2281
2282
2283
2284
  int flags;
  Tcl_DString translatedFilename;
#ifdef SQLITE_HAS_CODEC
  void *pKey = 0;
  int nKey = 0;
#endif










  flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;


  if( objc==2 ){
    zArg = Tcl_GetStringFromObj(objv[1], 0);
    if( strcmp(zArg,"-version")==0 ){
      Tcl_AppendResult(interp,sqlite4_libversion(),0);
      return TCL_OK;
    }
    if( strcmp(zArg,"-has-codec")==0 ){
................................................................................
      int b;
      if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR;
      if( b && (flags & SQLITE_OPEN_READONLY)==0 ){
        flags |= SQLITE_OPEN_CREATE;
      }else{
        flags &= ~SQLITE_OPEN_CREATE;
      }


















    }else{
      Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0);
      return TCL_ERROR;
    }
  }
  if( objc<3 || (objc&1)!=1 ){
    Tcl_WrongNumArgs(interp, 1, objv, 

Changes to src/tokenize.c.

474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
  }
  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
    sqlite4SetString(&pParse->zErrMsg, db, "%s", sqlite4ErrStr(pParse->rc));
  }
  assert( pzErrMsg!=0 );
  if( pParse->zErrMsg ){
    *pzErrMsg = pParse->zErrMsg;
    sqlite4_log(pParse->rc, "%s", *pzErrMsg);
    pParse->zErrMsg = 0;
    nErr++;
  }
  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
    sqlite4VdbeDelete(pParse->pVdbe);
    pParse->pVdbe = 0;
  }







|







474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
  }
  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
    sqlite4SetString(&pParse->zErrMsg, db, "%s", sqlite4ErrStr(pParse->rc));
  }
  assert( pzErrMsg!=0 );
  if( pParse->zErrMsg ){
    *pzErrMsg = pParse->zErrMsg;
    sqlite4_log(db->pEnv, pParse->rc, "%s", *pzErrMsg);
    pParse->zErrMsg = 0;
    nErr++;
  }
  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
    sqlite4VdbeDelete(pParse->pVdbe);
    pParse->pVdbe = 0;
  }

Changes to src/util.c.

1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053

/*
** Log an error that is an API call on a connection pointer that should
** not have been used.  The "type" of connection pointer is given as the
** argument.  The zType is a word like "NULL" or "closed" or "invalid".
*/
static void logBadConnection(const char *zType){
  sqlite4_log(SQLITE_MISUSE, 
     "API call with %s database connection pointer",
     zType
  );
}

/*
** Check to make sure we have a valid db pointer.  This test is not







|







1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053

/*
** Log an error that is an API call on a connection pointer that should
** not have been used.  The "type" of connection pointer is given as the
** argument.  The zType is a word like "NULL" or "closed" or "invalid".
*/
static void logBadConnection(const char *zType){
  sqlite4_log(0, SQLITE_MISUSE, 
     "API call with %s database connection pointer",
     zType
  );
}

/*
** Check to make sure we have a valid db pointer.  This test is not

Changes to src/vdbe.c.

803
804
805
806
807
808
809

810
811
812

813
814
815
816
817
818
819
820
....
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
  p->rc = pOp->p1;
  p->errorAction = (u8)pOp->p2;
  p->pc = pc;
  if( pOp->p4.z ){
    assert( p->rc!=SQLITE_OK );
    sqlite4SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
    testcase( sqlite4DefaultEnv.xLog!=0 );

    sqlite4_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
  }else if( p->rc ){
    testcase( sqlite4DefaultEnv.xLog!=0 );

    sqlite4_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
  }
  rc = sqlite4VdbeHalt(p);
  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  if( rc==SQLITE_BUSY ){
    p->rc = rc = SQLITE_BUSY;
  }else{
    assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
................................................................................
  /* If we reach this point, it means that execution is finished with
  ** an error of some kind.
  */
vdbe_error_halt:
  assert( rc );
  p->rc = rc;
  testcase( sqlite4DefaultEnv.xLog!=0 );
  sqlite4_log(rc, "statement aborts at %d: [%s] %s", 
                   pc, p->zSql, p->zErrMsg);
  sqlite4VdbeHalt(p);
  if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
  rc = SQLITE_ERROR;
  if( resetSchemaOnFault>0 ){
    sqlite4ResetInternalSchema(db, resetSchemaOnFault-1);
  }







>
|


>
|







 







|







803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
....
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
  p->rc = pOp->p1;
  p->errorAction = (u8)pOp->p2;
  p->pc = pc;
  if( pOp->p4.z ){
    assert( p->rc!=SQLITE_OK );
    sqlite4SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
    testcase( sqlite4DefaultEnv.xLog!=0 );
    sqlite4_log(db->pEnv, pOp->p1,
                "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
  }else if( p->rc ){
    testcase( sqlite4DefaultEnv.xLog!=0 );
    sqlite4_log(db->pEnv, pOp->p1,
                "constraint failed at %d in [%s]", pc, p->zSql);
  }
  rc = sqlite4VdbeHalt(p);
  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  if( rc==SQLITE_BUSY ){
    p->rc = rc = SQLITE_BUSY;
  }else{
    assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
................................................................................
  /* If we reach this point, it means that execution is finished with
  ** an error of some kind.
  */
vdbe_error_halt:
  assert( rc );
  p->rc = rc;
  testcase( sqlite4DefaultEnv.xLog!=0 );
  sqlite4_log(db->pEnv, rc, "statement aborts at %d: [%s] %s", 
                   pc, p->zSql, p->zErrMsg);
  sqlite4VdbeHalt(p);
  if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
  rc = SQLITE_ERROR;
  if( resetSchemaOnFault>0 ){
    sqlite4ResetInternalSchema(db, resetSchemaOnFault-1);
  }

Changes to src/vdbeapi.c.

34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
...
191
192
193
194
195
196
197





198
199
200
201
202
203
204
...
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
/*
** Check on a Vdbe to make sure it has not been finalized.  Log
** an error and return true if it has been finalized (or is otherwise
** invalid).  Return false if it is ok.
*/
static int vdbeSafety(Vdbe *p){
  if( p->db==0 ){
    sqlite4_log(SQLITE_MISUSE, "API called with finalized prepared statement");
    return 1;
  }else{
    return 0;
  }
}
static int vdbeSafetyNotNull(Vdbe *p){
  if( p==0 ){
    sqlite4_log(SQLITE_MISUSE, "API called with NULL prepared statement");
    return 1;
  }else{
    return vdbeSafety(p);
  }
}

/*
................................................................................
static void setResultStrOrError(
  sqlite4_context *pCtx,  /* Function context */
  const char *z,          /* String pointer */
  int n,                  /* Bytes in string, or negative */
  u8 enc,                 /* Encoding of z.  0 for BLOBs */
  void (*xDel)(void*)     /* Destructor function */
){





  if( sqlite4VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
    sqlite4_result_error_toobig(pCtx);
  }
}
void sqlite4_result_blob(
  sqlite4_context *pCtx, 
  const void *z, 
................................................................................
  if( vdbeSafetyNotNull(p) ){
    return SQLITE_MISUSE_BKPT;
  }
  sqlite4_mutex_enter(p->db->mutex);
  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
    sqlite4Error(p->db, SQLITE_MISUSE, 0);
    sqlite4_mutex_leave(p->db->mutex);
    sqlite4_log(SQLITE_MISUSE, 
        "bind on a busy prepared statement: [%s]", p->zSql);
    return SQLITE_MISUSE_BKPT;
  }
  if( i<1 || i>p->nVar ){
    sqlite4Error(p->db, SQLITE_RANGE, 0);
    sqlite4_mutex_leave(p->db->mutex);
    return SQLITE_RANGE;







|







|







 







>
>
>
>
>







 







|







34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
...
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
...
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
/*
** Check on a Vdbe to make sure it has not been finalized.  Log
** an error and return true if it has been finalized (or is otherwise
** invalid).  Return false if it is ok.
*/
static int vdbeSafety(Vdbe *p){
  if( p->db==0 ){
    sqlite4_log(0,SQLITE_MISUSE,"API called with finalized prepared statement");
    return 1;
  }else{
    return 0;
  }
}
static int vdbeSafetyNotNull(Vdbe *p){
  if( p==0 ){
    sqlite4_log(0,SQLITE_MISUSE, "API called with NULL prepared statement");
    return 1;
  }else{
    return vdbeSafety(p);
  }
}

/*
................................................................................
static void setResultStrOrError(
  sqlite4_context *pCtx,  /* Function context */
  const char *z,          /* String pointer */
  int n,                  /* Bytes in string, or negative */
  u8 enc,                 /* Encoding of z.  0 for BLOBs */
  void (*xDel)(void*)     /* Destructor function */
){
  if( xDel==SQLITE_DYNAMIC ){
    assert( sqlite4MemdebugHasType(z, MEMTYPE_HEAP) );
    assert( sqlite4MemdebugNoType(z, ~MEMTYPE_HEAP) );
    sqlite4MemdebugSetType((char*)z, MEMTYPE_DB | MEMTYPE_HEAP);
  }
  if( sqlite4VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
    sqlite4_result_error_toobig(pCtx);
  }
}
void sqlite4_result_blob(
  sqlite4_context *pCtx, 
  const void *z, 
................................................................................
  if( vdbeSafetyNotNull(p) ){
    return SQLITE_MISUSE_BKPT;
  }
  sqlite4_mutex_enter(p->db->mutex);
  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
    sqlite4Error(p->db, SQLITE_MISUSE, 0);
    sqlite4_mutex_leave(p->db->mutex);
    sqlite4_log(p->db->pEnv,SQLITE_MISUSE, 
        "bind on a busy prepared statement: [%s]", p->zSql);
    return SQLITE_MISUSE_BKPT;
  }
  if( i<1 || i>p->nVar ){
    sqlite4Error(p->db, SQLITE_RANGE, 0);
    sqlite4_mutex_leave(p->db->mutex);
    return SQLITE_RANGE;

Changes to test/log1.test.

434
435
436
437
438
439
440

441
442
443
444
445
446
447
  copy_db_files test.db test.db2
  sqlite4 db2 test.db2
  execsql { SELECT count(*) FROM t1 ; PRAGMA integrity_check } db2
} {21 ok}
db2 close

do_test 11.21 { sqlite4_lsm_work db main -flush } {0}

do_execsql_test 11.22 {
  INSERT INTO t1 VALUES(randstr(10,10), randstr(100,100));
}
do_test 11.23 { 
  sqlite4_lsm_info db main log-structure 
} {1335 1482 0 1259 1483 1908}
do_test 11.24 { sqlite4_lsm_work db main -checkpoint } {0}







>







434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
  copy_db_files test.db test.db2
  sqlite4 db2 test.db2
  execsql { SELECT count(*) FROM t1 ; PRAGMA integrity_check } db2
} {21 ok}
db2 close

do_test 11.21 { sqlite4_lsm_work db main -flush } {0}
db eval {SELECT randstr(5,5)}
do_execsql_test 11.22 {
  INSERT INTO t1 VALUES(randstr(10,10), randstr(100,100));
}
do_test 11.23 { 
  sqlite4_lsm_info db main log-structure 
} {1335 1482 0 1259 1483 1908}
do_test 11.24 { sqlite4_lsm_work db main -checkpoint } {0}

Changes to test/test_main.c.

3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
....
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
....
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
    struct OpenFlag {
      const char *zFlag;
      int flag;
    } aFlag[] = {
      { "SQLITE_OPEN_READONLY", SQLITE_OPEN_READONLY },
      { "SQLITE_OPEN_READWRITE", SQLITE_OPEN_READWRITE },
      { "SQLITE_OPEN_CREATE", SQLITE_OPEN_CREATE },
      { "SQLITE_OPEN_DELETEONCLOSE", SQLITE_OPEN_DELETEONCLOSE },
      { "SQLITE_OPEN_EXCLUSIVE", SQLITE_OPEN_EXCLUSIVE },
      { "SQLITE_OPEN_AUTOPROXY", SQLITE_OPEN_AUTOPROXY },
      { "SQLITE_OPEN_MAIN_DB", SQLITE_OPEN_MAIN_DB },
      { "SQLITE_OPEN_TEMP_DB", SQLITE_OPEN_TEMP_DB },
      { "SQLITE_OPEN_TRANSIENT_DB", SQLITE_OPEN_TRANSIENT_DB },
      { "SQLITE_OPEN_MAIN_JOURNAL", SQLITE_OPEN_MAIN_JOURNAL },
      { "SQLITE_OPEN_TEMP_JOURNAL", SQLITE_OPEN_TEMP_JOURNAL },
      { "SQLITE_OPEN_SUBJOURNAL", SQLITE_OPEN_SUBJOURNAL },
      { "SQLITE_OPEN_MASTER_JOURNAL", SQLITE_OPEN_MASTER_JOURNAL },
      { "SQLITE_OPEN_NOMUTEX", SQLITE_OPEN_NOMUTEX },
      { "SQLITE_OPEN_FULLMUTEX", SQLITE_OPEN_FULLMUTEX },
      { "SQLITE_OPEN_WAL", SQLITE_OPEN_WAL },
      { 0, 0 }
    };
    rc = Tcl_GetIndexFromObjStruct(interp, apFlag[i], aFlag, sizeof(aFlag[0]), 
        "flag", 0, &iFlag
    );
    if( rc!=TCL_OK ) return rc;
    flags |= aFlag[iFlag].flag;
................................................................................
  }
  if( Tcl_GetIntFromObj(interp, objv[3], &val) ) return TCL_ERROR;
  rc = sqlite4_limit(db, id, val);
  Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
  return TCL_OK;  
}

/*
** tclcmd:  save_prng_state
**
** Save the state of the pseudo-random number generator.
** At the same time, verify that sqlite4_test_control works even when
** called with an out-of-range opcode.
*/
static int save_prng_state(
  ClientData clientData, /* Pointer to sqlite4_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  int rc = sqlite4_test_control(9999);
  assert( rc==0 );
  rc = sqlite4_test_control(-1);
  assert( rc==0 );
  sqlite4_test_control(SQLITE_TESTCTRL_PRNG_SAVE);
  return TCL_OK;
}
/*
** tclcmd:  restore_prng_state
*/
static int restore_prng_state(
  ClientData clientData, /* Pointer to sqlite4_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  sqlite4_test_control(SQLITE_TESTCTRL_PRNG_RESTORE);
  return TCL_OK;
}
/*
** tclcmd:  reset_prng_state
*/
static int reset_prng_state(
  ClientData clientData, /* Pointer to sqlite4_enable_XXX function */
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int objc,              /* Number of arguments */
  Tcl_Obj *CONST objv[]  /* Command arguments */
){
  sqlite4_test_control(SQLITE_TESTCTRL_PRNG_RESET);
  return TCL_OK;
}


#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
static void test_unlock_notify_cb(void **aArg, int nArg){
  int ii;
  for(ii=0; ii<nArg; ii++){
    Tcl_EvalEx((Tcl_Interp *)aArg[ii], "unlock_notify", -1, TCL_EVAL_GLOBAL);
  }
................................................................................
     { "sqlite4_stmt_busy",             test_stmt_busy     ,0 },
     { "uses_stmt_journal",             uses_stmt_journal ,0 },

     { "sqlite4_db_release_memory",     test_db_release_memory,  0},

     { "sqlite4_limit",                 test_limit,                 0},

     { "save_prng_state",               save_prng_state,    0 },
     { "restore_prng_state",            restore_prng_state, 0 },
     { "reset_prng_state",              reset_prng_state,   0 },
     { "optimization_control",          optimization_control,0},
#if SQLITE_OS_WIN
     { "lock_win32_file",               win32_file_lock,    0 },
#endif
     { "tcl_objproc",                   runAsObjProc,       0 },

     /* sqlite4_column_*() API */







<
<
<
<
<
<
<
<
<
<
<
<
<







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







<
<
<







3265
3266
3267
3268
3269
3270
3271













3272
3273
3274
3275
3276
3277
3278
....
3956
3957
3958
3959
3960
3961
3962













































3963
3964
3965
3966
3967
3968
3969
....
4445
4446
4447
4448
4449
4450
4451



4452
4453
4454
4455
4456
4457
4458
    struct OpenFlag {
      const char *zFlag;
      int flag;
    } aFlag[] = {
      { "SQLITE_OPEN_READONLY", SQLITE_OPEN_READONLY },
      { "SQLITE_OPEN_READWRITE", SQLITE_OPEN_READWRITE },
      { "SQLITE_OPEN_CREATE", SQLITE_OPEN_CREATE },













      { 0, 0 }
    };
    rc = Tcl_GetIndexFromObjStruct(interp, apFlag[i], aFlag, sizeof(aFlag[0]), 
        "flag", 0, &iFlag
    );
    if( rc!=TCL_OK ) return rc;
    flags |= aFlag[iFlag].flag;
................................................................................
  }
  if( Tcl_GetIntFromObj(interp, objv[3], &val) ) return TCL_ERROR;
  rc = sqlite4_limit(db, id, val);
  Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
  return TCL_OK;  
}















































#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
static void test_unlock_notify_cb(void **aArg, int nArg){
  int ii;
  for(ii=0; ii<nArg; ii++){
    Tcl_EvalEx((Tcl_Interp *)aArg[ii], "unlock_notify", -1, TCL_EVAL_GLOBAL);
  }
................................................................................
     { "sqlite4_stmt_busy",             test_stmt_busy     ,0 },
     { "uses_stmt_journal",             uses_stmt_journal ,0 },

     { "sqlite4_db_release_memory",     test_db_release_memory,  0},

     { "sqlite4_limit",                 test_limit,                 0},




     { "optimization_control",          optimization_control,0},
#if SQLITE_OS_WIN
     { "lock_win32_file",               win32_file_lock,    0 },
#endif
     { "tcl_objproc",                   runAsObjProc,       0 },

     /* sqlite4_column_*() API */

Changes to test/test_malloc.c.

71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
...
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
...
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
...
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
** A version of sqlite4_mem_methods.xMalloc() that includes fault simulation
** logic.
*/
static void *faultsimMalloc(void *pMem, sqlite4_size_t n){
  void *p = 0;
  assert( pMem==(void*)&memfault );
  if( !faultsimStep() ){
    p = memfault.m.xMalloc(memfault.m.pAppData, n);
  }
  return p;
}


/*
** A version of sqlite4_mem_methods.xRealloc() that includes fault simulation
** logic.
*/
static void *faultsimRealloc(void *pMem, void *pOld, sqlite4_size_t n){
  void *p = 0;
  assert( pMem==(void*)&memfault );
  if( !faultsimStep() ){
    p = memfault.m.xRealloc(memfault.m.pAppData, pOld, n);
  }
  return p;
}

/* 
** The following method calls are passed directly through to the underlying
** malloc system:
................................................................................
**     xFree
**     xSize
**     xInit
**     xShutdown
*/
static void faultsimFree(void *pMem, void *p){
  assert( pMem==(void*)&memfault );
  memfault.m.xFree(memfault.m.pAppData, p);
}
static sqlite4_size_t faultsimSize(void *pMem, void *p){
  assert( pMem==(void*)&memfault );
  return memfault.m.xSize(memfault.m.pAppData, p);
}
static int faultsimInit(void *pMem){
  return memfault.m.xInit(memfault.m.pAppData);
}
static void faultsimShutdown(void *pMem){
  memfault.m.xShutdown(memfault.m.pAppData);
}

/*
** This routine configures the malloc failure simulation.  After
** calling this routine, the next nDelay mallocs will succeed, followed
** by a block of nRepeat failures, after which malloc() calls will begin
** to succeed again.
................................................................................
    faultsimFree,                     /* xFree */
    faultsimRealloc,                  /* xRealloc */
    faultsimSize,                     /* xSize */
    faultsimInit,                     /* xInit */
    faultsimShutdown,                 /* xShutdown */
    faultsimBeginBenign,              /* xBeginBenign */
    faultsimEndBenign,                /* xEndBenign */
    (void*)&memfault                  /* pAppData */
  };
  int rc;

  install = (install ? 1 : 0);
  assert(memfault.isInstalled==1 || memfault.isInstalled==0);

  if( install==memfault.isInstalled ){
................................................................................
  if( install ){
    sqlite4_initialize(0);
    rc = sqlite4_env_config(0, SQLITE_ENVCONFIG_GETMALLOC, &memfault.m);
    assert(memfault.m.xMalloc);
    if( rc==SQLITE_OK ){
      rc = sqlite4_env_config(0, SQLITE_ENVCONFIG_MALLOC, &m);
    }
    sqlite4_test_control(SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, 
        faultsimBeginBenign, faultsimEndBenign
    );
  }else{
    sqlite4_mem_methods m;
    assert(memfault.m.xMalloc);

    /* One should be able to reset the default memory allocator by storing
    ** a zeroed allocator then calling GETMALLOC. */
    memset(&m, 0, sizeof(m));
    sqlite4_env_config(0, SQLITE_ENVCONFIG_MALLOC, &m);
    sqlite4_env_config(0, SQLITE_ENVCONFIG_GETMALLOC, &m);
    assert( memcmp(&m, &memfault.m, sizeof(m))==0 );

    rc = sqlite4_env_config(0, SQLITE_ENVCONFIG_MALLOC, &memfault.m);
    sqlite4_test_control(SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS, 0, 0);
  }

  if( rc==SQLITE_OK ){
    memfault.isInstalled = 1;
  }
  return rc;
}







|













|







 







|



|


|


|







 







|







 







<
<
<












<







71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
...
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
...
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
...
205
206
207
208
209
210
211



212
213
214
215
216
217
218
219
220
221
222
223

224
225
226
227
228
229
230
** A version of sqlite4_mem_methods.xMalloc() that includes fault simulation
** logic.
*/
static void *faultsimMalloc(void *pMem, sqlite4_size_t n){
  void *p = 0;
  assert( pMem==(void*)&memfault );
  if( !faultsimStep() ){
    p = memfault.m.xMalloc(memfault.m.pMemEnv, n);
  }
  return p;
}


/*
** A version of sqlite4_mem_methods.xRealloc() that includes fault simulation
** logic.
*/
static void *faultsimRealloc(void *pMem, void *pOld, sqlite4_size_t n){
  void *p = 0;
  assert( pMem==(void*)&memfault );
  if( !faultsimStep() ){
    p = memfault.m.xRealloc(memfault.m.pMemEnv, pOld, n);
  }
  return p;
}

/* 
** The following method calls are passed directly through to the underlying
** malloc system:
................................................................................
**     xFree
**     xSize
**     xInit
**     xShutdown
*/
static void faultsimFree(void *pMem, void *p){
  assert( pMem==(void*)&memfault );
  memfault.m.xFree(memfault.m.pMemEnv, p);
}
static sqlite4_size_t faultsimSize(void *pMem, void *p){
  assert( pMem==(void*)&memfault );
  return memfault.m.xSize(memfault.m.pMemEnv, p);
}
static int faultsimInit(void *pMem){
  return memfault.m.xInit(memfault.m.pMemEnv);
}
static void faultsimShutdown(void *pMem){
  memfault.m.xShutdown(memfault.m.pMemEnv);
}

/*
** This routine configures the malloc failure simulation.  After
** calling this routine, the next nDelay mallocs will succeed, followed
** by a block of nRepeat failures, after which malloc() calls will begin
** to succeed again.
................................................................................
    faultsimFree,                     /* xFree */
    faultsimRealloc,                  /* xRealloc */
    faultsimSize,                     /* xSize */
    faultsimInit,                     /* xInit */
    faultsimShutdown,                 /* xShutdown */
    faultsimBeginBenign,              /* xBeginBenign */
    faultsimEndBenign,                /* xEndBenign */
    (void*)&memfault                  /* pMemEnv */
  };
  int rc;

  install = (install ? 1 : 0);
  assert(memfault.isInstalled==1 || memfault.isInstalled==0);

  if( install==memfault.isInstalled ){
................................................................................
  if( install ){
    sqlite4_initialize(0);
    rc = sqlite4_env_config(0, SQLITE_ENVCONFIG_GETMALLOC, &memfault.m);
    assert(memfault.m.xMalloc);
    if( rc==SQLITE_OK ){
      rc = sqlite4_env_config(0, SQLITE_ENVCONFIG_MALLOC, &m);
    }



  }else{
    sqlite4_mem_methods m;
    assert(memfault.m.xMalloc);

    /* One should be able to reset the default memory allocator by storing
    ** a zeroed allocator then calling GETMALLOC. */
    memset(&m, 0, sizeof(m));
    sqlite4_env_config(0, SQLITE_ENVCONFIG_MALLOC, &m);
    sqlite4_env_config(0, SQLITE_ENVCONFIG_GETMALLOC, &m);
    assert( memcmp(&m, &memfault.m, sizeof(m))==0 );

    rc = sqlite4_env_config(0, SQLITE_ENVCONFIG_MALLOC, &memfault.m);

  }

  if( rc==SQLITE_OK ){
    memfault.isInstalled = 1;
  }
  return rc;
}

Changes to test/test_mutex.c.

19
20
21
22
23
24
25
26

27
28
29

30
31
32
33
34
35
36
37
38
39
40
41
42
43

44
45
46
47
48

49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91

92
93
94

95
96
97
98
99
100

101
102
103
104
105
106
107
108
109
110
111

112
113
114
115
116
117
118
119
120

121
122
123
124
125
126
127
128
129

130
131
132
133
134
135
136
...
190
191
192
193
194
195
196
197

198
199
200
201
202
203
204
...
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
#include <assert.h>
#include <string.h>

/* defined in test1.c */
const char *sqlite4TestErrorName(int);

/* A countable mutex */
struct sqlite4_mutex {

  sqlite4_mutex *pReal;
  int eType;
};


/* State variables */
static struct test_mutex_globals {
  int isInstalled;              /* True if installed */
  int disableInit;              /* True to cause sqlite4_initalize() to fail */
  int disableTry;               /* True to force sqlite4_mutex_try() to fail */
  int isInit;                   /* True if initialized */
  sqlite4_mutex_methods m;      /* Interface to "real" mutex system */
  int aCounter[8];              /* Number of grabs of each type of mutex */
  sqlite4_mutex aStatic[6];     /* The six static mutexes */
} g = {0};

/* Return true if the countable mutex is currently held */
static int counterMutexHeld(sqlite4_mutex *p){

  return g.m.xMutexHeld(p->pReal);
}

/* Return true if the countable mutex is not currently held */
static int counterMutexNotheld(sqlite4_mutex *p){

  return g.m.xMutexNotheld(p->pReal);
}

/* Initialize the countable mutex interface
** Or, if g.disableInit is non-zero, then do not initialize but instead
** return the value of g.disableInit as the result code.  This can be used
** to simulate an initialization failure.
*/
static int counterMutexInit(void){ 
  int rc;
  if( g.disableInit ) return g.disableInit;
  rc = g.m.xMutexInit();
  g.isInit = 1;
  return rc;
}

/*
** Uninitialize the mutex subsystem
*/
static int counterMutexEnd(void){ 
  g.isInit = 0;
  return g.m.xMutexEnd();
}

/*
** Allocate a countable mutex
*/
static sqlite4_mutex *counterMutexAlloc(int eType){
  sqlite4_mutex *pReal;
  sqlite4_mutex *pRet = 0;

  assert( g.isInit );
  assert(eType<8 && eType>=0);

  pReal = g.m.xMutexAlloc(eType);
  if( !pReal ) return 0;

  if( eType==SQLITE_MUTEX_FAST || eType==SQLITE_MUTEX_RECURSIVE ){
    pRet = (sqlite4_mutex *)malloc(sizeof(sqlite4_mutex));
  }else{
    pRet = &g.aStatic[eType-2];
  }


  pRet->eType = eType;
  pRet->pReal = pReal;
  return pRet;

}

/*
** Free a countable mutex
*/
static void counterMutexFree(sqlite4_mutex *p){

  assert( g.isInit );
  g.m.xMutexFree(p->pReal);
  if( p->eType==SQLITE_MUTEX_FAST || p->eType==SQLITE_MUTEX_RECURSIVE ){
    free(p);
  }
}

/*
** Enter a countable mutex.  Block until entry is safe.
*/
static void counterMutexEnter(sqlite4_mutex *p){

  assert( g.isInit );
  g.aCounter[p->eType]++;
  g.m.xMutexEnter(p->pReal);
}

/*
** Try to enter a mutex.  Return true on success.
*/
static int counterMutexTry(sqlite4_mutex *p){

  assert( g.isInit );
  g.aCounter[p->eType]++;
  if( g.disableTry ) return SQLITE_BUSY;
  return g.m.xMutexTry(p->pReal);
}

/* Leave a mutex
*/
static void counterMutexLeave(sqlite4_mutex *p){

  assert( g.isInit );
  g.m.xMutexLeave(p->pReal);
}

/*
** sqlite4_shutdown
*/
................................................................................
    counterMutexEnd,
    counterMutexAlloc,
    counterMutexFree,
    counterMutexEnter,
    counterMutexTry,
    counterMutexLeave,
    counterMutexHeld,
    counterMutexNotheld

  };

  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "BOOLEAN");
    return TCL_ERROR;
  }
  if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[1], &isInstall) ){
................................................................................
static int test_alloc_mutex(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
#if SQLITE_THREADSAFE
  sqlite4_mutex *p = sqlite4_mutex_alloc(SQLITE_MUTEX_FAST);
  char zBuf[100];
  sqlite4_mutex_free(p);
  sqlite4_snprintf(zBuf, sizeof(zBuf), "%p", p);
  Tcl_AppendResult(interp, zBuf, (char*)0);
#endif
  return TCL_OK;
}







|
>


<
>









<



|
>




|
>








|


|







|

|





|

|




|

<
<
<
<
<
<
<
>


<
>





|
>










|
>








|
>








|
>







 







|
>







 







|







19
20
21
22
23
24
25
26
27
28
29

30
31
32
33
34
35
36
37
38
39

40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86







87
88
89

90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
...
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
...
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
#include <assert.h>
#include <string.h>

/* defined in test1.c */
const char *sqlite4TestErrorName(int);

/* A countable mutex */
typedef struct sqlite4CounterMutex {
  sqlite4_mutex base;      /* Base class.  Must be first */
  sqlite4_mutex *pReal;
  int eType;

} sqlite4CounterMutex;

/* State variables */
static struct test_mutex_globals {
  int isInstalled;              /* True if installed */
  int disableInit;              /* True to cause sqlite4_initalize() to fail */
  int disableTry;               /* True to force sqlite4_mutex_try() to fail */
  int isInit;                   /* True if initialized */
  sqlite4_mutex_methods m;      /* Interface to "real" mutex system */
  int aCounter[8];              /* Number of grabs of each type of mutex */

} g = {0};

/* Return true if the countable mutex is currently held */
static int counterMutexHeld(sqlite4_mutex *pMutex){
  sqlite4CounterMutex *p = (sqlite4CounterMutex*)pMutex;
  return g.m.xMutexHeld(p->pReal);
}

/* Return true if the countable mutex is not currently held */
static int counterMutexNotheld(sqlite4_mutex *pMutex){
  sqlite4CounterMutex *p = (sqlite4CounterMutex*)pMutex;
  return g.m.xMutexNotheld(p->pReal);
}

/* Initialize the countable mutex interface
** Or, if g.disableInit is non-zero, then do not initialize but instead
** return the value of g.disableInit as the result code.  This can be used
** to simulate an initialization failure.
*/
static int counterMutexInit(void *p){ 
  int rc;
  if( g.disableInit ) return g.disableInit;
  rc = g.m.xMutexInit(p);
  g.isInit = 1;
  return rc;
}

/*
** Uninitialize the mutex subsystem
*/
static int counterMutexEnd(void *p){ 
  g.isInit = 0;
  return g.m.xMutexEnd(p);
}

/*
** Allocate a countable mutex
*/
static sqlite4_mutex *counterMutexAlloc(void *pMutexEnv, int eType){
  sqlite4_mutex *pReal;
  sqlite4CounterMutex *pRet = 0;

  assert( g.isInit );
  assert(eType<8 && eType>=0);

  pReal = g.m.xMutexAlloc(g.m.pMutexEnv, eType);
  if( !pReal ) return 0;







  pRet = (sqlite4CounterMutex *)malloc(sizeof(*pRet));
  pRet->eType = eType;
  pRet->pReal = pReal;

  return (sqlite4_mutex*)pRet;
}

/*
** Free a countable mutex
*/
static void counterMutexFree(sqlite4_mutex *pMutex){
  sqlite4CounterMutex *p = (sqlite4CounterMutex*)pMutex;
  assert( g.isInit );
  g.m.xMutexFree(p->pReal);
  if( p->eType==SQLITE_MUTEX_FAST || p->eType==SQLITE_MUTEX_RECURSIVE ){
    free(p);
  }
}

/*
** Enter a countable mutex.  Block until entry is safe.
*/
static void counterMutexEnter(sqlite4_mutex *pMutex){
  sqlite4CounterMutex *p = (sqlite4CounterMutex*)pMutex;
  assert( g.isInit );
  g.aCounter[p->eType]++;
  g.m.xMutexEnter(p->pReal);
}

/*
** Try to enter a mutex.  Return true on success.
*/
static int counterMutexTry(sqlite4_mutex *pMutex){
  sqlite4CounterMutex *p = (sqlite4CounterMutex*)pMutex;
  assert( g.isInit );
  g.aCounter[p->eType]++;
  if( g.disableTry ) return SQLITE_BUSY;
  return g.m.xMutexTry(p->pReal);
}

/* Leave a mutex
*/
static void counterMutexLeave(sqlite4_mutex *pMutex){
  sqlite4CounterMutex *p = (sqlite4CounterMutex*)pMutex;
  assert( g.isInit );
  g.m.xMutexLeave(p->pReal);
}

/*
** sqlite4_shutdown
*/
................................................................................
    counterMutexEnd,
    counterMutexAlloc,
    counterMutexFree,
    counterMutexEnter,
    counterMutexTry,
    counterMutexLeave,
    counterMutexHeld,
    counterMutexNotheld, 
    0
  };

  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 1, objv, "BOOLEAN");
    return TCL_ERROR;
  }
  if( TCL_OK!=Tcl_GetBooleanFromObj(interp, objv[1], &isInstall) ){
................................................................................
static int test_alloc_mutex(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
#if SQLITE_THREADSAFE
  sqlite4_mutex *p = sqlite4_mutex_alloc(0, SQLITE_MUTEX_FAST);
  char zBuf[100];
  sqlite4_mutex_free(p);
  sqlite4_snprintf(zBuf, sizeof(zBuf), "%p", p);
  Tcl_AppendResult(interp, zBuf, (char*)0);
#endif
  return TCL_OK;
}

Changes to test/test_storage2.c.

239
240
241
242
243
244
245


246
247
248
249
250
251
252
...
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
  KVStore **ppKVStore,
  const char *zName,
  unsigned openFlags
){

  /* Virtual methods for an LSM data store */
  static const KVStoreMethods kvwrapMethods = {


    kvwrapReplace,
    kvwrapOpenCursor,
    kvwrapSeek,
    kvwrapNextEntry,
    kvwrapPrevEntry,
    kvwrapDelete,
    kvwrapKey,
................................................................................
static int kvwrap_install_cmd(Tcl_Interp *interp, int objc, Tcl_Obj **objv){
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 2, objv, "");
    return TCL_ERROR;
  }

  if( kvwg.xFactory==0 ){
    sqlite4_config(0, SQLITE_CONFIG_GET_KVFACTORY, &kvwg.xFactory);
    sqlite4_config(0, SQLITE_CONFIG_SET_KVFACTORY, newFileStorage);
  }
  return TCL_OK;
}

static int kvwrap_seek_cmd(Tcl_Interp *interp, int objc, Tcl_Obj **objv){
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 2, objv, "");







>
>







 







|
|







239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
...
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
  KVStore **ppKVStore,
  const char *zName,
  unsigned openFlags
){

  /* Virtual methods for an LSM data store */
  static const KVStoreMethods kvwrapMethods = {
    1,
    sizeof(KVStoreMethods),
    kvwrapReplace,
    kvwrapOpenCursor,
    kvwrapSeek,
    kvwrapNextEntry,
    kvwrapPrevEntry,
    kvwrapDelete,
    kvwrapKey,
................................................................................
static int kvwrap_install_cmd(Tcl_Interp *interp, int objc, Tcl_Obj **objv){
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 2, objv, "");
    return TCL_ERROR;
  }

  if( kvwg.xFactory==0 ){
    sqlite4_env_config(0, SQLITE_ENVCONFIG_KVSTORE_GET, "main", &kvwg.xFactory);
    sqlite4_env_config(0, SQLITE_ENVCONFIG_KVSTORE_PUSH, "main",newFileStorage);
  }
  return TCL_OK;
}

static int kvwrap_seek_cmd(Tcl_Interp *interp, int objc, Tcl_Obj **objv){
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 2, objv, "");

Changes to test/tester.tcl.

1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
....
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471

  # TEMPORARY: For 3.5.9, disable testing of extended result codes. There are
  # a couple of obscure IO errors that do not return them.
  set ::ioerropts(-erc) 0

  set ::go 1
  #reset_prng_state
  save_prng_state
  for {set n $::ioerropts(-start)} {$::go} {incr n} {
    set ::TN $n
    incr ::ioerropts(-count) -1
    if {$::ioerropts(-count)<0} break
 
    # Skip this IO error if it was specified with the "-exclude" option.
    if {[info exists ::ioerropts(-exclude)]} {
................................................................................
    if {$tail != $::G(start:file) && $tail!="$::G(start:file).test"} return
    unset ::G(start:file)
  }

  # Run the test script in a slave interpreter.
  #
  unset -nocomplain ::run_thread_tests_called
  reset_prng_state
  set time [time { slave_test_script [list source $zFile] }]
  set ms [expr [lindex $time 0] / 1000]

  # Add some info to the output.
  #
  puts "Time: $tail $ms ms"
  show_memstats







|







 







|







1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
....
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471

  # TEMPORARY: For 3.5.9, disable testing of extended result codes. There are
  # a couple of obscure IO errors that do not return them.
  set ::ioerropts(-erc) 0

  set ::go 1
  #reset_prng_state
  #save_prng_state
  for {set n $::ioerropts(-start)} {$::go} {incr n} {
    set ::TN $n
    incr ::ioerropts(-count) -1
    if {$::ioerropts(-count)<0} break
 
    # Skip this IO error if it was specified with the "-exclude" option.
    if {[info exists ::ioerropts(-exclude)]} {
................................................................................
    if {$tail != $::G(start:file) && $tail!="$::G(start:file).test"} return
    unset ::G(start:file)
  }

  # Run the test script in a slave interpreter.
  #
  unset -nocomplain ::run_thread_tests_called
  #reset_prng_state
  set time [time { slave_test_script [list source $zFile] }]
  set ms [expr [lindex $time 0] / 1000]

  # Add some info to the output.
  #
  puts "Time: $tail $ms ms"
  show_memstats

Changes to test/where.test.

12
13
14
15
16
17
18




19
20
21
22
23
24
25
# focus of this file is testing the use of indices in WHERE clases.
#
# $Id: where.test,v 1.50 2008/11/03 09:06:06 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl





# Build some test data
#
do_test where-1.0 {
  execsql {
    CREATE TABLE t1(w int, x int, y int);
    CREATE TABLE t2(p int, q int, r int, s int);
  }







>
>
>
>







12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# focus of this file is testing the use of indices in WHERE clases.
#
# $Id: where.test,v 1.50 2008/11/03 09:06:06 danielk1977 Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

db close
kvwrap install
sqlite4 db test.db

# Build some test data
#
do_test where-1.0 {
  execsql {
    CREATE TABLE t1(w int, x int, y int);
    CREATE TABLE t2(p int, q int, r int, s int);
  }

Changes to www/design.wiki.

77
78
79
80
81
82
83




84
85
86
87
88
89
90
...
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
to "<tt>sqlite4_</tt>".  Legacy and deprecated interfaces in SQLite3 have
been removed from SQLite4.  There are additional parameters to some routines,
and on occasion the parameters are altered slightly or reordered.  Some of
the interface names have been modified to be more rational.  But on the 
whole, the programming interface for SQLite4 is remarkably similar to
SQLite3, and porting an application from SQLite3 to SQLite4 will usually
involve only an hour or two search-and-replace.</p>





<h1>3.0 Key Changes In SQLite4</h1>

<h2>3.1 The Run-Time Environment Object</h2>

<p>Some of the interfaces in SQLite4 take a new (added) first parameter
which is a pointer to an <tt>sqlite4_env</tt>
................................................................................
<li> allocate, resize, and free heap memory,
<li> access and control the underlying key/value storage engines,
<li> initialize the built-in PRNG with a high-quality random seed,
<li> acquire the current time and date and the local timezone,
<li> record error log message.
</ul>

<p>Builds of SQLite4 for standard platforms (windows and unix) contain
a global sqlite4_env that is normally appropriate for use on that platform.
Any interface routine that requires a pointer to an sqlite4_env object
will use the global default sqlite4_env object if a NULL pointer is passed
on its sqlite4_env parameter.  Most applications never need to pass anything
other than this NULL pointer.  However, some applications may want to have two
or more instances of SQLite4 running in the same address space where each
instance uses different mutex primitives, a different heap, different
date/time functions, etc.  SQLite4 accommodates this need by allowing each







>
>
>
>







 







|
|







77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
...
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
to "<tt>sqlite4_</tt>".  Legacy and deprecated interfaces in SQLite3 have
been removed from SQLite4.  There are additional parameters to some routines,
and on occasion the parameters are altered slightly or reordered.  Some of
the interface names have been modified to be more rational.  But on the 
whole, the programming interface for SQLite4 is remarkably similar to
SQLite3, and porting an application from SQLite3 to SQLite4 will usually
involve only an hour or two search-and-replace.</p>

<p>SQLite3 and SQLite4 share no symbols in common, so it is possible to
link both SQLite3 and SQLite4 into the same process and use them both at
the same time.</p>

<h1>3.0 Key Changes In SQLite4</h1>

<h2>3.1 The Run-Time Environment Object</h2>

<p>Some of the interfaces in SQLite4 take a new (added) first parameter
which is a pointer to an <tt>sqlite4_env</tt>
................................................................................
<li> allocate, resize, and free heap memory,
<li> access and control the underlying key/value storage engines,
<li> initialize the built-in PRNG with a high-quality random seed,
<li> acquire the current time and date and the local timezone,
<li> record error log message.
</ul>

<p>Builds of SQLite4 for standard platforms (windows and unix) contain a global
sqlite4_env object that is normally appropriate for use on that platform.
Any interface routine that requires a pointer to an sqlite4_env object
will use the global default sqlite4_env object if a NULL pointer is passed
on its sqlite4_env parameter.  Most applications never need to pass anything
other than this NULL pointer.  However, some applications may want to have two
or more instances of SQLite4 running in the same address space where each
instance uses different mutex primitives, a different heap, different
date/time functions, etc.  SQLite4 accommodates this need by allowing each

Changes to www/env.wiki.

13
14
15
16
17
18
19
20
21
22
23
24

25
26
27
28
29
30

31
32
33
34
35
36
37
..
39
40
41
42
43
44
45
46

47
48
49

50
51
52
53
54
55
56
57
58
59
60
61
Basically, the sqlite4_env object defines how SQLite4 interacts with the
rest of the application.

Builds for unix and windows come with a built-in sqlite4_env object that is
appropriate for most applications.  And so in most cases, the programmer never
has to think about the run-time environment; the default setup will work great.
But some speciallized applications may want to alter the environment to 
accommodate their specialized needs.  For example, the application might want
to use a memory allocator other than the default malloc()/free()/realloc()
from the standard library.  Or, the application might want to define an
alternative key/value storage engine to use on the backend of SQLite4.
In these cases, the application can create its own sqlite4_env object or

objects and use them in place of the default.

An sqlite4_env object is not constant.
It contains state information, such as the
current state of the PRNG and the state of various mutexes.  
SQLite4 contains no global variables, except for the default sqlite4_env

object.  All global state is contained within sqlite4_env objects.

An sqlite4_env object is opaque; its internal structure is not visible to the
application.  The content of an sqlite4_env object is controlled indirectly
through methods, such as sqlite4_env_config().

<h2>Methods Of The Run-time Environment Object</h2>
................................................................................
A number of interfaces in SQLite4 require a pointer to an sqlite4_env object
as their first parameter.  Think of these interfaces as methods of the
sqlite4_env object.  Examples include (but are not limited to):

<blockquote><pre>
int sqlite4_env_config(sqlite4_env*, int op, ...);
int sqlite4_open(sqlite4_env*, const char *zFilename, sqlite4 **, ...);
void *sqlite4_malloc(sqlite4_env*, size_t);

void sqlite4_free(sqlite4_env*, void*);
char *sqlite4_mprintf(sqlite4_env*, const char *zFormat, ...);
int sqlite4_randomness(sqlite4_env*, int amt, unsigned char *buf);

</pre></blockquote>

Any interface that takes a pointer to an sqlite4_env object will accept a
NULL pointer.  When a NULL pointer is seen on an sqlite4_env method, the
default sqlite4_env object is used.  

<h2>Managing Run-time Environment Objects</h2>

The default run-time environment can be obtained using the following
interface:

<blockquote><pre>







|



|
>
|




|
>







 







|
>



>




|







13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
..
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
Basically, the sqlite4_env object defines how SQLite4 interacts with the
rest of the application.

Builds for unix and windows come with a built-in sqlite4_env object that is
appropriate for most applications.  And so in most cases, the programmer never
has to think about the run-time environment; the default setup will work great.
But some speciallized applications may want to alter the environment to 
accommodate their particular needs.  For example, the application might want
to use a memory allocator other than the default malloc()/free()/realloc()
from the standard library.  Or, the application might want to define an
alternative key/value storage engine to use on the backend of SQLite4.
In these cases, the application can either customize the built-in default
sqlite4_env object, or create its own sqlite4_env objects to use in place
of the default.

An sqlite4_env object is not constant.
It contains state information, such as the
current state of the PRNG and the state of various mutexes.  
SQLite4 contains no global variables, except for the single
built-in default sqlite4_env
object.  All global state is contained within sqlite4_env objects.

An sqlite4_env object is opaque; its internal structure is not visible to the
application.  The content of an sqlite4_env object is controlled indirectly
through methods, such as sqlite4_env_config().

<h2>Methods Of The Run-time Environment Object</h2>
................................................................................
A number of interfaces in SQLite4 require a pointer to an sqlite4_env object
as their first parameter.  Think of these interfaces as methods of the
sqlite4_env object.  Examples include (but are not limited to):

<blockquote><pre>
int sqlite4_env_config(sqlite4_env*, int op, ...);
int sqlite4_open(sqlite4_env*, const char *zFilename, sqlite4 **, ...);
void *sqlite4_malloc(sqlite4_env*, sqlite4_size_t);
void *sqlite4_realloc(sqlite4_env*, void*, sqlite4_size_t);
void sqlite4_free(sqlite4_env*, void*);
char *sqlite4_mprintf(sqlite4_env*, const char *zFormat, ...);
int sqlite4_randomness(sqlite4_env*, int amt, unsigned char *buf);
void sqlite4_log(sqlite4_env*, int errCode, const char *zFormat, ...);
</pre></blockquote>

Any interface that takes a pointer to an sqlite4_env object will accept a
NULL pointer.  When a NULL pointer is seen on an sqlite4_env method, the
built-in default sqlite4_env object is used.  

<h2>Managing Run-time Environment Objects</h2>

The default run-time environment can be obtained using the following
interface:

<blockquote><pre>

Changes to www/index.wiki.

3
4
5
6
7
8
9

  *  [./design.wiki | The Design Of SQLite4]
  *  [./env.wiki | The Run-time Environment Object]
  *  [./varint.wiki | The Varint format]
  *  [./data_encoding.wiki | The Data Encoding]
  *  [./key_encoding.wiki | The Key Encoding]
  *  [./decimal.wiki | Internal representation of numeric values]
  *  [./porting.wiki | Porting an app from SQLite3 to SQLite4]








>
3
4
5
6
7
8
9
10
  *  [./design.wiki | The Design Of SQLite4]
  *  [./env.wiki | The Run-time Environment Object]
  *  [./varint.wiki | The Varint format]
  *  [./data_encoding.wiki | The Data Encoding]
  *  [./key_encoding.wiki | The Key Encoding]
  *  [./decimal.wiki | Internal representation of numeric values]
  *  [./porting.wiki | Porting an app from SQLite3 to SQLite4]
  *  [./storage.wiki | How to create a new storage engine]

Changes to www/porting.wiki.

12
13
14
15
16
17
18


19
20
21
22
23
24
25
26
27
<ul>
<li> sqlite4_open()
<li> sqlite4_malloc()
<li> sqlite4_realloc()
<li> sqlite4_free()
<li> sqlite4_mprintf()
<li> sqlite4_vmprintf()


</ul>

<li><p>Check all uses of sqlite4_snprintf() and sqlite4_vnsprintf() for
    the new function signature:
<ul>
<li>The order of the first two arguments is reversed
<li>Both routines return the length of the result string.
</ul>
</ul>







>
>









12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<ul>
<li> sqlite4_open()
<li> sqlite4_malloc()
<li> sqlite4_realloc()
<li> sqlite4_free()
<li> sqlite4_mprintf()
<li> sqlite4_vmprintf()
<li> sqlite4_log()
<li> sqlite4_randomness()
</ul>

<li><p>Check all uses of sqlite4_snprintf() and sqlite4_vnsprintf() for
    the new function signature:
<ul>
<li>The order of the first two arguments is reversed
<li>Both routines return the length of the result string.
</ul>
</ul>

Added www/storage.wiki.





































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
<title>Pluggable Storage Engine</title>

<h2>Overview</h2>

SQLite4 works with run-time interchangeable storage engines with the
following properties:

  *  The storage engine works with key/value pairs where both the
     key and the value are byte arrays of arbitrary length and with no
     restrictions on content.

  *  All keys are unique.

  *  Keys sort in lexicographical order (as if sorted using the
     memcmp() library function).  When one key is a prefix of another,
     the shorter key occurs first.

  *  Transaction commit and rollback is handled by the storage engine.

SQLite4 comes with two built-in storage engines.  A log-structured merge-tree
(LSM) storage engine is used for persistent on-disk databases and an
in-memory binary tree storage engine is used for TEMP databases.
Future versions of SQLite4 might add other built-in storage engines.

Applicates can add new storage engines to SQLite4 at run-time.  The
purpose of this document is to describe how that is done.

<h2>Adding A New Storage Engine</h2>

Each storage engine implements a "factory function".  The factory function
creates an object that defines a single connection to a single database
file.  The signature of the factory function is as follows:

<blockquote><pre>
int storageEngineFactor(
  sqlite4_env *pEnv,            /* The run-time environment */
  sqlite4_kv_store **ppResult,  /* OUT: storage engine object written here */
  const char *zName,            /* Name of the database file */
  unsigned flags                /* Flags */
);
</pre></blockquote>

SQLite4 will invoke the factory function whenever it needs to open a
connection to a database file.  The first argument is the
[./env.wiki | run-time environment] in use by the database connection.
The third argument is the name of the database file to be opened.
The fourth argument is zero or more boolean flags that are hints to the
factory telling it how the database will be used.  The factory should
create a new sqlite4_kv_storage object describing the connection to the
database file and return a pointer to that object in the address
specified by 2nd argument, then return SQLITE_OK.  Or, if something goes
wrong, the factory should return an appropriate error code.

<font color="blue"><i>
We need to add some mechanism for the factory to return detailed
error information back up to the caller.
</i></font>

To add a new storage engine to SQLite4, use the sqlite4_env_config()
interface to register the factory function for the storage engine with
the run-time environment that will be using the storage engine.  
For example:

<blockquote><pre>
sqlite4_env_config(pEnv, SQLITE_ENVCONFIG_PUSH_KVSTORE,
                   "main", &exampleStorageEngine);
</pre></blockquote>

The example above adds the factory "exampleStorageEngine()" to the 
run-time environment as the "main" storage engine.  The "main" storage
engine is used by default for persistent databases.  The "temp" storage
engine is used by default for transient and "TEMP" databases.  Storage
engines with other names can be registered and used by specifying the
storage engine name in the "kv=" query parameter of the URI passed to
sqlite4_open().

Storage engines stack.  The built-in includes two storage engines for
"main" and "temp": the LSM and binary-tree storage engines, respectively.
If you push a new "main" storage engine, the new one will take precedence
over the built-in storage engine.  Later, you can call sqlite4_env_config()
with the SQLITE_ENVCONFIG_POP_KVSTORE argument to remove the added storage
engine and restore the built-in LSM storage engine as the "main" storage
engine.  The built-in storage engines cannot be popped from the stack.

The SQLITE_ENVCONFIG_GET_KVSTORE operator for sqlite3_env_config() is
available for querying the current storage engines.

<h2>Storage Engine Implementation</h2>

The sqlite4_kvstore object that the factory function returns has the
following basis:

<blockquote><pre>
struct sqlite4_kvstore {
  const struct sqlite4_kv_methods *pStoreVfunc;  /* Methods */
  sqlite4_env *pEnv;                      /* Runtime environment for kvstore */
  int iTransLevel;                        /* Current transaction level */
  unsigned kvId;                          /* Unique ID used for tracing */
  unsigned fTrace;                        /* True to enable tracing */
  char zKVName<nowiki>[12]</nowiki>;                       /* Used for debugging */
  /* Subclasses will typically append additional fields */
};
</pre></blockquote>

Useful subclasses of the sqlite4_kvstore base class will almost
certainly want to add additional fields at after the basis.
The most interesting part of the sqlite4_kvstore object is surely
the virtual method table, which looks like this:

<blockquote><pre>
struct sqlite4_kv_methods {
  int iVersion;
  int szSelf;
  int (*xReplace)(
         sqlite4_kvstore*,
         const unsigned char *pKey, sqlite4_kvsize nKey,
         const unsigned char *pData, sqlite4_kvsize nData);
  int (*xOpenCursor)(sqlite4_kvstore*, sqlite4_kvcursor**);
  int (*xSeek)(sqlite4_kvcursor*,
               const unsigned char *pKey, sqlite4_kvsize nKey, int dir);
  int (*xNext)(sqlite4_kvcursor*);
  int (*xPrev)(sqlite4_kvcursor*);
  int (*xDelete)(sqlite4_kvcursor*);
  int (*xKey)(sqlite4_kvcursor*,
              const unsigned char **ppKey, sqlite4_kvsize *pnKey);
  int (*xData)(sqlite4_kvcursor*, sqlite4_kvsize ofst, sqlite4_kvsize n,
               const unsigned char **ppData, sqlite4_kvsize *pnData);
  int (*xReset)(sqlite4_kvcursor*);
  int (*xCloseCursor)(sqlite4_kvcursor*);
  int (*xBegin)(sqlite4_kvstore*, int);
  int (*xCommitPhaseOne)(sqlite4_kvstore*, int);
  int (*xCommitPhaseTwo)(sqlite4_kvstore*, int);
  int (*xRollback)(sqlite4_kvstore*, int);
  int (*xRevert)(sqlite4_kvstore*, int);
  int (*xClose)(sqlite4_kvstore*);
  int (*xControl)(sqlite4_kvstore*, int, void*);
};
</pre></blockquote>

The storage engine implementation will need to provide implementations for
all of the methods in the sqlite4_kv_methods object.  Note that the first
two fields, iVersion and szSelf, are present to support future extensions.
The iVersion field should always currently be 1, but might be larger for
later enhanced versions.  And the szSelf field should be equal to
sizeof(sqlite4_kv_methods).

Search operations involve a cursor object whose basis is the following:

<blockquote><pre>
struct sqlite4_kvcursor {
  sqlite4_kvstore *pStore;                /* The owner of this cursor */
  const struct sqlite4_kv_methods *pStoreVfunc;  /* Methods */
  sqlite4_env *pEnv;                      /* Runtime environment  */
  int iTransLevel;                        /* Current transaction level */
  unsigned curId;                         /* Unique ID for tracing */
  unsigned fTrace;                        /* True to enable tracing */
  /* Subclasses will typically add additional fields */
};
</pre></blockquote>

As before, actual implementations will more than likely want to extend
this object by adding additional fields onto the end.

<h2>Storage Engine Methods</h2>

SQLite invokes the xBegin, xCommit, and xRollback methods change
the transaction level of the storage engine.  The transaction level
is a non-negative integer that is initialized to zero.  The transaction
level must be at least 1 in order for content to be read.  The
transaction level must be at least 2 for content to be modified.

The xBegin method increases transaction level.  The increase may be no
more than 1 unless the transaction level is initially 0 in which case
it can be increased immediately to 2.  Increasing the transaction level
to 1 or more makes a "snapshot" of the database file such that changes
made by other connections are not visible.  An xBegin call may fail
with SQLITE_BUSY if the initial transaction level is 0 or 1.

A read-only database will fail an attempt to increase xBegin above 1.  An
implementation that does not support nested transactions will fail any
attempt to increase the transaction level above 2.

The xCommitPhaseOne and xCommitPhaseTwo methods implement a 2-phase
commit that lowers the transaction level to the value given in the
second argument, making all the changes made at higher transaction levels
permanent.  A rollback is still possible following phase one.  If
possible, errors should be reported during phase one so that a
multiple-database transaction can still be rolled back if the
phase one fails on a different database.  Implementations that do not
support two-phase commit can implement xCommitPhaseOne as a no-op function
returning SQLITE_OK.

The xRollback method lowers the transaction level to the value given in
its argument and reverts or undoes all changes made at higher transaction
levels.  An xRollback to level N causes the database to revert to the state
it was in on the most recent xBegin to level N+1.

The xRevert(N) method causes the state of the database file to go back
to what it was immediately after the most recent xCommit(N).  Higher-level
subtransactions are cancelled.  This call is equivalent to xRollback(N-1)
followed by xBegin(N) but is atomic and might be more efficient.

The xReplace method replaces the value for an existing entry with the
given key, or creates a new entry with the given key and value if no
prior entry exists with the given key.  The key and value pointers passed
into xReplace belong to the caller and will likely be destroyed when the
call to xReplace returns so the xReplace routine must make its own
copy of that information.

A cursor is at all times pointing to ether an entry in the database or
to EOF.  EOF means "no entry".  Cursor operations other than xCloseCursor 
will fail if the transaction level is less than 1.

The xSeek method moves a cursor to an entry in the database that matches
the supplied key as closely as possible.  If the dir argument is 0, then
the match must be exact or else the seek fails and the cursor is left
pointing to EOF.  If dir is negative, then an exact match is
found if it is available, otherwise the cursor is positioned at the largest
entry that is less than the search key or to EOF if the store contains no
entry less than the search key.  If dir is positive, then an exist match
is found if it is available, otherwise the cursor is left pointing the
the smallest entry that is larger than the search key, or to EOF if there
are no entries larger than the search key.

The return code from xSeek might be one of the following:

   <b>SQLITE_OK</b> The cursor is left pointing to any entry that
                    exactly matchings the probe key.

   <b>SQLITE_INEXACT</b> The cursor is left pointing to the nearest entry
                    to the probe it could find, either before or after
                    the probe, according to the dir argument.

   <b>SQLITE_NOTFOUND</b> No suitable entry could be found.  Either dir==0 and
                    there was no exact match, or dir<0 and the probe is
                    smaller than every entry in the database, or dir>0 and
                    the probe is larger than every entry in the database.

xSeek might also return some error code like SQLITE_IOERR or
SQLITE_NOMEM.

The xNext method will only be called following an xSeek with a positive dir,
or another xNext.  The xPrev method will only be called following an xSeek
with a negative dir or another xPrev.  Both xNext and xPrev will return
SQLITE_OK on success and SQLITE_NOTFOUND if they run off the end of the
database.  Both routines might also return error codes such as
SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_NOMEM.

Values returned by xKey and xData must remain stable until
the next xSeek, xNext, xPrev, xReset, xDelete, or xCloseCursor on the same
cursor.  This is true even if the transaction level is reduced to zero,
or if the content of the entry is changed by xInsert, xDelete on a different
cursor, or xRollback.  The content returned by repeated calls to xKey and
xData is allowed (but is not required) to change if xInsert, xDelete, or
xRollback are invoked in between the calls, but the content returned by
every call must be stable until the cursor moves, or is reset or closed.
The cursor owns the values returned by xKey and xData and must take
responsiblity for freeing memory used to hold those values when appropriate.
If the SQLite core needs to keep a key or value beyond the time when it
is guaranteed to be stable, it will make its own copy.

The xDelete method deletes the entry that the cursor is currently
pointing at.  However, subsequent xNext or xPrev calls behave as if the
entries is not actually deleted until the cursor moves.  In other words
it is acceptable to xDelete an entry out from under a cursor.  Subsequent
xNext or xPrev calls on that cursor will work the same as if the entry
had not been deleted.  Two cursors can be pointing to the same entry and
one cursor can xDelete and the other cursor is expected to continue
functioning normally, including responding correctly to subsequent
xNext and xPrev calls.

<font color="blue"><i>
To be continued...
</i></font>