/ Check-in [b082538d]
Login
SQLite training in Houston TX on 2019-11-05 (details)
Part of the 2019 Tcl Conference

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

Overview
Comment:Improvements to the way out-of-memory conditions are handled, resulting in an almost 1% performance gain in the commmon case where OOM errors do not occur.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: b082538da774ac77f284fd7e22f9b1b9c2abc343
User & Date: drh 2016-02-05 14:11:12
Context
2016-02-05
16:46
From test scripts, remove stray "breakpoint" commands and blank lines at the ends of files. check-in: a6b35273 user: drh tags: trunk
14:34
Merge PRAGMA synchronous=EXTRA and OOM performance enhancements from trunk. check-in: 332c8036 user: drh tags: begin-concurrent
14:29
Merge OOM handling optimizations and PRAGMA synchronous=EXTRA as well as other enhancements from trunk. check-in: 201fcbee user: drh tags: apple-osx
14:15
Merge enhancements from trunk. check-in: a533608c user: drh tags: sessions
14:11
Improvements to the way out-of-memory conditions are handled, resulting in an almost 1% performance gain in the commmon case where OOM errors do not occur. check-in: b082538d user: drh tags: trunk
13:38
Add the slightly faster sqlite3DbMallocRawNN(db,n) routine for the majority cases where db is guaranteed to be not NULL. Closed-Leaf check-in: 0a802e96 user: drh tags: oom-handling
04:55
Improve ERRORLEVEL handling in the MSVC batch build tool sub-routine 'fn_UnsetVariable'. check-in: fe123ab4 user: mistachkin tags: trunk
Changes
Hide Diffs Side-by-Side Diffs Ignore Whitespace Patch

Changes to ext/misc/json1.c.

   339    339           jsonAppendString(p, z, n);
   340    340         }
   341    341         break;
   342    342       }
   343    343       default: {
   344    344         if( p->bErr==0 ){
   345    345           sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
   346         -        p->bErr = 1;
          346  +        p->bErr = 2;
   347    347           jsonReset(p);
   348    348         }
   349    349         break;
   350    350       }
   351    351     }
   352    352   }
   353    353   
................................................................................
  1567   1567   static void jsonArrayFinal(sqlite3_context *ctx){
  1568   1568     JsonString *pStr;
  1569   1569     pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  1570   1570     if( pStr ){
  1571   1571       pStr->pCtx = ctx;
  1572   1572       jsonAppendChar(pStr, ']');
  1573   1573       if( pStr->bErr ){
  1574         -      sqlite3_result_error_nomem(ctx);
         1574  +      if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
  1575   1575         assert( pStr->bStatic );
  1576   1576       }else{
  1577   1577         sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
  1578   1578                             pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  1579   1579         pStr->bStatic = 1;
  1580   1580       }
  1581   1581     }else{
................................................................................
  1615   1615   }
  1616   1616   static void jsonObjectFinal(sqlite3_context *ctx){
  1617   1617     JsonString *pStr;
  1618   1618     pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  1619   1619     if( pStr ){
  1620   1620       jsonAppendChar(pStr, '}');
  1621   1621       if( pStr->bErr ){
  1622         -      sqlite3_result_error_nomem(ctx);
         1622  +      if( pStr->bErr==0 ) sqlite3_result_error_nomem(ctx);
  1623   1623         assert( pStr->bStatic );
  1624   1624       }else{
  1625   1625         sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
  1626   1626                             pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  1627   1627         pStr->bStatic = 1;
  1628   1628       }
  1629   1629     }else{

Changes to src/alter.c.

   691    691     */
   692    692     if( pDflt ){
   693    693       sqlite3_value *pVal = 0;
   694    694       int rc;
   695    695       rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
   696    696       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
   697    697       if( rc!=SQLITE_OK ){
   698         -      db->mallocFailed = 1;
          698  +      assert( db->mallocFailed = 1 );
   699    699         return;
   700    700       }
   701    701       if( !pVal ){
   702    702         sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
   703    703         return;
   704    704       }
   705    705       sqlite3ValueFree(pVal);

Changes to src/analyze.c.

   309    309   
   310    310   /* Initialize the BLOB value of a ROWID
   311    311   */
   312    312   #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
   313    313   static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
   314    314     assert( db!=0 );
   315    315     if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
   316         -  p->u.aRowid = sqlite3DbMallocRaw(db, n);
          316  +  p->u.aRowid = sqlite3DbMallocRawNN(db, n);
   317    317     if( p->u.aRowid ){
   318    318       p->nRowid = n;
   319    319       memcpy(p->u.aRowid, pData, n);
   320    320     }else{
   321    321       p->nRowid = 0;
   322    322     }
   323    323   }
................................................................................
  1111   1111       VdbeCoverage(v);
  1112   1112       sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
  1113   1113       addrNextRow = sqlite3VdbeCurrentAddr(v);
  1114   1114   
  1115   1115       if( nColTest>0 ){
  1116   1116         int endDistinctTest = sqlite3VdbeMakeLabel(v);
  1117   1117         int *aGotoChng;               /* Array of jump instruction addresses */
  1118         -      aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*nColTest);
         1118  +      aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
  1119   1119         if( aGotoChng==0 ) continue;
  1120   1120   
  1121   1121         /*
  1122   1122         **  next_row:
  1123   1123         **   regChng = 0
  1124   1124         **   if( idx(0) != regPrev(0) ) goto chng_addr_0
  1125   1125         **   regChng = 1
................................................................................
  1519   1519       int nCol = pIndex->nKeyCol+1;
  1520   1520   #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  1521   1521       /* Index.aiRowEst may already be set here if there are duplicate 
  1522   1522       ** sqlite_stat1 entries for this index. In that case just clobber
  1523   1523       ** the old data with the new instead of allocating a new array.  */
  1524   1524       if( pIndex->aiRowEst==0 ){
  1525   1525         pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
  1526         -      if( pIndex->aiRowEst==0 ) pInfo->db->mallocFailed = 1;
         1526  +      if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
  1527   1527       }
  1528   1528       aiRowEst = pIndex->aiRowEst;
  1529   1529   #endif
  1530   1530       pIndex->bUnordered = 0;
  1531   1531       decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
  1532   1532       if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
  1533   1533     }else{
................................................................................
  1666   1666   ){
  1667   1667     int rc;                       /* Result codes from subroutines */
  1668   1668     sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
  1669   1669     char *zSql;                   /* Text of the SQL statement */
  1670   1670     Index *pPrevIdx = 0;          /* Previous index in the loop */
  1671   1671     IndexSample *pSample;         /* A slot in pIdx->aSample[] */
  1672   1672   
  1673         -  assert( db->lookaside.bEnabled==0 );
         1673  +  assert( db->lookaside.bDisable );
  1674   1674     zSql = sqlite3MPrintf(db, zSql1, zDb);
  1675   1675     if( !zSql ){
  1676   1676       return SQLITE_NOMEM;
  1677   1677     }
  1678   1678     rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  1679   1679     sqlite3DbFree(db, zSql);
  1680   1680     if( rc ) return rc;
................................................................................
  1780   1780   /*
  1781   1781   ** Load content from the sqlite_stat4 and sqlite_stat3 tables into 
  1782   1782   ** the Index.aSample[] arrays of all indices.
  1783   1783   */
  1784   1784   static int loadStat4(sqlite3 *db, const char *zDb){
  1785   1785     int rc = SQLITE_OK;             /* Result codes from subroutines */
  1786   1786   
  1787         -  assert( db->lookaside.bEnabled==0 );
         1787  +  assert( db->lookaside.bDisable );
  1788   1788     if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
  1789   1789       rc = loadStatTbl(db, 0,
  1790   1790         "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx", 
  1791   1791         "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
  1792   1792         zDb
  1793   1793       );
  1794   1794     }
................................................................................
  1862   1862       sqlite3DbFree(db, zSql);
  1863   1863     }
  1864   1864   
  1865   1865   
  1866   1866     /* Load the statistics from the sqlite_stat4 table. */
  1867   1867   #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  1868   1868     if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
  1869         -    int lookasideEnabled = db->lookaside.bEnabled;
  1870         -    db->lookaside.bEnabled = 0;
         1869  +    db->lookaside.bDisable++;
  1871   1870       rc = loadStat4(db, sInfo.zDatabase);
  1872         -    db->lookaside.bEnabled = lookasideEnabled;
         1871  +    db->lookaside.bDisable--;
  1873   1872     }
  1874   1873     for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  1875   1874       Index *pIdx = sqliteHashData(i);
  1876   1875       sqlite3_free(pIdx->aiRowEst);
  1877   1876       pIdx->aiRowEst = 0;
  1878   1877     }
  1879   1878   #endif
  1880   1879   
  1881   1880     if( rc==SQLITE_NOMEM ){
  1882         -    db->mallocFailed = 1;
         1881  +    sqlite3OomFault(db);
  1883   1882     }
  1884   1883     return rc;
  1885   1884   }
  1886   1885   
  1887   1886   
  1888   1887   #endif /* SQLITE_OMIT_ANALYZE */

Changes to src/attach.c.

   105    105       }
   106    106     }
   107    107   
   108    108     /* Allocate the new entry in the db->aDb[] array and initialize the schema
   109    109     ** hash tables.
   110    110     */
   111    111     if( db->aDb==db->aDbStatic ){
   112         -    aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
          112  +    aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
   113    113       if( aNew==0 ) return;
   114    114       memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
   115    115     }else{
   116    116       aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
   117    117       if( aNew==0 ) return;
   118    118     }
   119    119     db->aDb = aNew;
................................................................................
   123    123     /* Open the database file. If the btree is successfully opened, use
   124    124     ** it to obtain the database schema. At this point the schema may
   125    125     ** or may not be initialized.
   126    126     */
   127    127     flags = db->openFlags;
   128    128     rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
   129    129     if( rc!=SQLITE_OK ){
   130         -    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
          130  +    if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
   131    131       sqlite3_result_error(context, zErr, -1);
   132    132       sqlite3_free(zErr);
   133    133       return;
   134    134     }
   135    135     assert( pVfs );
   136    136     flags |= SQLITE_OPEN_MAIN_DB;
   137    137     rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
................................................................................
   226    226         sqlite3BtreeClose(db->aDb[iDb].pBt);
   227    227         db->aDb[iDb].pBt = 0;
   228    228         db->aDb[iDb].pSchema = 0;
   229    229       }
   230    230       sqlite3ResetAllSchemasOfConnection(db);
   231    231       db->nDb = iDb;
   232    232       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
   233         -      db->mallocFailed = 1;
          233  +      sqlite3OomFault(db);
   234    234         sqlite3DbFree(db, zErrDyn);
   235    235         zErrDyn = sqlite3MPrintf(db, "out of memory");
   236    236       }else if( zErrDyn==0 ){
   237    237         zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
   238    238       }
   239    239       goto attach_error;
   240    240     }

Changes to src/build.c.

    74     74       p = &pToplevel->aTableLock[pToplevel->nTableLock++];
    75     75       p->iDb = iDb;
    76     76       p->iTab = iTab;
    77     77       p->isWriteLock = isWriteLock;
    78     78       p->zName = zName;
    79     79     }else{
    80     80       pToplevel->nTableLock = 0;
    81         -    pToplevel->db->mallocFailed = 1;
           81  +    sqlite3OomFault(pToplevel->db);
    82     82     }
    83     83   }
    84     84   
    85     85   /*
    86     86   ** Code an OP_TableLock instruction for each table locked by the
    87     87   ** statement (configured by calls to sqlite3TableLock()).
    88     88   */
................................................................................
  1551   1551       zSep = "\n  ";
  1552   1552       zSep2 = ",\n  ";
  1553   1553       zEnd = "\n)";
  1554   1554     }
  1555   1555     n += 35 + 6*p->nCol;
  1556   1556     zStmt = sqlite3DbMallocRaw(0, n);
  1557   1557     if( zStmt==0 ){
  1558         -    db->mallocFailed = 1;
         1558  +    sqlite3OomFault(db);
  1559   1559       return 0;
  1560   1560     }
  1561   1561     sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  1562   1562     k = sqlite3Strlen30(zStmt);
  1563   1563     identPut(zStmt, &k, p->zName);
  1564   1564     zStmt[k++] = '(';
  1565   1565     for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
................................................................................
  2034   2034     if( db->init.busy ){
  2035   2035       Table *pOld;
  2036   2036       Schema *pSchema = p->pSchema;
  2037   2037       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  2038   2038       pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
  2039   2039       if( pOld ){
  2040   2040         assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
  2041         -      db->mallocFailed = 1;
         2041  +      sqlite3OomFault(db);
  2042   2042         return;
  2043   2043       }
  2044   2044       pParse->pNewTable = 0;
  2045   2045       db->flags |= SQLITE_InternChanges;
  2046   2046   
  2047   2047   #ifndef SQLITE_OMIT_ALTERTABLE
  2048   2048       if( !p->pSelect ){
................................................................................
  2138   2138   int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  2139   2139     Table *pSelTab;   /* A fake table from which we get the result set */
  2140   2140     Select *pSel;     /* Copy of the SELECT that implements the view */
  2141   2141     int nErr = 0;     /* Number of errors encountered */
  2142   2142     int n;            /* Temporarily holds the number of cursors assigned */
  2143   2143     sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
  2144   2144     sqlite3_xauth xAuth;       /* Saved xAuth pointer */
  2145         -  u8 bEnabledLA;             /* Saved db->lookaside.bEnabled state */
  2146   2145   
  2147   2146     assert( pTable );
  2148   2147   
  2149   2148   #ifndef SQLITE_OMIT_VIRTUALTABLE
  2150   2149     if( sqlite3VtabCallConnect(pParse, pTable) ){
  2151   2150       return SQLITE_ERROR;
  2152   2151     }
................................................................................
  2184   2183     ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  2185   2184     ** "*" elements in the results set of the view and will assign cursors
  2186   2185     ** to the elements of the FROM clause.  But we do not want these changes
  2187   2186     ** to be permanent.  So the computation is done on a copy of the SELECT
  2188   2187     ** statement that defines the view.
  2189   2188     */
  2190   2189     assert( pTable->pSelect );
  2191         -  bEnabledLA = db->lookaside.bEnabled;
  2192   2190     if( pTable->pCheck ){
  2193         -    db->lookaside.bEnabled = 0;
         2191  +    db->lookaside.bDisable++;
  2194   2192       sqlite3ColumnsFromExprList(pParse, pTable->pCheck, 
  2195   2193                                  &pTable->nCol, &pTable->aCol);
         2194  +    db->lookaside.bDisable--;
  2196   2195     }else{
  2197   2196       pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  2198   2197       if( pSel ){
  2199   2198         n = pParse->nTab;
  2200   2199         sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  2201   2200         pTable->nCol = -1;
  2202         -      db->lookaside.bEnabled = 0;
         2201  +      db->lookaside.bDisable++;
  2203   2202   #ifndef SQLITE_OMIT_AUTHORIZATION
  2204   2203         xAuth = db->xAuth;
  2205   2204         db->xAuth = 0;
  2206   2205         pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  2207   2206         db->xAuth = xAuth;
  2208   2207   #else
  2209   2208         pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  2210   2209   #endif
         2210  +      db->lookaside.bDisable--;
  2211   2211         pParse->nTab = n;
  2212   2212         if( pSelTab ){
  2213   2213           assert( pTable->aCol==0 );
  2214   2214           pTable->nCol = pSelTab->nCol;
  2215   2215           pTable->aCol = pSelTab->aCol;
  2216   2216           pSelTab->nCol = 0;
  2217   2217           pSelTab->aCol = 0;
................................................................................
  2222   2222           nErr++;
  2223   2223         }
  2224   2224         sqlite3SelectDelete(db, pSel);
  2225   2225       } else {
  2226   2226         nErr++;
  2227   2227       }
  2228   2228     }
  2229         -  db->lookaside.bEnabled = bEnabledLA;
  2230   2229     pTable->pSchema->schemaFlags |= DB_UnresetViews;
  2231   2230   #endif /* SQLITE_OMIT_VIEW */
  2232   2231     return nErr;  
  2233   2232   }
  2234   2233   #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  2235   2234   
  2236   2235   #ifndef SQLITE_OMIT_VIEW
................................................................................
  2688   2687     pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
  2689   2688   
  2690   2689     assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  2691   2690     pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
  2692   2691         pFKey->zTo, (void *)pFKey
  2693   2692     );
  2694   2693     if( pNextTo==pFKey ){
  2695         -    db->mallocFailed = 1;
         2694  +    sqlite3OomFault(db);
  2696   2695       goto fk_end;
  2697   2696     }
  2698   2697     if( pNextTo ){
  2699   2698       assert( pNextTo->pPrevTo==0 );
  2700   2699       pFKey->pNextTo = pNextTo;
  2701   2700       pNextTo->pPrevTo = pFKey;
  2702   2701     }
................................................................................
  3270   3269     if( db->init.busy ){
  3271   3270       Index *p;
  3272   3271       assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  3273   3272       p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
  3274   3273                             pIndex->zName, pIndex);
  3275   3274       if( p ){
  3276   3275         assert( p==pIndex );  /* Malloc must have failed */
  3277         -      db->mallocFailed = 1;
         3276  +      sqlite3OomFault(db);
  3278   3277         goto exit_create_index;
  3279   3278       }
  3280   3279       db->flags |= SQLITE_InternChanges;
  3281   3280       if( pTblName!=0 ){
  3282   3281         pIndex->tnum = db->init.newTnum;
  3283   3282       }
  3284   3283     }
................................................................................
  3699   3698     sqlite3 *db,        /* Connection to notify of malloc failures */
  3700   3699     SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
  3701   3700     Token *pTable,      /* Table to append */
  3702   3701     Token *pDatabase    /* Database of the table */
  3703   3702   ){
  3704   3703     struct SrcList_item *pItem;
  3705   3704     assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
         3705  +  assert( db!=0 );
  3706   3706     if( pList==0 ){
  3707         -    pList = sqlite3DbMallocRaw(db, sizeof(SrcList) );
         3707  +    pList = sqlite3DbMallocRawNN(db, sizeof(SrcList) );
  3708   3708       if( pList==0 ) return 0;
  3709   3709       pList->nAlloc = 1;
  3710   3710       pList->nSrc = 0;
  3711   3711     }
  3712   3712     pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  3713   3713     if( db->mallocFailed ){
  3714   3714       sqlite3SrcListDelete(db, pList);
................................................................................
  3988   3988           "file for storing temporary tables");
  3989   3989         pParse->rc = rc;
  3990   3990         return 1;
  3991   3991       }
  3992   3992       db->aDb[1].pBt = pBt;
  3993   3993       assert( db->aDb[1].pSchema );
  3994   3994       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  3995         -      db->mallocFailed = 1;
         3995  +      sqlite3OomFault(db);
  3996   3996         return 1;
  3997   3997       }
  3998   3998     }
  3999   3999     return 0;
  4000   4000   }
  4001   4001   
  4002   4002   /*
................................................................................
  4363   4363   
  4364   4364     if( pWith ){
  4365   4365       int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
  4366   4366       pNew = sqlite3DbRealloc(db, pWith, nByte);
  4367   4367     }else{
  4368   4368       pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
  4369   4369     }
  4370         -  assert( zName!=0 || pNew==0 );
  4371         -  assert( db->mallocFailed==0 || pNew==0 );
         4370  +  assert( (pNew!=0 && zName!=0) || db->mallocFailed );
  4372   4371   
  4373         -  if( pNew==0 ){
         4372  +  if( db->mallocFailed ){
  4374   4373       sqlite3ExprListDelete(db, pArglist);
  4375   4374       sqlite3SelectDelete(db, pQuery);
  4376   4375       sqlite3DbFree(db, zName);
  4377   4376       pNew = pWith;
  4378   4377     }else{
  4379   4378       pNew->a[pNew->nCte].pSelect = pQuery;
  4380   4379       pNew->a[pNew->nCte].pCols = pArglist;

Changes to src/callback.c.

   173    173   
   174    174         /* If a malloc() failure occurred in sqlite3HashInsert(), it will 
   175    175         ** return the pColl pointer to be deleted (because it wasn't added
   176    176         ** to the hash table).
   177    177         */
   178    178         assert( pDel==0 || pDel==pColl );
   179    179         if( pDel!=0 ){
   180         -        db->mallocFailed = 1;
          180  +        sqlite3OomFault(db);
   181    181           sqlite3DbFree(db, pDel);
   182    182           pColl = 0;
   183    183         }
   184    184       }
   185    185     }
   186    186     return pColl;
   187    187   }
................................................................................
   461    461     Schema * p;
   462    462     if( pBt ){
   463    463       p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
   464    464     }else{
   465    465       p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
   466    466     }
   467    467     if( !p ){
   468         -    db->mallocFailed = 1;
          468  +    sqlite3OomFault(db);
   469    469     }else if ( 0==p->file_format ){
   470    470       sqlite3HashInit(&p->tblHash);
   471    471       sqlite3HashInit(&p->idxHash);
   472    472       sqlite3HashInit(&p->trigHash);
   473    473       sqlite3HashInit(&p->fkeyHash);
   474    474       p->enc = SQLITE_UTF8;
   475    475     }
   476    476     return p;
   477    477   }

Changes to src/date.c.

   963    963     testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
   964    964     if( n<sizeof(zBuf) ){
   965    965       z = zBuf;
   966    966     }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
   967    967       sqlite3_result_error_toobig(context);
   968    968       return;
   969    969     }else{
   970         -    z = sqlite3DbMallocRaw(db, (int)n);
          970  +    z = sqlite3DbMallocRawNN(db, (int)n);
   971    971       if( z==0 ){
   972    972         sqlite3_result_error_nomem(context);
   973    973         return;
   974    974       }
   975    975     }
   976    976     computeJD(&x);
   977    977     computeYMD_HMS(&x);

Changes to src/delete.c.

   435    435       }
   436    436     
   437    437       if( eOnePass!=ONEPASS_OFF ){
   438    438         /* For ONEPASS, no need to store the rowid/primary-key. There is only
   439    439         ** one, so just keep it in its register(s) and fall through to the
   440    440         ** delete code.  */
   441    441         nKey = nPk; /* OP_Found will use an unpacked key */
   442         -      aToOpen = sqlite3DbMallocRaw(db, nIdx+2);
          442  +      aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
   443    443         if( aToOpen==0 ){
   444    444           sqlite3WhereEnd(pWInfo);
   445    445           goto delete_from_cleanup;
   446    446         }
   447    447         memset(aToOpen, 1, nIdx+1);
   448    448         aToOpen[nIdx+1] = 0;
   449    449         if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;

Changes to src/expr.c.

   449    449     const Token *pToken,    /* Token argument.  Might be NULL */
   450    450     int dequote             /* True to dequote */
   451    451   ){
   452    452     Expr *pNew;
   453    453     int nExtra = 0;
   454    454     int iValue = 0;
   455    455   
          456  +  assert( db!=0 );
   456    457     if( pToken ){
   457    458       if( op!=TK_INTEGER || pToken->z==0
   458    459             || sqlite3GetInt32(pToken->z, &iValue)==0 ){
   459    460         nExtra = pToken->n+1;
   460    461         assert( iValue>=0 );
   461    462       }
   462    463     }
   463         -  pNew = sqlite3DbMallocRaw(db, sizeof(Expr)+nExtra);
          464  +  pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
   464    465     if( pNew ){
   465    466       memset(pNew, 0, sizeof(Expr));
   466    467       pNew->op = (u8)op;
   467    468       pNew->iAgg = -1;
   468    469       if( pToken ){
   469    470         if( nExtra==0 ){
   470    471           pNew->flags |= EP_IntValue;
................................................................................
   695    696         }
   696    697         if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
   697    698       }
   698    699       if( x>0 ){
   699    700         if( x>pParse->nzVar ){
   700    701           char **a;
   701    702           a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
   702         -        if( a==0 ) return;  /* Error reported through db->mallocFailed */
          703  +        if( a==0 ){
          704  +          assert( db->mallocFailed ); /* Error reported through mallocFailed */
          705  +          return;
          706  +        }
   703    707           pParse->azVar = a;
   704    708           memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
   705    709           pParse->nzVar = x;
   706    710         }
   707    711         if( z[0]!='?' || pParse->azVar[x-1]==0 ){
   708    712           sqlite3DbFree(db, pParse->azVar[x-1]);
   709    713           pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
................................................................................
   850    854   ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
   851    855   ** if any. Before returning, *pzBuffer is set to the first byte past the
   852    856   ** portion of the buffer copied into by this function.
   853    857   */
   854    858   static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
   855    859     Expr *pNew = 0;                      /* Value to return */
   856    860     assert( flags==0 || flags==EXPRDUP_REDUCE );
          861  +  assert( db!=0 );
   857    862     if( p ){
   858    863       const int isReduced = (flags&EXPRDUP_REDUCE);
   859    864       u8 *zAlloc;
   860    865       u32 staticFlag = 0;
   861    866   
   862    867       assert( pzBuffer==0 || isReduced );
   863    868   
   864    869       /* Figure out where to write the new Expr structure. */
   865    870       if( pzBuffer ){
   866    871         zAlloc = *pzBuffer;
   867    872         staticFlag = EP_Static;
   868    873       }else{
   869         -      zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
          874  +      zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, flags));
   870    875       }
   871    876       pNew = (Expr *)zAlloc;
   872    877   
   873    878       if( pNew ){
   874    879         /* Set nNewSize to the size allocated for the structure pointed to
   875    880         ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
   876    881         ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
................................................................................
   985    990     assert( flags==0 || flags==EXPRDUP_REDUCE );
   986    991     return exprDup(db, p, flags, 0);
   987    992   }
   988    993   ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
   989    994     ExprList *pNew;
   990    995     struct ExprList_item *pItem, *pOldItem;
   991    996     int i;
          997  +  assert( db!=0 );
   992    998     if( p==0 ) return 0;
   993         -  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
          999  +  pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
   994   1000     if( pNew==0 ) return 0;
   995   1001     pNew->nExpr = i = p->nExpr;
   996   1002     if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
   997         -  pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
         1003  +  pNew->a = pItem = sqlite3DbMallocRawNN(db,  i*sizeof(p->a[0]) );
   998   1004     if( pItem==0 ){
   999   1005       sqlite3DbFree(db, pNew);
  1000   1006       return 0;
  1001   1007     } 
  1002   1008     pOldItem = p->a;
  1003   1009     for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  1004   1010       Expr *pOldExpr = pOldItem->pExpr;
................................................................................
  1021   1027   */
  1022   1028   #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  1023   1029    || !defined(SQLITE_OMIT_SUBQUERY)
  1024   1030   SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  1025   1031     SrcList *pNew;
  1026   1032     int i;
  1027   1033     int nByte;
         1034  +  assert( db!=0 );
  1028   1035     if( p==0 ) return 0;
  1029   1036     nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  1030         -  pNew = sqlite3DbMallocRaw(db, nByte );
         1037  +  pNew = sqlite3DbMallocRawNN(db, nByte );
  1031   1038     if( pNew==0 ) return 0;
  1032   1039     pNew->nSrc = pNew->nAlloc = p->nSrc;
  1033   1040     for(i=0; i<p->nSrc; i++){
  1034   1041       struct SrcList_item *pNewItem = &pNew->a[i];
  1035   1042       struct SrcList_item *pOldItem = &p->a[i];
  1036   1043       Table *pTab;
  1037   1044       pNewItem->pSchema = pOldItem->pSchema;
................................................................................
  1060   1067       pNewItem->colUsed = pOldItem->colUsed;
  1061   1068     }
  1062   1069     return pNew;
  1063   1070   }
  1064   1071   IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  1065   1072     IdList *pNew;
  1066   1073     int i;
         1074  +  assert( db!=0 );
  1067   1075     if( p==0 ) return 0;
  1068         -  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
         1076  +  pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
  1069   1077     if( pNew==0 ) return 0;
  1070   1078     pNew->nId = p->nId;
  1071         -  pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
         1079  +  pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
  1072   1080     if( pNew->a==0 ){
  1073   1081       sqlite3DbFree(db, pNew);
  1074   1082       return 0;
  1075   1083     }
  1076   1084     /* Note that because the size of the allocation for p->a[] is not
  1077   1085     ** necessarily a power of two, sqlite3IdListAppend() may not be called
  1078   1086     ** on the duplicate created by this function. */
................................................................................
  1082   1090       pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  1083   1091       pNewItem->idx = pOldItem->idx;
  1084   1092     }
  1085   1093     return pNew;
  1086   1094   }
  1087   1095   Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  1088   1096     Select *pNew, *pPrior;
         1097  +  assert( db!=0 );
  1089   1098     if( p==0 ) return 0;
  1090         -  pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
         1099  +  pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
  1091   1100     if( pNew==0 ) return 0;
  1092   1101     pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  1093   1102     pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  1094   1103     pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  1095   1104     pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  1096   1105     pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  1097   1106     pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
................................................................................
  1129   1138   */
  1130   1139   ExprList *sqlite3ExprListAppend(
  1131   1140     Parse *pParse,          /* Parsing context */
  1132   1141     ExprList *pList,        /* List to which to append. Might be NULL */
  1133   1142     Expr *pExpr             /* Expression to be appended. Might be NULL */
  1134   1143   ){
  1135   1144     sqlite3 *db = pParse->db;
         1145  +  assert( db!=0 );
  1136   1146     if( pList==0 ){
  1137         -    pList = sqlite3DbMallocRaw(db, sizeof(ExprList) );
         1147  +    pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
  1138   1148       if( pList==0 ){
  1139   1149         goto no_mem;
  1140   1150       }
  1141   1151       pList->nExpr = 0;
  1142         -    pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
         1152  +    pList->a = sqlite3DbMallocRawNN(db, sizeof(pList->a[0]));
  1143   1153       if( pList->a==0 ) goto no_mem;
  1144   1154     }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
  1145   1155       struct ExprList_item *a;
  1146   1156       assert( pList->nExpr>0 );
  1147   1157       a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
  1148   1158       if( a==0 ){
  1149   1159         goto no_mem;

Changes to src/fkey.c.

   215    215       */
   216    216       if( pParent->iPKey>=0 ){
   217    217         if( !zKey ) return 0;
   218    218         if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
   219    219       }
   220    220     }else if( paiCol ){
   221    221       assert( nCol>1 );
   222         -    aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
          222  +    aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
   223    223       if( !aiCol ) return 1;
   224    224       *paiCol = aiCol;
   225    225     }
   226    226   
   227    227     for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
   228    228       if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){ 
   229    229         /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
................................................................................
  1161   1161     Trigger *pTrigger;              /* Trigger definition to return */
  1162   1162     int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
  1163   1163   
  1164   1164     action = pFKey->aAction[iAction];
  1165   1165     pTrigger = pFKey->apTrigger[iAction];
  1166   1166   
  1167   1167     if( action!=OE_None && !pTrigger ){
  1168         -    u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
  1169   1168       char const *zFrom;            /* Name of child table */
  1170   1169       int nFrom;                    /* Length in bytes of zFrom */
  1171   1170       Index *pIdx = 0;              /* Parent key index for this FK */
  1172   1171       int *aiCol = 0;               /* child table cols -> parent key cols */
  1173   1172       TriggerStep *pStep = 0;        /* First (only) step of trigger program */
  1174   1173       Expr *pWhere = 0;             /* WHERE clause of trigger step */
  1175   1174       ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
................................................................................
  1270   1269             pWhere,
  1271   1270             0, 0, 0, 0, 0, 0
  1272   1271         );
  1273   1272         pWhere = 0;
  1274   1273       }
  1275   1274   
  1276   1275       /* Disable lookaside memory allocation */
  1277         -    enableLookaside = db->lookaside.bEnabled;
  1278         -    db->lookaside.bEnabled = 0;
         1276  +    db->lookaside.bDisable++;
  1279   1277   
  1280   1278       pTrigger = (Trigger *)sqlite3DbMallocZero(db, 
  1281   1279           sizeof(Trigger) +         /* struct Trigger */
  1282   1280           sizeof(TriggerStep) +     /* Single step in trigger program */
  1283   1281           nFrom + 1                 /* Space for pStep->zTarget */
  1284   1282       );
  1285   1283       if( pTrigger ){
................................................................................
  1293   1291         if( pWhen ){
  1294   1292           pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
  1295   1293           pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  1296   1294         }
  1297   1295       }
  1298   1296   
  1299   1297       /* Re-enable the lookaside buffer, if it was disabled earlier. */
  1300         -    db->lookaside.bEnabled = enableLookaside;
         1298  +    db->lookaside.bDisable--;
  1301   1299   
  1302   1300       sqlite3ExprDelete(db, pWhere);
  1303   1301       sqlite3ExprDelete(db, pWhen);
  1304   1302       sqlite3ExprListDelete(db, pList);
  1305   1303       sqlite3SelectDelete(db, pSelect);
  1306   1304       if( db->mallocFailed==1 ){
  1307   1305         fkTriggerDelete(db, pTrigger);

Changes to src/func.c.

  1611   1611   ** of the built-in functions above are part of the global function set.
  1612   1612   ** This routine only deals with those that are not global.
  1613   1613   */
  1614   1614   void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
  1615   1615     int rc = sqlite3_overload_function(db, "MATCH", 2);
  1616   1616     assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  1617   1617     if( rc==SQLITE_NOMEM ){
  1618         -    db->mallocFailed = 1;
         1618  +    sqlite3OomFault(db);
  1619   1619     }
  1620   1620   }
  1621   1621   
  1622   1622   /*
  1623   1623   ** Set the LIKEOPT flag on the 2-argument function with the given name.
  1624   1624   */
  1625   1625   static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){

Changes to src/insert.c.

    79     79       ** sqliteDeleteIndex() when the Index structure itself is cleaned
    80     80       ** up.
    81     81       */
    82     82       int n;
    83     83       Table *pTab = pIdx->pTable;
    84     84       pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
    85     85       if( !pIdx->zColAff ){
    86         -      db->mallocFailed = 1;
           86  +      sqlite3OomFault(db);
    87     87         return 0;
    88     88       }
    89     89       for(n=0; n<pIdx->nColumn; n++){
    90     90         i16 x = pIdx->aiColumn[n];
    91     91         if( x>=0 ){
    92     92           pIdx->zColAff[n] = pTab->aCol[x].affinity;
    93     93         }else if( x==XN_ROWID ){
................................................................................
   130    130   void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
   131    131     int i;
   132    132     char *zColAff = pTab->zColAff;
   133    133     if( zColAff==0 ){
   134    134       sqlite3 *db = sqlite3VdbeDb(v);
   135    135       zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
   136    136       if( !zColAff ){
   137         -      db->mallocFailed = 1;
          137  +      sqlite3OomFault(db);
   138    138         return;
   139    139       }
   140    140   
   141    141       for(i=0; i<pTab->nCol; i++){
   142    142         zColAff[i] = pTab->aCol[i].affinity;
   143    143       }
   144    144       do{
................................................................................
   226    226     if( pTab->tabFlags & TF_Autoincrement ){
   227    227       Parse *pToplevel = sqlite3ParseToplevel(pParse);
   228    228       AutoincInfo *pInfo;
   229    229   
   230    230       pInfo = pToplevel->pAinc;
   231    231       while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
   232    232       if( pInfo==0 ){
   233         -      pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
          233  +      pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
   234    234         if( pInfo==0 ) return 0;
   235    235         pInfo->pNext = pToplevel->pAinc;
   236    236         pToplevel->pAinc = pInfo;
   237    237         pInfo->pTab = pTab;
   238    238         pInfo->iDb = iDb;
   239    239         pToplevel->nMem++;                  /* Register to hold name of table */
   240    240         pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
................................................................................
   783    783     }
   784    784   
   785    785     /* If this is not a view, open the table and and all indices */
   786    786     if( !isView ){
   787    787       int nIdx;
   788    788       nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
   789    789                                         &iDataCur, &iIdxCur);
   790         -    aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
          790  +    aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
   791    791       if( aRegIdx==0 ){
   792    792         goto insert_cleanup;
   793    793       }
   794    794       for(i=0; i<nIdx; i++){
   795    795         aRegIdx[i] = ++pParse->nMem;
   796    796       }
   797    797     }

Changes to src/legacy.c.

    86     86             callbackIsInit = 1;
    87     87           }
    88     88           if( rc==SQLITE_ROW ){
    89     89             azVals = &azCols[nCol];
    90     90             for(i=0; i<nCol; i++){
    91     91               azVals[i] = (char *)sqlite3_column_text(pStmt, i);
    92     92               if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
    93         -              db->mallocFailed = 1;
           93  +              sqlite3OomFault(db);
    94     94                 goto exec_out;
    95     95               }
    96     96             }
    97     97           }
    98     98           if( xCallback(pArg, nCol, azVals, azCols) ){
    99     99             /* EVIDENCE-OF: R-38229-40159 If the callback function to
   100    100             ** sqlite3_exec() returns non-zero, then sqlite3_exec() will

Changes to src/main.c.

   694    694       p = (LookasideSlot*)pStart;
   695    695       for(i=cnt-1; i>=0; i--){
   696    696         p->pNext = db->lookaside.pFree;
   697    697         db->lookaside.pFree = p;
   698    698         p = (LookasideSlot*)&((u8*)p)[sz];
   699    699       }
   700    700       db->lookaside.pEnd = p;
   701         -    db->lookaside.bEnabled = 1;
          701  +    db->lookaside.bDisable = 0;
   702    702       db->lookaside.bMalloced = pBuf==0 ?1:0;
   703    703     }else{
   704    704       db->lookaside.pStart = db;
   705    705       db->lookaside.pEnd = db;
   706         -    db->lookaside.bEnabled = 0;
          706  +    db->lookaside.bDisable = 1;
   707    707       db->lookaside.bMalloced = 0;
   708    708     }
   709    709   #endif /* SQLITE_OMIT_LOOKASIDE */
   710    710     return SQLITE_OK;
   711    711   }
   712    712   
   713    713   /*
................................................................................
  2204   2204         z = sqlite3_value_text16(db->pErr);
  2205   2205       }
  2206   2206       /* A malloc() may have failed within the call to sqlite3_value_text16()
  2207   2207       ** above. If this is the case, then the db->mallocFailed flag needs to
  2208   2208       ** be cleared before returning. Do this directly, instead of via
  2209   2209       ** sqlite3ApiExit(), to avoid setting the database handle error message.
  2210   2210       */
  2211         -    db->mallocFailed = 0;
         2211  +    sqlite3OomClear(db);
  2212   2212     }
  2213   2213     sqlite3_mutex_leave(db->mutex);
  2214   2214     return z;
  2215   2215   }
  2216   2216   #endif /* SQLITE_OMIT_UTF16 */
  2217   2217   
  2218   2218   /*
................................................................................
  2842   2842     db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
  2843   2843     assert( db->pDfltColl!=0 );
  2844   2844   
  2845   2845     /* Parse the filename/URI argument. */
  2846   2846     db->openFlags = flags;
  2847   2847     rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  2848   2848     if( rc!=SQLITE_OK ){
  2849         -    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
         2849  +    if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  2850   2850       sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  2851   2851       sqlite3_free(zErrMsg);
  2852   2852       goto opendb_out;
  2853   2853     }
  2854   2854   
  2855   2855     /* Open the backend database driver */
  2856   2856     rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,

Changes to src/malloc.c.

   571    571   }
   572    572   
   573    573   /*
   574    574   ** Allocate and zero memory.  If the allocation fails, make
   575    575   ** the mallocFailed flag in the connection pointer.
   576    576   */
   577    577   void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
   578         -  void *p = sqlite3DbMallocRaw(db, n);
   579         -  if( p ){
   580         -    memset(p, 0, (size_t)n);
   581         -  }
          578  +  void *p;
          579  +  testcase( db==0 );
          580  +  p = sqlite3DbMallocRaw(db, n);
          581  +  if( p ) memset(p, 0, (size_t)n);
          582  +  return p;
          583  +}
          584  +
          585  +
          586  +/* Finish the work of sqlite3DbMallocRawNN for the unusual and
          587  +** slower case when the allocation cannot be fulfilled using lookaside.
          588  +*/
          589  +static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
          590  +  void *p;
          591  +  assert( db!=0 );
          592  +  p = sqlite3Malloc(n);
          593  +  if( !p ) sqlite3OomFault(db);
          594  +  sqlite3MemdebugSetType(p, 
          595  +         (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
   582    596     return p;
   583    597   }
   584    598   
   585    599   /*
   586    600   ** Allocate memory, either lookaside (if possible) or heap.  
   587    601   ** If the allocation fails, set the mallocFailed flag in
   588    602   ** the connection pointer.
................................................................................
   596    610   **
   597    611   **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
   598    612   **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
   599    613   **         if( b ) a[10] = 9;
   600    614   **
   601    615   ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
   602    616   ** that all prior mallocs (ex: "a") worked too.
          617  +**
          618  +** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
          619  +** not a NULL pointer.
   603    620   */
   604         -static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n);
   605    621   void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
   606         -  assert( db==0 || sqlite3_mutex_held(db->mutex) );
   607         -  assert( db==0 || db->pnBytesFreed==0 );
          622  +  void *p;
          623  +  if( db ) return sqlite3DbMallocRawNN(db, n);
          624  +  p = sqlite3Malloc(n);
          625  +  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
          626  +  return p;
          627  +}
          628  +void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
          629  +  assert( db!=0 );
          630  +  assert( sqlite3_mutex_held(db->mutex) );
          631  +  assert( db->pnBytesFreed==0 );
   608    632   #ifndef SQLITE_OMIT_LOOKASIDE
   609         -  if( db ){
   610         -    LookasideSlot *pBuf;
   611         -    if( db->mallocFailed ){
   612         -      return 0;
   613         -    }
   614         -    if( db->lookaside.bEnabled ){
   615         -      if( n>db->lookaside.sz ){
   616         -        db->lookaside.anStat[1]++;
   617         -      }else if( (pBuf = db->lookaside.pFree)==0 ){
   618         -        db->lookaside.anStat[2]++;
   619         -      }else{
   620         -        db->lookaside.pFree = pBuf->pNext;
   621         -        db->lookaside.nOut++;
   622         -        db->lookaside.anStat[0]++;
   623         -        if( db->lookaside.nOut>db->lookaside.mxOut ){
   624         -          db->lookaside.mxOut = db->lookaside.nOut;
   625         -        }
   626         -        return (void*)pBuf;
          633  +  LookasideSlot *pBuf;
          634  +  if( db->lookaside.bDisable==0 ){
          635  +    assert( db->mallocFailed==0 );
          636  +    if( n>db->lookaside.sz ){
          637  +      db->lookaside.anStat[1]++;
          638  +    }else if( (pBuf = db->lookaside.pFree)==0 ){
          639  +      db->lookaside.anStat[2]++;
          640  +    }else{
          641  +      db->lookaside.pFree = pBuf->pNext;
          642  +      db->lookaside.nOut++;
          643  +      db->lookaside.anStat[0]++;
          644  +      if( db->lookaside.nOut>db->lookaside.mxOut ){
          645  +        db->lookaside.mxOut = db->lookaside.nOut;
   627    646         }
          647  +      return (void*)pBuf;
   628    648       }
          649  +  }else if( db->mallocFailed ){
          650  +    return 0;
   629    651     }
   630    652   #else
   631         -  if( db && db->mallocFailed ){
          653  +  if( db->mallocFailed ){
   632    654       return 0;
   633    655     }
   634    656   #endif
   635    657     return dbMallocRawFinish(db, n);
   636    658   }
   637         -static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
   638         -  void *p = sqlite3Malloc(n);
   639         -  if( !p && db ){
   640         -    db->mallocFailed = 1;
   641         -  }
   642         -  sqlite3MemdebugSetType(p, 
   643         -         (db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
   644         -  return p;
   645         -}
          659  +
          660  +/* Forward declaration */
          661  +static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
   646    662   
   647    663   /*
   648    664   ** Resize the block of memory pointed to by p to n bytes. If the
   649    665   ** resize fails, set the mallocFailed flag in the connection object.
   650    666   */
   651    667   void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
          668  +  assert( db!=0 );
          669  +  if( p==0 ) return sqlite3DbMallocRawNN(db, n);
          670  +  assert( sqlite3_mutex_held(db->mutex) );
          671  +  if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
          672  +  return dbReallocFinish(db, p, n);
          673  +}
          674  +static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
   652    675     void *pNew = 0;
   653    676     assert( db!=0 );
   654         -  assert( sqlite3_mutex_held(db->mutex) );
          677  +  assert( p!=0 );
   655    678     if( db->mallocFailed==0 ){
   656         -    if( p==0 ){
   657         -      return sqlite3DbMallocRaw(db, n);
   658         -    }
   659    679       if( isLookaside(db, p) ){
   660         -      if( n<=db->lookaside.sz ){
   661         -        return p;
   662         -      }
   663         -      pNew = sqlite3DbMallocRaw(db, n);
          680  +      pNew = sqlite3DbMallocRawNN(db, n);
   664    681         if( pNew ){
   665    682           memcpy(pNew, p, db->lookaside.sz);
   666    683           sqlite3DbFree(db, p);
   667    684         }
   668    685       }else{
   669    686         assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
   670    687         assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
   671    688         sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   672    689         pNew = sqlite3_realloc64(p, n);
   673    690         if( !pNew ){
   674         -        db->mallocFailed = 1;
          691  +        sqlite3OomFault(db);
   675    692         }
   676    693         sqlite3MemdebugSetType(pNew,
   677         -            (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
          694  +            (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
   678    695       }
   679    696     }
   680    697     return pNew;
   681    698   }
   682    699   
   683    700   /*
   684    701   ** Attempt to reallocate p.  If the reallocation fails, then free p
................................................................................
   712    729     if( zNew ){
   713    730       memcpy(zNew, z, n);
   714    731     }
   715    732     return zNew;
   716    733   }
   717    734   char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
   718    735     char *zNew;
          736  +  assert( db!=0 );
   719    737     if( z==0 ){
   720    738       return 0;
   721    739     }
   722    740     assert( (n&0x7fffffff)==n );
   723         -  zNew = sqlite3DbMallocRaw(db, n+1);
          741  +  zNew = sqlite3DbMallocRawNN(db, n+1);
   724    742     if( zNew ){
   725    743       memcpy(zNew, z, (size_t)n);
   726    744       zNew[n] = 0;
   727    745     }
   728    746     return zNew;
   729    747   }
   730    748   
................................................................................
   731    749   /*
   732    750   ** Free any prior content in *pz and replace it with a copy of zNew.
   733    751   */
   734    752   void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
   735    753     sqlite3DbFree(db, *pz);
   736    754     *pz = sqlite3DbStrDup(db, zNew);
   737    755   }
          756  +
          757  +/*
          758  +** Call this routine to record the fact that an OOM (out-of-memory) error
          759  +** has happened.  This routine will set db->mallocFailed, and also
          760  +** temporarily disable the lookaside memory allocator and interrupt
          761  +** any running VDBEs.
          762  +*/
          763  +void sqlite3OomFault(sqlite3 *db){
          764  +  if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
          765  +    db->mallocFailed = 1;
          766  +    if( db->nVdbeExec>0 ){
          767  +      db->u1.isInterrupted = 1;
          768  +    }
          769  +    db->lookaside.bDisable++;
          770  +  }
          771  +}
          772  +
          773  +/*
          774  +** This routine reactivates the memory allocator and clears the
          775  +** db->mallocFailed flag as necessary.
          776  +**
          777  +** The memory allocator is not restarted if there are running
          778  +** VDBEs.
          779  +*/
          780  +void sqlite3OomClear(sqlite3 *db){
          781  +  if( db->mallocFailed && db->nVdbeExec==0 ){
          782  +    db->mallocFailed = 0;
          783  +    db->u1.isInterrupted = 0;
          784  +    assert( db->lookaside.bDisable>0 );
          785  +    db->lookaside.bDisable--;
          786  +  }
          787  +}
   738    788   
   739    789   /*
   740    790   ** Take actions at the end of an API call to indicate an OOM error
   741    791   */
   742    792   static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
   743         -  db->mallocFailed = 0;
          793  +  sqlite3OomClear(db);
   744    794     sqlite3Error(db, SQLITE_NOMEM);
   745    795     return SQLITE_NOMEM;
   746    796   }
   747    797   
   748    798   /*
   749    799   ** This function must be called before exiting any API function (i.e. 
   750    800   ** returning control to the user) that has called sqlite3_malloc or

Changes to src/parse.y.

   101    101   */
   102    102   struct TrigEvent { int a; IdList * b; };
   103    103   
   104    104   /*
   105    105   ** An instance of this structure holds the ATTACH key and the key type.
   106    106   */
   107    107   struct AttachKey { int type;  Token key; };
          108  +
          109  +/*
          110  +** Disable lookaside memory allocation for objects that might be
          111  +** shared across database connections.
          112  +*/
          113  +static void disableLookaside(Parse *pParse){
          114  +  pParse->disableLookaside++;
          115  +  pParse->db->lookaside.bDisable++;
          116  +}
   108    117   
   109    118   } // end %include
   110    119   
   111    120   // Input is a single SQL command
   112    121   input ::= cmdlist.
   113    122   cmdlist ::= cmdlist ecmd.
   114    123   cmdlist ::= ecmd.
................................................................................
   152    161   ///////////////////// The CREATE TABLE statement ////////////////////////////
   153    162   //
   154    163   cmd ::= create_table create_table_args.
   155    164   create_table ::= createkw temp(T) TABLE ifnotexists(E) nm(Y) dbnm(Z). {
   156    165      sqlite3StartTable(pParse,&Y,&Z,T,0,0,E);
   157    166   }
   158    167   createkw(A) ::= CREATE(X).  {
   159         -  pParse->db->lookaside.bEnabled = 0;
          168  +  disableLookaside(pParse);
   160    169     A = X;
   161    170   }
   162    171   %type ifnotexists {int}
   163    172   ifnotexists(A) ::= .              {A = 0;}
   164    173   ifnotexists(A) ::= IF NOT EXISTS. {A = 1;}
   165    174   %type temp {int}
   166    175   %ifndef SQLITE_OMIT_TEMPDB
................................................................................
  1503   1512   cmd ::= ALTER TABLE fullname(X) RENAME TO nm(Z). {
  1504   1513     sqlite3AlterRenameTable(pParse,X,&Z);
  1505   1514   }
  1506   1515   cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column(Y). {
  1507   1516     sqlite3AlterFinishAddColumn(pParse, &Y);
  1508   1517   }
  1509   1518   add_column_fullname ::= fullname(X). {
  1510         -  pParse->db->lookaside.bEnabled = 0;
         1519  +  disableLookaside(pParse);
  1511   1520     sqlite3AlterBeginAddColumn(pParse, X);
  1512   1521   }
  1513   1522   kwcolumn_opt ::= .
  1514   1523   kwcolumn_opt ::= COLUMNKW.
  1515   1524   %endif  SQLITE_OMIT_ALTERTABLE
  1516   1525   
  1517   1526   //////////////////////// CREATE VIRTUAL TABLE ... /////////////////////////////

Changes to src/pragma.c.

   474    474         returnSingleInt(v, "page_size", size);
   475    475       }else{
   476    476         /* Malloc may fail when setting the page-size, as there is an internal
   477    477         ** buffer that the pager module resizes using sqlite3_realloc().
   478    478         */
   479    479         db->nextPagesize = sqlite3Atoi(zRight);
   480    480         if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
   481         -        db->mallocFailed = 1;
          481  +        sqlite3OomFault(db);
   482    482         }
   483    483       }
   484    484       break;
   485    485     }
   486    486   
   487    487     /*
   488    488     **  PRAGMA [schema.]secure_delete

Changes to src/prepare.c.

    24     24     const char *zObj,    /* Object being parsed at the point of error */
    25     25     const char *zExtra   /* Error information */
    26     26   ){
    27     27     sqlite3 *db = pData->db;
    28     28     if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
    29     29       char *z;
    30     30       if( zObj==0 ) zObj = "?";
    31         -    z = sqlite3_mprintf("malformed database schema (%s)", zObj);
    32         -    if( z && zExtra ) z = sqlite3_mprintf("%z - %s", z, zExtra);
           31  +    z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
           32  +    if( zExtra ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
    33     33       sqlite3DbFree(db, *pData->pzErrMsg);
    34     34       *pData->pzErrMsg = z;
    35         -    if( z==0 ) db->mallocFailed = 1;
    36     35     }
    37     36     pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
    38     37   }
    39     38   
    40     39   /*
    41     40   ** This is the callback routine for the code that initializes the
    42     41   ** database.  See sqlite3Init() below for additional information.
................................................................................
    87     86       db->init.iDb = 0;
    88     87       if( SQLITE_OK!=rc ){
    89     88         if( db->init.orphanTrigger ){
    90     89           assert( iDb==1 );
    91     90         }else{
    92     91           pData->rc = rc;
    93     92           if( rc==SQLITE_NOMEM ){
    94         -          db->mallocFailed = 1;
           93  +          sqlite3OomFault(db);
    95     94           }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
    96     95             corruptSchema(pData, argv[0], sqlite3_errmsg(db));
    97     96           }
    98     97         }
    99     98       }
   100     99       sqlite3_finalize(pStmt);
   101    100     }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
................................................................................
   332    331     if( openedTransaction ){
   333    332       sqlite3BtreeCommit(pDb->pBt);
   334    333     }
   335    334     sqlite3BtreeLeave(pDb->pBt);
   336    335   
   337    336   error_out:
   338    337     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
   339         -    db->mallocFailed = 1;
          338  +    sqlite3OomFault(db);
   340    339     }
   341    340     return rc;
   342    341   }
   343    342   
   344    343   /*
   345    344   ** Initialize all database files - the main database file, the file
   346    345   ** used to store temporary tables, and any additional database files
................................................................................
   430    429   
   431    430       /* If there is not already a read-only (or read-write) transaction opened
   432    431       ** on the b-tree database, open one now. If a transaction is opened, it 
   433    432       ** will be closed immediately after reading the meta-value. */
   434    433       if( !sqlite3BtreeIsInReadTrans(pBt) ){
   435    434         rc = sqlite3BtreeBeginTrans(pBt, 0);
   436    435         if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
   437         -        db->mallocFailed = 1;
          436  +        sqlite3OomFault(db);
   438    437         }
   439    438         if( rc!=SQLITE_OK ) return;
   440    439         openedTransaction = 1;
   441    440       }
   442    441   
   443    442       /* Read the schema cookie from the database. If it does not match the 
   444    443       ** value stored as part of the in-memory schema representation,
................................................................................
   493    492   ** Free all memory allocations in the pParse object
   494    493   */
   495    494   void sqlite3ParserReset(Parse *pParse){
   496    495     if( pParse ){
   497    496       sqlite3 *db = pParse->db;
   498    497       sqlite3DbFree(db, pParse->aLabel);
   499    498       sqlite3ExprListDelete(db, pParse->pConstExpr);
          499  +    if( db ){
          500  +      assert( db->lookaside.bDisable >= pParse->disableLookaside );
          501  +      db->lookaside.bDisable -= pParse->disableLookaside;
          502  +    }
          503  +    pParse->disableLookaside = 0;
   500    504     }
   501    505   }
   502    506   
   503    507   /*
   504    508   ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
   505    509   */
   506    510   static int sqlite3Prepare(
................................................................................
   588    592         pParse->zTail = &zSql[nBytes];
   589    593       }
   590    594     }else{
   591    595       sqlite3RunParser(pParse, zSql, &zErrMsg);
   592    596     }
   593    597     assert( 0==pParse->nQueryLoop );
   594    598   
   595         -  if( db->mallocFailed ){
   596         -    pParse->rc = SQLITE_NOMEM;
   597         -  }
   598    599     if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
   599    600     if( pParse->checkSchema ){
   600    601       schemaIsValid(pParse);
   601    602     }
   602    603     if( db->mallocFailed ){
   603    604       pParse->rc = SQLITE_NOMEM;
   604    605     }
................................................................................
   712    713     zSql = sqlite3_sql((sqlite3_stmt *)p);
   713    714     assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
   714    715     db = sqlite3VdbeDb(p);
   715    716     assert( sqlite3_mutex_held(db->mutex) );
   716    717     rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
   717    718     if( rc ){
   718    719       if( rc==SQLITE_NOMEM ){
   719         -      db->mallocFailed = 1;
          720  +      sqlite3OomFault(db);
   720    721       }
   721    722       assert( pNew==0 );
   722    723       return rc;
   723    724     }else{
   724    725       assert( pNew!=0 );
   725    726     }
   726    727     sqlite3VdbeSwap((Vdbe*)pNew, p);

Changes to src/printf.c.

   925    925     assert( db!=0 );
   926    926     sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
   927    927                         db->aLimit[SQLITE_LIMIT_LENGTH]);
   928    928     acc.printfFlags = SQLITE_PRINTF_INTERNAL;
   929    929     sqlite3VXPrintf(&acc, zFormat, ap);
   930    930     z = sqlite3StrAccumFinish(&acc);
   931    931     if( acc.accError==STRACCUM_NOMEM ){
   932         -    db->mallocFailed = 1;
          932  +    sqlite3OomFault(db);
   933    933     }
   934    934     return z;
   935    935   }
   936    936   
   937    937   /*
   938    938   ** Print into memory obtained from sqliteMalloc().  Use the internal
   939    939   ** %-conversion extensions.

Changes to src/rowset.c.

   177    177   ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
   178    178   ** routine returns NULL.
   179    179   */
   180    180   static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
   181    181     assert( p!=0 );
   182    182     if( p->nFresh==0 ){
   183    183       struct RowSetChunk *pNew;
   184         -    pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
          184  +    pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
   185    185       if( pNew==0 ){
   186    186         return 0;
   187    187       }
   188    188       pNew->pNextChunk = p->pChunk;
   189    189       p->pChunk = pNew;
   190    190       p->pFresh = pNew->aEntry;
   191    191       p->nFresh = ROWSET_ENTRY_PER_CHUNK;

Changes to src/select.c.

   108    108     u16 selFlags,         /* Flag parameters, such as SF_Distinct */
   109    109     Expr *pLimit,         /* LIMIT value.  NULL means not used */
   110    110     Expr *pOffset         /* OFFSET value.  NULL means no offset */
   111    111   ){
   112    112     Select *pNew;
   113    113     Select standin;
   114    114     sqlite3 *db = pParse->db;
   115         -  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
          115  +  pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
   116    116     if( pNew==0 ){
   117    117       assert( db->mallocFailed );
   118    118       pNew = &standin;
   119    119     }
   120    120     if( pEList==0 ){
   121    121       pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ASTERISK,0));
   122    122     }
................................................................................
  1012   1012       p->nField = (u16)N;
  1013   1013       p->nXField = (u16)X;
  1014   1014       p->enc = ENC(db);
  1015   1015       p->db = db;
  1016   1016       p->nRef = 1;
  1017   1017       memset(&p[1], 0, nExtra);
  1018   1018     }else{
  1019         -    db->mallocFailed = 1;
         1019  +    sqlite3OomFault(db);
  1020   1020     }
  1021   1021     return p;
  1022   1022   }
  1023   1023   
  1024   1024   /*
  1025   1025   ** Deallocate a KeyInfo object
  1026   1026   */
................................................................................
  1673   1673         }
  1674   1674         zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
  1675   1675         if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
  1676   1676       }
  1677   1677       pCol->zName = zName;
  1678   1678       sqlite3ColumnPropertiesFromName(0, pCol);
  1679   1679       if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
  1680         -      db->mallocFailed = 1;
         1680  +      sqlite3OomFault(db);
  1681   1681       }
  1682   1682     }
  1683   1683     sqlite3HashClear(&ht);
  1684   1684     if( db->mallocFailed ){
  1685   1685       for(j=0; j<i; j++){
  1686   1686         sqlite3DbFree(db, aCol[j].zName);
  1687   1687       }
................................................................................
  1760   1760     db->flags = savedFlags;
  1761   1761     pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  1762   1762     if( pTab==0 ){
  1763   1763       return 0;
  1764   1764     }
  1765   1765     /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
  1766   1766     ** is disabled */
  1767         -  assert( db->lookaside.bEnabled==0 );
         1767  +  assert( db->lookaside.bDisable );
  1768   1768     pTab->nRef = 1;
  1769   1769     pTab->zName = 0;
  1770   1770     pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  1771   1771     sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  1772   1772     selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
  1773   1773     pTab->iPKey = -1;
  1774   1774     if( db->mallocFailed ){
................................................................................
  2866   2866     /* Compute the comparison permutation and keyinfo that is used with
  2867   2867     ** the permutation used to determine if the next
  2868   2868     ** row of results comes from selectA or selectB.  Also add explicit
  2869   2869     ** collations to the ORDER BY clause terms so that when the subqueries
  2870   2870     ** to the right and the left are evaluated, they use the correct
  2871   2871     ** collation.
  2872   2872     */
  2873         -  aPermute = sqlite3DbMallocRaw(db, sizeof(int)*(nOrderBy + 1));
         2873  +  aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
  2874   2874     if( aPermute ){
  2875   2875       struct ExprList_item *pItem;
  2876   2876       aPermute[0] = nOrderBy;
  2877   2877       for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
  2878   2878         assert( pItem->u.x.iOrderByCol>0 );
  2879   2879         assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
  2880   2880         aPermute[i] = pItem->u.x.iOrderByCol - 1;
................................................................................
  5558   5558             flag = minMaxQuery(&sAggInfo, &pMinMax);
  5559   5559           }
  5560   5560           assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
  5561   5561   
  5562   5562           if( flag ){
  5563   5563             pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
  5564   5564             pDel = pMinMax;
  5565         -          if( pMinMax && !db->mallocFailed ){
         5565  +          assert( db->mallocFailed || pMinMax!=0 );
         5566  +          if( !db->mallocFailed ){
  5566   5567               pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
  5567   5568               pMinMax->a[0].pExpr->op = TK_COLUMN;
  5568   5569             }
  5569   5570           }
  5570   5571     
  5571   5572           /* This case runs if the aggregate has no GROUP BY clause.  The
  5572   5573           ** processing is much simpler since there is only a single row

Changes to src/sqliteInt.h.

  1090   1090   ** with a particular database connection.  Hence, schema information cannot
  1091   1091   ** be stored in lookaside because in shared cache mode the schema information
  1092   1092   ** is shared by multiple database connections.  Therefore, while parsing
  1093   1093   ** schema information, the Lookaside.bEnabled flag is cleared so that
  1094   1094   ** lookaside allocations are not used to construct the schema objects.
  1095   1095   */
  1096   1096   struct Lookaside {
         1097  +  u32 bDisable;           /* Only operate the lookaside when zero */
  1097   1098     u16 sz;                 /* Size of each buffer in bytes */
  1098         -  u8 bEnabled;            /* False to disable new lookaside allocations */
  1099   1099     u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
  1100   1100     int nOut;               /* Number of buffers currently checked out */
  1101   1101     int mxOut;              /* Highwater mark for nOut */
  1102   1102     int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
  1103   1103     LookasideSlot *pFree;   /* List of available buffers */
  1104   1104     void *pStart;           /* First byte of available memory space */
  1105   1105     void *pEnd;             /* First byte past end of available space */
................................................................................
  1174   1174     int errCode;                  /* Most recent error code (SQLITE_*) */
  1175   1175     int errMask;                  /* & result codes with this before returning */
  1176   1176     u16 dbOptFlags;               /* Flags to enable/disable optimizations */
  1177   1177     u8 enc;                       /* Text encoding */
  1178   1178     u8 autoCommit;                /* The auto-commit flag. */
  1179   1179     u8 temp_store;                /* 1: file 2: memory 0: default */
  1180   1180     u8 mallocFailed;              /* True if we have seen a malloc failure */
         1181  +  u8 bBenignMalloc;             /* Do not require OOMs if true */
  1181   1182     u8 dfltLockMode;              /* Default locking-mode for attached dbs */
  1182   1183     signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
  1183   1184     u8 suppressErr;               /* Do not issue error messages if true */
  1184   1185     u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
  1185   1186     u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
  1186   1187     int nextPagesize;             /* Pagesize after VACUUM if >0 */
  1187   1188     u32 magic;                    /* Magic number for detect library misuse */
................................................................................
  2729   2730     u8 checkSchema;      /* Causes schema cookie check after an error */
  2730   2731     u8 nested;           /* Number of nested calls to the parser/code generator */
  2731   2732     u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
  2732   2733     u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
  2733   2734     u8 mayAbort;         /* True if statement may throw an ABORT exception */
  2734   2735     u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */
  2735   2736     u8 okConstFactor;    /* OK to factor out constants */
         2737  +  u8 disableLookaside; /* Number of times lookaside has been disabled */
  2736   2738     int aTempReg[8];     /* Holding area for temporary registers */
  2737   2739     int nRangeReg;       /* Size of the temporary register block */
  2738   2740     int iRangeReg;       /* First register in temporary register block */
  2739   2741     int nErr;            /* Number of errors seen */
  2740   2742     int nTab;            /* Number of previously allocated VDBE cursors */
  2741   2743     int nMem;            /* Number of memory cells used so far */
  2742   2744     int nSet;            /* Number of sets used so far */
................................................................................
  3221   3223   
  3222   3224   int sqlite3MallocInit(void);
  3223   3225   void sqlite3MallocEnd(void);
  3224   3226   void *sqlite3Malloc(u64);
  3225   3227   void *sqlite3MallocZero(u64);
  3226   3228   void *sqlite3DbMallocZero(sqlite3*, u64);
  3227   3229   void *sqlite3DbMallocRaw(sqlite3*, u64);
         3230  +void *sqlite3DbMallocRawNN(sqlite3*, u64);
  3228   3231   char *sqlite3DbStrDup(sqlite3*,const char*);
  3229   3232   char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
  3230   3233   void *sqlite3Realloc(void*, u64);
  3231   3234   void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
  3232   3235   void *sqlite3DbRealloc(sqlite3 *, void *, u64);
  3233   3236   void sqlite3DbFree(sqlite3*, void*);
  3234   3237   int sqlite3MallocSize(void*);
................................................................................
  3773   3776   int sqlite3KeyInfoIsWriteable(KeyInfo*);
  3774   3777   #endif
  3775   3778   int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
  3776   3779     void (*)(sqlite3_context*,int,sqlite3_value **),
  3777   3780     void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
  3778   3781     FuncDestructor *pDestructor
  3779   3782   );
         3783  +void sqlite3OomFault(sqlite3*);
         3784  +void sqlite3OomClear(sqlite3*);
  3780   3785   int sqlite3ApiExit(sqlite3 *db, int);
  3781   3786   int sqlite3OpenTempDatabase(Parse *);
  3782   3787   
  3783   3788   void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
  3784   3789   void sqlite3StrAccumAppend(StrAccum*,const char*,int);
  3785   3790   void sqlite3StrAccumAppendAll(StrAccum*,const char*);
  3786   3791   void sqlite3AppendChar(StrAccum*,int,char);

Changes to src/test_func.c.

   162    162   static void test_agg_errmsg16_step(sqlite3_context *a, int b,sqlite3_value **c){
   163    163   }
   164    164   static void test_agg_errmsg16_final(sqlite3_context *ctx){
   165    165   #ifndef SQLITE_OMIT_UTF16
   166    166     const void *z;
   167    167     sqlite3 * db = sqlite3_context_db_handle(ctx);
   168    168     sqlite3_aggregate_context(ctx, 2048);
   169         -  sqlite3BeginBenignMalloc();
   170    169     z = sqlite3_errmsg16(db);
   171         -  sqlite3EndBenignMalloc();
   172    170     sqlite3_result_text16(ctx, z, -1, SQLITE_TRANSIENT);
   173    171   #endif
   174    172   }
   175    173   
   176    174   /*
   177    175   ** Routines for testing the sqlite3_get_auxdata() and sqlite3_set_auxdata()
   178    176   ** interface.

Changes to src/tokenize.c.

   386    386   */
   387    387   int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
   388    388     int nErr = 0;                   /* Number of errors encountered */
   389    389     int i;                          /* Loop counter */
   390    390     void *pEngine;                  /* The LEMON-generated LALR(1) parser */
   391    391     int tokenType;                  /* type of the next token */
   392    392     int lastTokenParsed = -1;       /* type of the previous token */
   393         -  u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
   394    393     sqlite3 *db = pParse->db;       /* The database connection */
   395    394     int mxSqlLen;                   /* Max length of an SQL string */
   396    395   
   397    396     assert( zSql!=0 );
   398    397     mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
   399    398     if( db->nVdbeActive==0 ){
   400    399       db->u1.isInterrupted = 0;
................................................................................
   402    401     pParse->rc = SQLITE_OK;
   403    402     pParse->zTail = zSql;
   404    403     i = 0;
   405    404     assert( pzErrMsg!=0 );
   406    405     /* sqlite3ParserTrace(stdout, "parser: "); */
   407    406     pEngine = sqlite3ParserAlloc(sqlite3Malloc);
   408    407     if( pEngine==0 ){
   409         -    db->mallocFailed = 1;
          408  +    sqlite3OomFault(db);
   410    409       return SQLITE_NOMEM;
   411    410     }
   412    411     assert( pParse->pNewTable==0 );
   413    412     assert( pParse->pNewTrigger==0 );
   414    413     assert( pParse->nVar==0 );
   415    414     assert( pParse->nzVar==0 );
   416    415     assert( pParse->azVar==0 );
   417         -  enableLookaside = db->lookaside.bEnabled;
   418         -  if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
   419    416     while( zSql[i]!=0 ){
   420    417       assert( i>=0 );
   421    418       pParse->sLastToken.z = &zSql[i];
   422    419       pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
   423    420       i += pParse->sLastToken.n;
   424    421       if( i>mxSqlLen ){
   425    422         pParse->rc = SQLITE_TOOBIG;
   426    423         break;
   427    424       }
   428    425       if( tokenType>=TK_SPACE ){
   429    426         assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
   430    427         if( db->u1.isInterrupted ){
   431         -        sqlite3ErrorMsg(pParse, "interrupt");
   432    428           pParse->rc = SQLITE_INTERRUPT;
   433    429           break;
   434    430         }
   435    431         if( tokenType==TK_ILLEGAL ){
   436    432           sqlite3ErrorMsg(pParse, "unrecognized token: \"%T\"",
   437    433                           &pParse->sLastToken);
   438    434           break;
................................................................................
   459    455     sqlite3_mutex_enter(sqlite3MallocMutex());
   460    456     sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
   461    457         sqlite3ParserStackPeak(pEngine)
   462    458     );
   463    459     sqlite3_mutex_leave(sqlite3MallocMutex());
   464    460   #endif /* YYDEBUG */
   465    461     sqlite3ParserFree(pEngine, sqlite3_free);
   466         -  db->lookaside.bEnabled = enableLookaside;
   467    462     if( db->mallocFailed ){
   468    463       pParse->rc = SQLITE_NOMEM;
   469    464     }
   470    465     if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
   471    466       pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
   472    467     }
   473    468     assert( pzErrMsg!=0 );

Changes to src/trigger.c.

   319    319   
   320    320     if( db->init.busy ){
   321    321       Trigger *pLink = pTrig;
   322    322       Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
   323    323       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   324    324       pTrig = sqlite3HashInsert(pHash, zName, pTrig);
   325    325       if( pTrig ){
   326         -      db->mallocFailed = 1;
          326  +      sqlite3OomFault(db);
   327    327       }else if( pLink->pSchema==pLink->pTabSchema ){
   328    328         Table *pTab;
   329    329         pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
   330    330         assert( pTab!=0 );
   331    331         pLink->pNext = pTab->pTrigger;
   332    332         pTab->pTrigger = pLink;
   333    333       }

Changes to src/update.c.

   193    193       }
   194    194       pParse->nTab++;
   195    195     }
   196    196   
   197    197     /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].  
   198    198     ** Initialize aXRef[] and aToOpen[] to their default values.
   199    199     */
   200         -  aXRef = sqlite3DbMallocRaw(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
          200  +  aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
   201    201     if( aXRef==0 ) goto update_cleanup;
   202    202     aRegIdx = aXRef+pTab->nCol;
   203    203     aToOpen = (u8*)(aRegIdx+nIdx);
   204    204     memset(aToOpen, 1, nIdx+1);
   205    205     aToOpen[nIdx+1] = 0;
   206    206     for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
   207    207   

Changes to src/util.c.

  1146   1146   ** binary value has been obtained from malloc and must be freed by
  1147   1147   ** the calling routine.
  1148   1148   */
  1149   1149   void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  1150   1150     char *zBlob;
  1151   1151     int i;
  1152   1152   
  1153         -  zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
         1153  +  zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
  1154   1154     n--;
  1155   1155     if( zBlob ){
  1156   1156       for(i=0; i<n; i+=2){
  1157   1157         zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
  1158   1158       }
  1159   1159       zBlob[i/2] = 0;
  1160   1160     }

Changes to src/vdbe.c.

   625    625       }
   626    626       if( p->db->flags & SQLITE_VdbeTrace )  printf("VDBE Trace:\n");
   627    627     }
   628    628     sqlite3EndBenignMalloc();
   629    629   #endif
   630    630     for(pOp=&aOp[p->pc]; rc==SQLITE_OK; pOp++){
   631    631       assert( pOp>=aOp && pOp<&aOp[p->nOp]);
   632         -    if( db->mallocFailed ) goto no_mem;
   633    632   #ifdef VDBE_PROFILE
   634    633       start = sqlite3Hwtime();
   635    634   #endif
   636    635       nVmStep++;
   637    636   #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
   638    637       if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
   639    638   #endif
................................................................................
  1623   1622     sqlite3_context *pCtx;
  1624   1623   
  1625   1624     assert( pOp->p4type==P4_FUNCDEF );
  1626   1625     n = pOp->p5;
  1627   1626     assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  1628   1627     assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
  1629   1628     assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  1630         -  pCtx = sqlite3DbMallocRaw(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
         1629  +  pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
  1631   1630     if( pCtx==0 ) goto no_mem;
  1632   1631     pCtx->pOut = 0;
  1633   1632     pCtx->pFunc = pOp->p4.pFunc;
  1634   1633     pCtx->iOp = (int)(pOp - aOp);
  1635   1634     pCtx->pVdbe = p;
  1636   1635     pCtx->argc = n;
  1637   1636     pOp->p4type = P4_FUNCCTX;
................................................................................
  2867   2866         assert( db->autoCommit==0 || db->nVTrans==0 );
  2868   2867         rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
  2869   2868                                   db->nStatement+db->nSavepoint);
  2870   2869         if( rc!=SQLITE_OK ) goto abort_due_to_error;
  2871   2870   #endif
  2872   2871   
  2873   2872         /* Create a new savepoint structure. */
  2874         -      pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
         2873  +      pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
  2875   2874         if( pNew ){
  2876   2875           pNew->zName = (char *)&pNew[1];
  2877   2876           memcpy(pNew->zName, zName, nName+1);
  2878   2877       
  2879   2878           /* If there is no open transaction, then mark this as a special
  2880   2879           ** "transaction savepoint". */
  2881   2880           if( db->autoCommit ){
................................................................................
  5417   5416     int nErr;       /* Number of errors reported */
  5418   5417     char *z;        /* Text of the error report */
  5419   5418     Mem *pnErr;     /* Register keeping track of errors remaining */
  5420   5419   
  5421   5420     assert( p->bIsReader );
  5422   5421     nRoot = pOp->p2;
  5423   5422     assert( nRoot>0 );
  5424         -  aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
         5423  +  aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(nRoot+1) );
  5425   5424     if( aRoot==0 ) goto no_mem;
  5426   5425     assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  5427   5426     pnErr = &aMem[pOp->p3];
  5428   5427     assert( (pnErr->flags & MEM_Int)!=0 );
  5429   5428     assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  5430   5429     pIn1 = &aMem[pOp->p1];
  5431   5430     for(j=0; j<nRoot; j++){
................................................................................
  5914   5913     sqlite3_context *pCtx;
  5915   5914   
  5916   5915     assert( pOp->p4type==P4_FUNCDEF );
  5917   5916     n = pOp->p5;
  5918   5917     assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  5919   5918     assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
  5920   5919     assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  5921         -  pCtx = sqlite3DbMallocRaw(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
         5920  +  pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
  5922   5921     if( pCtx==0 ) goto no_mem;
  5923   5922     pCtx->pMem = 0;
  5924   5923     pCtx->pFunc = pOp->p4.pFunc;
  5925   5924     pCtx->iOp = (int)(pOp - aOp);
  5926   5925     pCtx->pVdbe = p;
  5927   5926     pCtx->argc = n;
  5928   5927     pOp->p4type = P4_FUNCCTX;
................................................................................
  6781   6780   vdbe_error_halt:
  6782   6781     assert( rc );
  6783   6782     p->rc = rc;
  6784   6783     testcase( sqlite3GlobalConfig.xLog!=0 );
  6785   6784     sqlite3_log(rc, "statement aborts at %d: [%s] %s", 
  6786   6785                      (int)(pOp - aOp), p->zSql, p->zErrMsg);
  6787   6786     sqlite3VdbeHalt(p);
  6788         -  if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
         6787  +  if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
  6789   6788     rc = SQLITE_ERROR;
  6790   6789     if( resetSchemaOnFault>0 ){
  6791   6790       sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
  6792   6791     }
  6793   6792   
  6794   6793     /* This is the only way out of this procedure.  We have to
  6795   6794     ** release the mutexes on btrees that were acquired at the
................................................................................
  6811   6810     sqlite3VdbeError(p, "string or blob too big");
  6812   6811     rc = SQLITE_TOOBIG;
  6813   6812     goto vdbe_error_halt;
  6814   6813   
  6815   6814     /* Jump to here if a malloc() fails.
  6816   6815     */
  6817   6816   no_mem:
  6818         -  db->mallocFailed = 1;
         6817  +  sqlite3OomFault(db);
  6819   6818     sqlite3VdbeError(p, "out of memory");
  6820   6819     rc = SQLITE_NOMEM;
  6821   6820     goto vdbe_error_halt;
  6822   6821   
  6823   6822     /* Jump to here for any other kind of fatal error.  The "rc" variable
  6824   6823     ** should hold the error number.
  6825   6824     */
................................................................................
  6832   6831     goto vdbe_error_halt;
  6833   6832   
  6834   6833     /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  6835   6834     ** flag.
  6836   6835     */
  6837   6836   abort_due_to_interrupt:
  6838   6837     assert( db->u1.isInterrupted );
  6839         -  rc = SQLITE_INTERRUPT;
         6838  +  rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_INTERRUPT;
  6840   6839     p->rc = rc;
  6841   6840     sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  6842   6841     goto vdbe_error_halt;
  6843   6842   }

Changes to src/vdbeapi.c.

   469    469   
   470    470   /* An SQLITE_NOMEM error. */
   471    471   void sqlite3_result_error_nomem(sqlite3_context *pCtx){
   472    472     assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
   473    473     sqlite3VdbeMemSetNull(pCtx->pOut);
   474    474     pCtx->isError = SQLITE_NOMEM;
   475    475     pCtx->fErrorOrAux = 1;
   476         -  pCtx->pOut->db->mallocFailed = 1;
          476  +  sqlite3OomFault(pCtx->pOut->db);
   477    477   }
   478    478   
   479    479   /*
   480    480   ** This function is called after a transaction has been committed. It 
   481    481   ** invokes callbacks registered with sqlite3_wal_hook() as required.
   482    482   */
   483    483   static int doWalCallbacks(sqlite3 *db){
................................................................................
  1097   1097       sqlite3_mutex_enter(db->mutex);
  1098   1098       assert( db->mallocFailed==0 );
  1099   1099       ret = xFunc(&p->aColName[N]);
  1100   1100        /* A malloc may have failed inside of the xFunc() call. If this
  1101   1101       ** is the case, clear the mallocFailed flag and return NULL.
  1102   1102       */
  1103   1103       if( db->mallocFailed ){
  1104         -      db->mallocFailed = 0;
         1104  +      sqlite3OomClear(db);
  1105   1105         ret = 0;
  1106   1106       }
  1107   1107       sqlite3_mutex_leave(db->mutex);
  1108   1108     }
  1109   1109     return ret;
  1110   1110   }
  1111   1111   

Changes to src/vdbeaux.c.

   285    285     int op,             /* The new opcode */
   286    286     int p1,             /* The P1 operand */
   287    287     int p2,             /* The P2 operand */
   288    288     int p3,             /* The P3 operand */
   289    289     const u8 *zP4,      /* The P4 operand */
   290    290     int p4type          /* P4 operand type */
   291    291   ){
   292         -  char *p4copy = sqlite3DbMallocRaw(sqlite3VdbeDb(p), 8);
          292  +  char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
   293    293     if( p4copy ) memcpy(p4copy, zP4, 8);
   294    294     return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
   295    295   }
   296    296   
   297    297   /*
   298    298   ** Add an OP_ParseSchema opcode.  This routine is broken out from
   299    299   ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
................................................................................
  1419   1419   /*
  1420   1420   ** Release an array of N Mem elements
  1421   1421   */
  1422   1422   static void releaseMemArray(Mem *p, int N){
  1423   1423     if( p && N ){
  1424   1424       Mem *pEnd = &p[N];
  1425   1425       sqlite3 *db = p->db;
  1426         -    u8 malloc_failed = db->mallocFailed;
  1427   1426       if( db->pnBytesFreed ){
  1428   1427         do{
  1429   1428           if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  1430   1429         }while( (++p)<pEnd );
  1431   1430         return;
  1432   1431       }
  1433   1432       do{
................................................................................
  1455   1454         }else if( p->szMalloc ){
  1456   1455           sqlite3DbFree(db, p->zMalloc);
  1457   1456           p->szMalloc = 0;
  1458   1457         }
  1459   1458   
  1460   1459         p->flags = MEM_Undefined;
  1461   1460       }while( (++p)<pEnd );
  1462         -    db->mallocFailed = malloc_failed;
  1463   1461     }
  1464   1462   }
  1465   1463   
  1466   1464   /*
  1467   1465   ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  1468   1466   ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  1469   1467   */
................................................................................
  1516   1514     */
  1517   1515     releaseMemArray(pMem, 8);
  1518   1516     p->pResultSet = 0;
  1519   1517   
  1520   1518     if( p->rc==SQLITE_NOMEM ){
  1521   1519       /* This happens if a malloc() inside a call to sqlite3_column_text() or
  1522   1520       ** sqlite3_column_text16() failed.  */
  1523         -    db->mallocFailed = 1;
         1521  +    sqlite3OomFault(db);
  1524   1522       return SQLITE_ERROR;
  1525   1523     }
  1526   1524   
  1527   1525     /* When the number of output rows reaches nRow, that means the
  1528   1526     ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  1529   1527     ** nRow is the sum of the number of rows in the main program, plus
  1530   1528     ** the sum of the number of rows in all trigger subprograms encountered
................................................................................
  2509   2507     **     SQLITE_INTERRUPT
  2510   2508     **
  2511   2509     ** Then the internal cache might have been left in an inconsistent
  2512   2510     ** state.  We need to rollback the statement transaction, if there is
  2513   2511     ** one, or the complete transaction if there is no statement transaction.
  2514   2512     */
  2515   2513   
  2516         -  if( p->db->mallocFailed ){
         2514  +  if( db->mallocFailed ){
  2517   2515       p->rc = SQLITE_NOMEM;
  2518   2516     }
  2519   2517     if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
  2520   2518     closeAllCursors(p);
  2521   2519     if( p->magic!=VDBE_MAGIC_RUN ){
  2522   2520       return SQLITE_OK;
  2523   2521     }
................................................................................
  2670   2668       if( p->bIsReader ) db->nVdbeRead--;
  2671   2669       assert( db->nVdbeActive>=db->nVdbeRead );
  2672   2670       assert( db->nVdbeRead>=db->nVdbeWrite );
  2673   2671       assert( db->nVdbeWrite>=0 );
  2674   2672     }
  2675   2673     p->magic = VDBE_MAGIC_HALT;
  2676   2674     checkActiveVdbeCnt(db);
  2677         -  if( p->db->mallocFailed ){
         2675  +  if( db->mallocFailed ){
  2678   2676       p->rc = SQLITE_NOMEM;
  2679   2677     }
  2680   2678   
  2681   2679     /* If the auto-commit flag is set to true, then any locks that were held
  2682   2680     ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
  2683   2681     ** to invoke any required unlock-notify callbacks.
  2684   2682     */
................................................................................
  2707   2705   ** This function does not clear the VDBE error code or message, just
  2708   2706   ** copies them to the database handle.
  2709   2707   */
  2710   2708   int sqlite3VdbeTransferError(Vdbe *p){
  2711   2709     sqlite3 *db = p->db;
  2712   2710     int rc = p->rc;
  2713   2711     if( p->zErrMsg ){
  2714         -    u8 mallocFailed = db->mallocFailed;
         2712  +    db->bBenignMalloc++;
  2715   2713       sqlite3BeginBenignMalloc();
  2716   2714       if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
  2717   2715       sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  2718   2716       sqlite3EndBenignMalloc();
  2719         -    db->mallocFailed = mallocFailed;
         2717  +    db->bBenignMalloc--;
  2720   2718       db->errCode = rc;
  2721   2719     }else{
  2722   2720       sqlite3Error(db, rc);
  2723   2721     }
  2724   2722     return rc;
  2725   2723   }
  2726   2724   

Changes to src/vdbemem.c.

   112    112   ** pMem->z into the new allocation.  pMem must be either a string or
   113    113   ** blob if bPreserve is true.  If bPreserve is false, any prior content
   114    114   ** in pMem->z is discarded.
   115    115   */
   116    116   SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
   117    117     assert( sqlite3VdbeCheckMemInvariants(pMem) );
   118    118     assert( (pMem->flags&MEM_RowSet)==0 );
          119  +  testcase( pMem->db==0 );
   119    120   
   120    121     /* If the bPreserve flag is set to true, then the memory cell must already
   121    122     ** contain a valid string or blob value.  */
   122    123     assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
   123    124     testcase( bPreserve && pMem->z==0 );
   124    125   
   125    126     assert( pMem->szMalloc==0
................................................................................
   715    716   ** empty boolean index.
   716    717   */
   717    718   void sqlite3VdbeMemSetRowSet(Mem *pMem){
   718    719     sqlite3 *db = pMem->db;
   719    720     assert( db!=0 );
   720    721     assert( (pMem->flags & MEM_RowSet)==0 );
   721    722     sqlite3VdbeMemRelease(pMem);
   722         -  pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
          723  +  pMem->zMalloc = sqlite3DbMallocRawNN(db, 64);
   723    724     if( db->mallocFailed ){
   724    725       pMem->flags = MEM_Null;
   725    726       pMem->szMalloc = 0;
   726    727     }else{
   727    728       assert( pMem->zMalloc );
   728    729       pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
   729    730       pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
................................................................................
  1377   1378     }
  1378   1379   #endif
  1379   1380   
  1380   1381     *ppVal = pVal;
  1381   1382     return rc;
  1382   1383   
  1383   1384   no_mem:
  1384         -  db->mallocFailed = 1;
         1385  +  sqlite3OomFault(db);
  1385   1386     sqlite3DbFree(db, zVal);
  1386   1387     assert( *ppVal==0 );
  1387   1388   #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  1388   1389     if( pCtx==0 ) sqlite3ValueFree(pVal);
  1389   1390   #else
  1390   1391     assert( pCtx==0 ); sqlite3ValueFree(pVal);
  1391   1392   #endif
................................................................................
  1436   1437   
  1437   1438     UNUSED_PARAMETER( argc );
  1438   1439     iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal);
  1439   1440     nSerial = sqlite3VarintLen(iSerial);
  1440   1441     db = sqlite3_context_db_handle(context);
  1441   1442   
  1442   1443     nRet = 1 + nSerial + nVal;
  1443         -  aRet = sqlite3DbMallocRaw(db, nRet);
         1444  +  aRet = sqlite3DbMallocRawNN(db, nRet);
  1444   1445     if( aRet==0 ){
  1445   1446       sqlite3_result_error_nomem(context);
  1446   1447     }else{
  1447   1448       aRet[0] = nSerial+1;
  1448   1449       putVarint32(&aRet[1], iSerial);
  1449   1450       sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
  1450   1451       sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);

Changes to src/vtab.c.

    45     45   
    46     46     sqlite3_mutex_enter(db->mutex);
    47     47     nName = sqlite3Strlen30(zName);
    48     48     if( sqlite3HashFind(&db->aModule, zName) ){
    49     49       rc = SQLITE_MISUSE_BKPT;
    50     50     }else{
    51     51       Module *pMod;
    52         -    pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
           52  +    pMod = (Module *)sqlite3DbMallocRawNN(db, sizeof(Module) + nName + 1);
    53     53       if( pMod ){
    54     54         Module *pDel;
    55     55         char *zCopy = (char *)(&pMod[1]);
    56     56         memcpy(zCopy, zName, nName+1);
    57     57         pMod->zName = zCopy;
    58     58         pMod->pModule = pModule;
    59     59         pMod->pAux = pAux;
    60     60         pMod->xDestroy = xDestroy;
    61     61         pMod->pEpoTab = 0;
    62     62         pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
    63     63         assert( pDel==0 || pDel==pMod );
    64     64         if( pDel ){
    65         -        db->mallocFailed = 1;
           65  +        sqlite3OomFault(db);
    66     66           sqlite3DbFree(db, pDel);
    67     67         }
    68     68       }
    69     69     }
    70     70     rc = sqlite3ApiExit(db, rc);
    71     71     if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
    72     72   
................................................................................
   435    435     else {
   436    436       Table *pOld;
   437    437       Schema *pSchema = pTab->pSchema;
   438    438       const char *zName = pTab->zName;
   439    439       assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
   440    440       pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
   441    441       if( pOld ){
   442         -      db->mallocFailed = 1;
          442  +      sqlite3OomFault(db);
   443    443         assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
   444    444         return;
   445    445       }
   446    446       pParse->pNewTable = 0;
   447    447     }
   448    448   }
   449    449   
................................................................................
   526    526     sCtx.pTab = pTab;
   527    527     sCtx.pVTable = pVTable;
   528    528     sCtx.pPrior = db->pVtabCtx;
   529    529     sCtx.bDeclared = 0;
   530    530     db->pVtabCtx = &sCtx;
   531    531     rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
   532    532     db->pVtabCtx = sCtx.pPrior;
   533         -  if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
          533  +  if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
   534    534     assert( sCtx.pTab==pTab );
   535    535   
   536    536     if( SQLITE_OK!=rc ){
   537    537       if( zErr==0 ){
   538    538         *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
   539    539       }else {
   540    540         *pzErr = sqlite3MPrintf(db, "%s", zErr);
................................................................................
  1084   1084     }
  1085   1085     n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  1086   1086     apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
  1087   1087     if( apVtabLock ){
  1088   1088       pToplevel->apVtabLock = apVtabLock;
  1089   1089       pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  1090   1090     }else{
  1091         -    pToplevel->db->mallocFailed = 1;
         1091  +    sqlite3OomFault(pToplevel->db);
  1092   1092     }
  1093   1093   }
  1094   1094   
  1095   1095   /*
  1096   1096   ** Check to see if virtual tale module pMod can be have an eponymous
  1097   1097   ** virtual table instance.  If it can, create one if one does not already
  1098   1098   ** exist. Return non-zero if the eponymous virtual table instance exists

Changes to src/where.c.

   939    939   
   940    940     TRACE_IDX_INPUTS(p);
   941    941     rc = pVtab->pModule->xBestIndex(pVtab, p);
   942    942     TRACE_IDX_OUTPUTS(p);
   943    943   
   944    944     if( rc!=SQLITE_OK ){
   945    945       if( rc==SQLITE_NOMEM ){
   946         -      pParse->db->mallocFailed = 1;
          946  +      sqlite3OomFault(pParse->db);
   947    947       }else if( !pVtab->zErrMsg ){
   948    948         sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
   949    949       }else{
   950    950         sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
   951    951       }
   952    952     }
   953    953     sqlite3_free(pVtab->zErrMsg);
................................................................................
  1731   1731   /*
  1732   1732   ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
  1733   1733   */
  1734   1734   static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
  1735   1735     WhereTerm **paNew;
  1736   1736     if( p->nLSlot>=n ) return SQLITE_OK;
  1737   1737     n = (n+7)&~7;
  1738         -  paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
         1738  +  paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
  1739   1739     if( paNew==0 ) return SQLITE_NOMEM;
  1740   1740     memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
  1741   1741     if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  1742   1742     p->aLTerm = paNew;
  1743   1743     p->nLSlot = n;
  1744   1744     return SQLITE_OK;
  1745   1745   }
................................................................................
  2028   2028       }
  2029   2029       sqlite3DebugPrintf("    add: ");
  2030   2030       whereLoopPrint(pTemplate, pBuilder->pWC);
  2031   2031     }
  2032   2032   #endif
  2033   2033     if( p==0 ){
  2034   2034       /* Allocate a new WhereLoop to add to the end of the list */
  2035         -    *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
         2035  +    *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
  2036   2036       if( p==0 ) return SQLITE_NOMEM;
  2037   2037       whereLoopInit(p);
  2038   2038       p->pNextLoop = 0;
  2039   2039     }else{
  2040   2040       /* We will be overwriting WhereLoop p[].  But before we do, first
  2041   2041       ** go through the rest of the list and delete any other entries besides
  2042   2042       ** p[] that are also supplated by pTemplate */
................................................................................
  3525   3525     }else{
  3526   3526       nOrderBy = pWInfo->pOrderBy->nExpr;
  3527   3527     }
  3528   3528   
  3529   3529     /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
  3530   3530     nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
  3531   3531     nSpace += sizeof(LogEst) * nOrderBy;
  3532         -  pSpace = sqlite3DbMallocRaw(db, nSpace);
         3532  +  pSpace = sqlite3DbMallocRawNN(db, nSpace);
  3533   3533     if( pSpace==0 ) return SQLITE_NOMEM;
  3534   3534     aTo = (WherePath*)pSpace;
  3535   3535     aFrom = aTo+mxChoice;
  3536   3536     memset(aFrom, 0, sizeof(aFrom[0]));
  3537   3537     pX = (WhereLoop**)(aFrom+mxChoice);
  3538   3538     for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
  3539   3539       pFrom->aLoop = pX;

Changes to src/whereexpr.c.

    60     60   static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
    61     61     WhereTerm *pTerm;
    62     62     int idx;
    63     63     testcase( wtFlags & TERM_VIRTUAL );
    64     64     if( pWC->nTerm>=pWC->nSlot ){
    65     65       WhereTerm *pOld = pWC->a;
    66     66       sqlite3 *db = pWC->pWInfo->pParse->db;
    67         -    pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
           67  +    pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
    68     68       if( pWC->a==0 ){
    69     69         if( wtFlags & TERM_DYNAMIC ){
    70     70           sqlite3ExprDelete(db, p);
    71     71         }
    72     72         pWC->a = pOld;
    73     73         return 0;
    74     74       }
................................................................................
   545    545     indexable = ~(Bitmask)0;
   546    546     chngToIN = ~(Bitmask)0;
   547    547     for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
   548    548       if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
   549    549         WhereAndInfo *pAndInfo;
   550    550         assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
   551    551         chngToIN = 0;
   552         -      pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
          552  +      pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
   553    553         if( pAndInfo ){
   554    554           WhereClause *pAndWC;
   555    555           WhereTerm *pAndTerm;
   556    556           int j;
   557    557           Bitmask b = 0;
   558    558           pOrTerm->u.pAndInfo = pAndInfo;
   559    559           pOrTerm->wtFlags |= TERM_ANDINFO;
   560    560           pOrTerm->eOperator = WO_AND;
   561    561           pAndWC = &pAndInfo->wc;
   562    562           sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
   563    563           sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
   564    564           sqlite3WhereExprAnalyze(pSrc, pAndWC);
   565    565           pAndWC->pOuter = pWC;
   566         -        testcase( db->mallocFailed );
   567    566           if( !db->mallocFailed ){
   568    567             for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
   569    568               assert( pAndTerm->pExpr );
   570    569               if( allowedOp(pAndTerm->pExpr->op) ){
   571    570                 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
   572    571               }
   573    572             }