Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/sqlite/blob/master/ext/recover/sqlite3recover.c # sqlite [Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `sqlite / ext / recover / sqlite3recover.c` 3001 lines ยท 94021 bytes Raw Blame History 1 /* 2 ** 2022-08-27 3 ** 4 ** The author disclaims copyright to this source code. In place of 5 ** a legal notice, here is a blessing: 6 ** 7 ** May you do good and not evil. 8 ** May you find forgiveness for yourself and forgive others. 9 ** May you share freely, never taking more than you give. 10 ** 11 ************************************************************************* 12 ** 13 */ 14 15 16 #include "sqlite3recover.h" 17 #include 18 #include 19 20 #ifndef SQLITE_OMIT_VIRTUALTABLE 21 22 /* 23 ** Declaration for public API function in file dbdata.c. This may be called 24 ** with NULL as the final two arguments to register the sqlite_dbptr and 25 ** sqlite_dbdata virtual tables with a database handle. 26 */ 27 #ifdef _WIN32 28 __declspec(dllexport) 29 #endif 30 int sqlite3_dbdata_init(sqlite3*, char**, const sqlite3_api_routines*); 31 32 typedef unsigned int u32; 33 typedef unsigned char u8; 34 typedef sqlite3_int64 i64; 35 36 /* 37 ** Work around C99 "flex-array" syntax for pre-C99 compilers, so as 38 ** to avoid complaints from -fsanitize=strict-bounds. 39 */ 40 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) 41 # define FLEXARRAY 42 #else 43 # define FLEXARRAY 1 44 #endif 45 46 typedef struct RecoverTable RecoverTable; 47 typedef struct RecoverColumn RecoverColumn; 48 49 /* 50 ** When recovering rows of data that can be associated with table 51 ** definitions recovered from the sqlite_schema table, each table is 52 ** represented by an instance of the following object. 53 ** 54 ** iRoot: 55 ** The root page in the original database. Not necessarily (and usually 56 ** not) the same in the recovered database. 57 ** 58 ** zTab: 59 ** Name of the table. 60 ** 61 ** nCol/aCol[]: 62 ** aCol[] is an array of nCol columns. In the order in which they appear 63 ** in the table. 64 ** 65 ** nField: 66 ** The number of fields in each record of the table's b-tree. This may 67 ** be less than nCol (VIRTUAL generated columns have no field) or, for 68 ** a WITHOUT ROWID table with a column that appears more than once in 69 ** the PRIMARY KEY, greater than nCol. 70 ** 71 ** bIntkey: 72 ** Set to true for intkey tables, false for WITHOUT ROWID. 73 ** 74 ** iRowidBind: 75 ** Each column in the aCol[] array has associated with it the index of 76 ** the bind parameter its values will be bound to in the INSERT statement 77 ** used to construct the output database. If the table does has a rowid 78 ** but not an INTEGER PRIMARY KEY column, then iRowidBind contains the 79 ** index of the bind paramater to which the rowid value should be bound. 80 ** Otherwise, it contains -1. If the table does contain an INTEGER PRIMARY 81 ** KEY column, then the rowid value should be bound to the index associated 82 ** with the column. 83 ** 84 ** zRowid: 85 ** If iRowidBind>0, the name used to refer to the rowid in the INSERT 86 ** statement. This is the first of "_rowid_", "rowid" and "oid" that is 87 ** not also the name of a column. If all three are column names, the 88 ** rowid cannot be written and iRowidBind is 0. 89 ** 90 ** pNext: 91 ** All RecoverTable objects used by the recovery operation are allocated 92 ** and populated as part of creating the recovered database schema in 93 ** the output database, before any non-schema data are recovered. They 94 ** are then stored in a singly-linked list linked by this variable beginning 95 ** at sqlite3_recover.pTblList. 96 */ 97 struct RecoverTable { 98 u32 iRoot; /* Root page in original database */ 99 char *zTab; /* Name of table */ 100 int nCol; /* Number of columns in table */ 101 int nField; /* Number of fields in each record */ 102 RecoverColumn *aCol; /* Array of columns */ 103 int bIntkey; /* True for intkey, false for without rowid */ 104 int iRowidBind; /* If >0, bind rowid to INSERT here */ 105 const char *zRowid; /* Name to use for rowid in INSERT */ 106 RecoverTable *pNext; 107 }; 108 109 /* 110 ** Each database column is represented by an instance of the following object 111 ** stored in the RecoverTable.aCol[] array of the associated table. 112 ** 113 ** iField: 114 ** The index of the associated field within database records. Or -1 if 115 ** there is no associated field (e.g. for virtual generated columns). 116 ** 117 ** iBind: 118 ** The bind index of the INSERT statement to bind this columns values 119 ** to. Or 0 if there is no such index (iff (iField<0)). 120 ** 121 ** bIPK: 122 ** True if this is the INTEGER PRIMARY KEY column. 123 ** 124 ** zCol: 125 ** Name of column. 126 ** 127 ** eHidden: 128 ** A RECOVER_EHIDDEN_* constant value (see below for interpretation of each). 129 */ 130 struct RecoverColumn { 131 int iField; /* Field in record on disk */ 132 int iBind; /* Binding to use in INSERT */ 133 int bIPK; /* True for IPK column */ 134 char *zCol; 135 int eHidden; 136 }; 137 138 #define RECOVER_EHIDDEN_NONE 0 /* Normal database column */ 139 #define RECOVER_EHIDDEN_HIDDEN 1 /* Column is __HIDDEN__ */ 140 #define RECOVER_EHIDDEN_VIRTUAL 2 /* Virtual generated column */ 141 #define RECOVER_EHIDDEN_STORED 3 /* Stored generated column */ 142 143 /* 144 ** Bitmap object used to track pages in the input database. Allocated 145 ** and manipulated only by the following functions: 146 ** 147 ** recoverBitmapAlloc() 148 ** recoverBitmapFree() 149 ** recoverBitmapSet() 150 ** recoverBitmapQuery() 151 ** 152 ** nPg: 153 ** Largest page number that may be stored in the bitmap. The range 154 ** of valid keys is 1 to nPg, inclusive. 155 ** 156 ** aElem[]: 157 ** Array large enough to contain a bit for each key. For key value 158 ** iKey, the associated bit is the bit (iKey%32) of aElem[iKey/32]. 159 ** In other words, the following is true if bit iKey is set, or 160 ** false if it is clear: 161 ** 162 ** (aElem[iKey/32] & (1 << (iKey%32))) ? 1 : 0 163 */ 164 typedef struct RecoverBitmap RecoverBitmap; 165 struct RecoverBitmap { 166 i64 nPg; /* Size of bitmap */ 167 u32 aElem[FLEXARRAY]; /* Array of 32-bit bitmasks */ 168 }; 169 170 /* Size in bytes of a RecoverBitmap object sufficient to cover 32 pages */ 171 #define SZ_RECOVERBITMAP_32 (16) 172 173 /* 174 ** State variables (part of the sqlite3_recover structure) used while 175 ** recovering data for tables identified in the recovered schema (state 176 ** RECOVER_STATE_WRITING). 177 */ 178 typedef struct RecoverStateW1 RecoverStateW1; 179 struct RecoverStateW1 { 180 sqlite3_stmt *pTbls; 181 sqlite3_stmt *pSel; 182 sqlite3_stmt *pInsert; 183 int nInsert; 184 185 RecoverTable *pTab; /* Table currently being written */ 186 int nMax; /* Max field count in any schema table */ 187 sqlite3_value **apVal; /* Array of nMax values */ 188 int nVal; /* Number of valid entries in apVal[] */ 189 int bHaveRowid; 190 i64 iRowid; 191 i64 iPrevPage; 192 int iPrevCell; 193 }; 194 195 /* 196 ** State variables (part of the sqlite3_recover structure) used while 197 ** recovering data destined for the lost and found table (states 198 ** RECOVER_STATE_LOSTANDFOUND[123]). 199 */ 200 typedef struct RecoverStateLAF RecoverStateLAF; 201 struct RecoverStateLAF { 202 RecoverBitmap *pUsed; 203 i64 nPg; /* Size of db in pages */ 204 sqlite3_stmt *pAllAndParent; 205 sqlite3_stmt *pMapInsert; 206 sqlite3_stmt *pMaxField; 207 sqlite3_stmt *pUsedPages; 208 sqlite3_stmt *pFindRoot; 209 sqlite3_stmt *pInsert; /* INSERT INTO lost_and_found ... */ 210 sqlite3_stmt *pAllPage; 211 sqlite3_stmt *pPageData; 212 sqlite3_value **apVal; 213 int nMaxField; 214 }; 215 216 /* 217 ** Main recover handle structure. 218 */ 219 struct sqlite3_recover { 220 /* Copies of sqlite3_recover_init[_sql]() parameters */ 221 sqlite3 *dbIn; /* Input database */ 222 char *zDb; /* Name of input db ("main" etc.) */ 223 char *zUri; /* URI for output database */ 224 void *pSqlCtx; /* SQL callback context */ 225 int (*xSql)(void*,const char*); /* Pointer to SQL callback function */ 226 227 /* Values configured by sqlite3_recover_config() */ 228 char *zStateDb; /* State database to use (or NULL) */ 229 char *zLostAndFound; /* Name of lost-and-found table (or NULL) */ 230 int bFreelistCorrupt; /* SQLITE_RECOVER_FREELIST_CORRUPT setting */ 231 int bRecoverRowid; /* SQLITE_RECOVER_ROWIDS setting */ 232 int bSlowIndexes; /* SQLITE_RECOVER_SLOWINDEXES setting */ 233 234 int pgsz; 235 int detected_pgsz; 236 int nReserve; 237 u8 *pPage1Disk; 238 u8 *pPage1Cache; 239 240 /* Error code and error message */ 241 int errCode; /* For sqlite3_recover_errcode() */ 242 char *zErrMsg; /* For sqlite3_recover_errmsg() */ 243 244 int eState; 245 int bCloseTransaction; 246 247 /* Variables used with eState==RECOVER_STATE_WRITING */ 248 RecoverStateW1 w1; 249 250 /* Variables used with states RECOVER_STATE_LOSTANDFOUND[123] */ 251 RecoverStateLAF laf; 252 253 /* Fields used within sqlite3_recover_run() */ 254 sqlite3 *dbOut; /* Output database */ 255 sqlite3_stmt *pGetPage; /* SELECT against input db sqlite_dbdata */ 256 RecoverTable *pTblList; /* List of tables recovered from schema */ 257 }; 258 259 /* 260 ** The various states in which an sqlite3_recover object may exist: 261 ** 262 ** RECOVER_STATE_INIT: 263 ** The object is initially created in this state. sqlite3_recover_step() 264 ** has yet to be called. This is the only state in which it is permitted 265 ** to call sqlite3_recover_config(). 266 ** 267 ** RECOVER_STATE_WRITING: 268 ** 269 ** RECOVER_STATE_LOSTANDFOUND1: 270 ** State to populate the bitmap of pages used by other tables or the 271 ** database freelist. 272 ** 273 ** RECOVER_STATE_LOSTANDFOUND2: 274 ** Populate the recovery.map table - used to figure out a "root" page 275 ** for each lost page from in the database from which records are 276 ** extracted. 277 ** 278 ** RECOVER_STATE_LOSTANDFOUND3: 279 ** Populate the lost-and-found table itself. 280 */ 281 #define RECOVER_STATE_INIT 0 282 #define RECOVER_STATE_WRITING 1 283 #define RECOVER_STATE_LOSTANDFOUND1 2 284 #define RECOVER_STATE_LOSTANDFOUND2 3 285 #define RECOVER_STATE_LOSTANDFOUND3 4 286 #define RECOVER_STATE_SCHEMA2 5 287 #define RECOVER_STATE_DONE 6 288 289 290 /* 291 ** Global variables used by this extension. 292 */ 293 typedef struct RecoverGlobal RecoverGlobal; 294 struct RecoverGlobal { 295 const sqlite3_io_methods *pMethods; 296 sqlite3_recover *p; 297 }; 298 static RecoverGlobal recover_g; 299 300 /* 301 ** Use this static SQLite mutex to protect the globals during the 302 ** first call to sqlite3_recover_step(). 303 */ 304 #define RECOVER_MUTEX_ID SQLITE_MUTEX_STATIC_APP2 305 306 307 /* 308 ** Default value for SQLITE_RECOVER_ROWIDS (sqlite3_recover.bRecoverRowid). 309 */ 310 #define RECOVER_ROWID_DEFAULT 1 311 312 /* 313 ** Mutex handling: 314 ** 315 ** recoverEnterMutex() - Enter the recovery mutex 316 ** recoverLeaveMutex() - Leave the recovery mutex 317 ** recoverAssertMutexHeld() - Assert that the recovery mutex is held 318 */ 319 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0 320 # define recoverEnterMutex() 321 # define recoverLeaveMutex() 322 #else 323 static void recoverEnterMutex(void){ 324 sqlite3_mutex_enter(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)); 325 } 326 static void recoverLeaveMutex(void){ 327 sqlite3_mutex_leave(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)); 328 } 329 #endif 330 #if SQLITE_THREADSAFE+0>=1 && defined(SQLITE_DEBUG) 331 static void recoverAssertMutexHeld(void){ 332 assert( sqlite3_mutex_held(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)) ); 333 } 334 #else 335 # define recoverAssertMutexHeld() 336 #endif 337 338 339 /* 340 ** Like strlen(). But handles NULL pointer arguments. 341 */ 342 static int recoverStrlen(const char *zStr){ 343 if( zStr==0 ) return 0; 344 return (int)(strlen(zStr)&0x7fffffff); 345 } 346 347 /* 348 ** This function is a no-op if the recover handle passed as the first 349 ** argument already contains an error (if p->errCode!=SQLITE_OK). 350 ** 351 ** Otherwise, an attempt is made to allocate, zero and return a buffer nByte 352 ** bytes in size. If successful, a pointer to the new buffer is returned. Or, 353 ** if an OOM error occurs, NULL is returned and the handle error code 354 ** (p->errCode) set to SQLITE_NOMEM. 355 */ 356 static void *recoverMalloc(sqlite3_recover *p, i64 nByte){ 357 void *pRet = 0; 358 assert( nByte>0 ); 359 if( p->errCode==SQLITE_OK ){ 360 pRet = sqlite3_malloc64(nByte); 361 if( pRet ){ 362 memset(pRet, 0, nByte); 363 }else{ 364 p->errCode = SQLITE_NOMEM; 365 } 366 } 367 return pRet; 368 } 369 370 /* 371 ** Set the error code and error message for the recover handle passed as 372 ** the first argument. The error code is set to the value of parameter 373 ** errCode. 374 ** 375 ** Parameter zFmt must be a printf() style formatting string. The handle 376 ** error message is set to the result of using any trailing arguments for 377 ** parameter substitutions in the formatting string. 378 ** 379 ** For example: 380 ** 381 ** recoverError(p, SQLITE_ERROR, "no such table: %s", zTablename); 382 */ 383 static int recoverError( 384 sqlite3_recover *p, 385 int errCode, 386 const char *zFmt, ... 387 ){ 388 char *z = 0; 389 va_list ap; 390 va_start(ap, zFmt); 391 if( zFmt ){ 392 z = sqlite3_vmprintf(zFmt, ap); 393 } 394 va_end(ap); 395 sqlite3_free(p->zErrMsg); 396 p->zErrMsg = z; 397 p->errCode = errCode; 398 return errCode; 399 } 400 401 402 /* 403 ** This function is a no-op if p->errCode is initially other than SQLITE_OK. 404 ** In this case it returns NULL. 405 ** 406 ** Otherwise, an attempt is made to allocate and return a bitmap object 407 ** large enough to store a bit for all page numbers between 1 and nPg, 408 ** inclusive. The bitmap is initially zeroed. 409 */ 410 static RecoverBitmap *recoverBitmapAlloc(sqlite3_recover *p, i64 nPg){ 411 int nElem = (nPg+1+31) / 32; 412 int nByte = SZ_RECOVERBITMAP_32 + nElem*sizeof(u32); 413 RecoverBitmap *pRet = (RecoverBitmap*)recoverMalloc(p, nByte); 414 415 if( pRet ){ 416 pRet->nPg = nPg; 417 } 418 return pRet; 419 } 420 421 /* 422 ** Free a bitmap object allocated by recoverBitmapAlloc(). 423 */ 424 static void recoverBitmapFree(RecoverBitmap *pMap){ 425 sqlite3_free(pMap); 426 } 427 428 /* 429 ** Set the bit associated with page iPg in bitvec pMap. 430 */ 431 static void recoverBitmapSet(RecoverBitmap *pMap, i64 iPg){ 432 if( iPg<=pMap->nPg && iPg>0 ){ 433 int iElem = (iPg / 32); 434 int iBit = (iPg % 32); 435 pMap->aElem[iElem] |= (((u32)1) << iBit); 436 } 437 } 438 439 /* 440 ** Query bitmap object pMap for the state of the bit associated with page 441 ** iPg. Return 1 if it is set, or 0 otherwise. 442 */ 443 static int recoverBitmapQuery(RecoverBitmap *pMap, i64 iPg){ 444 int ret = 1; 445 if( iPg<=pMap->nPg && iPg>0 ){ 446 int iElem = (iPg / 32); 447 int iBit = (iPg % 32); 448 ret = (pMap->aElem[iElem] & (((u32)1) << iBit)) ? 1 : 0; 449 } 450 return ret; 451 } 452 453 /* 454 ** Set the recover handle error to the error code and message returned by 455 ** calling sqlite3_errcode() and sqlite3_errmsg(), respectively, on database 456 ** handle db. 457 */ 458 static int recoverDbError(sqlite3_recover *p, sqlite3 *db){ 459 return recoverError(p, sqlite3_errcode(db), "%s", sqlite3_errmsg(db)); 460 } 461 462 /* 463 ** This function is a no-op if recover handle p already contains an error 464 ** (if p->errCode!=SQLITE_OK). 465 ** 466 ** Otherwise, it attempts to prepare the SQL statement in zSql against 467 ** database handle db. If successful, the statement handle is returned. 468 ** Or, if an error occurs, NULL is returned and an error left in the 469 ** recover handle. 470 */ 471 static sqlite3_stmt *recoverPrepare( 472 sqlite3_recover *p, 473 sqlite3 *db, 474 const char *zSql 475 ){ 476 sqlite3_stmt *pStmt = 0; 477 if( p->errCode==SQLITE_OK ){ 478 if( sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) ){ 479 recoverDbError(p, db); 480 } 481 } 482 return pStmt; 483 } 484 485 /* 486 ** This function is a no-op if recover handle p already contains an error 487 ** (if p->errCode!=SQLITE_OK). 488 ** 489 ** Otherwise, argument zFmt is used as a printf() style format string, 490 ** along with any trailing arguments, to create an SQL statement. This 491 ** SQL statement is prepared against database handle db and, if successful, 492 ** the statment handle returned. Or, if an error occurs - either during 493 ** the printf() formatting or when preparing the resulting SQL - an 494 ** error code and message are left in the recover handle. 495 */ 496 static sqlite3_stmt *recoverPreparePrintf( 497 sqlite3_recover *p, 498 sqlite3 *db, 499 const char *zFmt, ... 500 ){ 501 sqlite3_stmt *pStmt = 0; 502 if( p->errCode==SQLITE_OK ){ 503 va_list ap; 504 char *z; 505 va_start(ap, zFmt); 506 z = sqlite3_vmprintf(zFmt, ap); 507 va_end(ap); 508 if( z==0 ){ 509 p->errCode = SQLITE_NOMEM; 510 }else{ 511 pStmt = recoverPrepare(p, db, z); 512 sqlite3_free(z); 513 } 514 } 515 return pStmt; 516 } 517 518 /* 519 ** Reset SQLite statement handle pStmt. If the call to sqlite3_reset() 520 ** indicates that an error occurred, and there is not already an error 521 ** in the recover handle passed as the first argument, set the error 522 ** code and error message appropriately. 523 ** 524 ** This function returns a copy of the statement handle pointer passed 525 ** as the second argument. 526 */ 527 static sqlite3_stmt *recoverReset(sqlite3_recover *p, sqlite3_stmt *pStmt){ 528 int rc = sqlite3_reset(pStmt); 529 if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT && p->errCode==SQLITE_OK ){ 530 recoverDbError(p, sqlite3_db_handle(pStmt)); 531 } 532 return pStmt; 533 } 534 535 /* 536 ** Finalize SQLite statement handle pStmt. If the call to sqlite3_reset() 537 ** indicates that an error occurred, and there is not already an error 538 ** in the recover handle passed as the first argument, set the error 539 ** code and error message appropriately. 540 */ 541 static void recoverFinalize(sqlite3_recover *p, sqlite3_stmt *pStmt){ 542 sqlite3 *db = sqlite3_db_handle(pStmt); 543 int rc = sqlite3_finalize(pStmt); 544 if( rc!=SQLITE_OK && p->errCode==SQLITE_OK ){ 545 recoverDbError(p, db); 546 } 547 } 548 549 /* 550 ** Run a single SQL statement in zSql. If zSql contains two or more 551 ** SQL statements separated by ';', only the first is run. 552 ** 553 ** Return the sqlite3_finalizer() or sqlite3_prepare() result code 554 ** from running the zSql statement. 555 */ 556 static int recoverOneStmt(sqlite3 *db, const char *zSql, const char **pzTail){ 557 sqlite3_stmt *pStmt = 0; 558 int rc; 559 if( zSql==0 ) return SQLITE_OK; 560 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, pzTail); 561 if( rc ){ 562 sqlite3_finalize(pStmt); 563 return rc; 564 } 565 while( SQLITE_ROW==sqlite3_step(pStmt) ){} 566 return sqlite3_finalize(pStmt); 567 } 568 569 /* 570 ** This function is a no-op if recover handle p already contains an error 571 ** (if p->errCode!=SQLITE_OK). A copy of p->errCode is returned in this 572 ** case. 573 ** 574 ** Otherwise, execute a single SQL statment in zSql. Even if zSql contains 575 ** two or more SQL statements separated by ';', only execute the first one. 576 ** If successful, return SQLITE_OK. Or, if an error occurs, leave an error 577 ** code and message in the recover handle and return a copy of the error code. 578 */ 579 static int recoverExec(sqlite3_recover *p, sqlite3 *db, const char *zSql){ 580 if( p->errCode==SQLITE_OK ){ 581 int rc = recoverOneStmt(db, zSql, 0); 582 if( rc ){ 583 recoverDbError(p, db); 584 } 585 } 586 return p->errCode; 587 } 588 589 /* 590 ** Bind the value pVal to parameter iBind of statement pStmt. Leave an 591 ** error in the recover handle passed as the first argument if an error 592 ** (e.g. an OOM) occurs. 593 */ 594 static void recoverBindValue( 595 sqlite3_recover *p, 596 sqlite3_stmt *pStmt, 597 int iBind, 598 sqlite3_value *pVal 599 ){ 600 if( p->errCode==SQLITE_OK ){ 601 int rc = sqlite3_bind_value(pStmt, iBind, pVal); 602 if( rc ) recoverError(p, rc, 0); 603 } 604 } 605 606 /* 607 ** This function is a no-op if recover handle p already contains an error 608 ** (if p->errCode!=SQLITE_OK). NULL is returned in this case. 609 ** 610 ** Otherwise, an attempt is made to interpret zFmt as a printf() style 611 ** formatting string and the result of using the trailing arguments for 612 ** parameter substitution with it written into a buffer obtained from 613 ** sqlite3_malloc(). If successful, a pointer to the buffer is returned. 614 ** It is the responsibility of the caller to eventually free the buffer 615 ** using sqlite3_free(). 616 ** 617 ** Or, if an error occurs, an error code and message is left in the recover 618 ** handle and NULL returned. 619 */ 620 static char *recoverMPrintf(sqlite3_recover *p, const char *zFmt, ...){ 621 va_list ap; 622 char *z; 623 va_start(ap, zFmt); 624 z = sqlite3_vmprintf(zFmt, ap); 625 va_end(ap); 626 if( p->errCode==SQLITE_OK ){ 627 if( z==0 ) p->errCode = SQLITE_NOMEM; 628 }else{ 629 sqlite3_free(z); 630 z = 0; 631 } 632 return z; 633 } 634 635 /* 636 ** This function is a no-op if recover handle p already contains an error 637 ** (if p->errCode!=SQLITE_OK). Zero is returned in this case. 638 ** 639 ** Otherwise, execute "PRAGMA page_count" against the input database. If 640 ** successful, return the integer result. Or, if an error occurs, leave an 641 ** error code and error message in the sqlite3_recover handle and return 642 ** zero. 643 */ 644 static i64 recoverPageCount(sqlite3_recover *p){ 645 i64 nPg = 0; 646 if( p->errCode==SQLITE_OK ){ 647 sqlite3_stmt *pStmt = 0; 648 pStmt = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.page_count", p->zDb); 649 if( pStmt ){ 650 sqlite3_step(pStmt); 651 nPg = sqlite3_column_int64(pStmt, 0); 652 } 653 recoverFinalize(p, pStmt); 654 } 655 return nPg; 656 } 657 658 /* 659 ** Implementation of SQL scalar function "read_i32". The first argument to 660 ** this function must be a blob. The second a non-negative integer. This 661 ** function reads and returns a 32-bit big-endian integer from byte 662 ** offset (4*) of the blob. 663 ** 664 ** SELECT read_i32(, ) 665 */ 666 static void recoverReadI32( 667 sqlite3_context *context, 668 int argc, 669 sqlite3_value **argv 670 ){ 671 const unsigned char *pBlob; 672 int nBlob; 673 int iInt; 674 675 assert( argc==2 ); 676 nBlob = sqlite3_value_bytes(argv[0]); 677 pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]); 678 iInt = sqlite3_value_int(argv[1]) & 0xFFFF; 679 680 if( (iInt+1)*4<=nBlob ){ 681 const unsigned char *a = &pBlob[iInt*4]; 682 i64 iVal = ((i64)a[0]<<24) 683 + ((i64)a[1]<<16) 684 + ((i64)a[2]<< 8) 685 + ((i64)a[3]<< 0); 686 sqlite3_result_int64(context, iVal); 687 } 688 } 689 690 /* 691 ** Implementation of SQL scalar function "page_is_used". This function 692 ** is used as part of the procedure for locating orphan rows for the 693 ** lost-and-found table, and it depends on those routines having populated 694 ** the sqlite3_recover.laf.pUsed variable. 695 ** 696 ** The only argument to this function is a page-number. It returns true 697 ** if the page has already been used somehow during data recovery, or false 698 ** otherwise. 699 ** 700 ** SELECT page_is_used(); 701 */ 702 static void recoverPageIsUsed( 703 sqlite3_context *pCtx, 704 int nArg, 705 sqlite3_value **apArg 706 ){ 707 sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx); 708 i64 pgno = sqlite3_value_int64(apArg[0]); 709 assert( nArg==1 ); 710 sqlite3_result_int(pCtx, recoverBitmapQuery(p->laf.pUsed, pgno)); 711 } 712 713 /* 714 ** The implementation of a user-defined SQL function invoked by the 715 ** sqlite_dbdata and sqlite_dbptr virtual table modules to access pages 716 ** of the database being recovered. 717 ** 718 ** This function always takes a single integer argument. If the argument 719 ** is zero, then the value returned is the number of pages in the db being 720 ** recovered. If the argument is greater than zero, it is a page number. 721 ** The value returned in this case is an SQL blob containing the data for 722 ** the identified page of the db being recovered. e.g. 723 ** 724 ** SELECT getpage(0); -- return number of pages in db 725 ** SELECT getpage(4); -- return page 4 of db as a blob of data 726 */ 727 static void recoverGetPage( 728 sqlite3_context *pCtx, 729 int nArg, 730 sqlite3_value **apArg 731 ){ 732 sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx); 733 i64 pgno = sqlite3_value_int64(apArg[0]); 734 sqlite3_stmt *pStmt = 0; 735 736 assert( nArg==1 ); 737 if( pgno==0 ){ 738 i64 nPg = recoverPageCount(p); 739 sqlite3_result_int64(pCtx, nPg); 740 return; 741 }else{ 742 if( p->pGetPage==0 ){ 743 pStmt = p->pGetPage = recoverPreparePrintf( 744 p, p->dbIn, "SELECT data FROM sqlite_dbpage(%Q) WHERE pgno=?", p->zDb 745 ); 746 }else if( p->errCode==SQLITE_OK ){ 747 pStmt = p->pGetPage; 748 } 749 750 if( pStmt ){ 751 sqlite3_bind_int64(pStmt, 1, pgno); 752 if( SQLITE_ROW==sqlite3_step(pStmt) ){ 753 const u8 *aPg; 754 int nPg; 755 assert( p->errCode==SQLITE_OK ); 756 aPg = sqlite3_column_blob(pStmt, 0); 757 nPg = sqlite3_column_bytes(pStmt, 0); 758 if( pgno==1 && nPg==p->pgsz && 0==memcmp(p->pPage1Cache, aPg, nPg) ){ 759 aPg = p->pPage1Disk; 760 } 761 sqlite3_result_blob(pCtx, aPg, nPg-p->nReserve, SQLITE_TRANSIENT); 762 } 763 recoverReset(p, pStmt); 764 } 765 } 766 767 if( p->errCode ){ 768 if( p->zErrMsg ) sqlite3_result_error(pCtx, p->zErrMsg, -1); 769 sqlite3_result_error_code(pCtx, p->errCode); 770 } 771 } 772 773 /* 774 ** Find a string that is not found anywhere in z[]. Return a pointer 775 ** to that string. 776 ** 777 ** Try to use zA and zB first. If both of those are already found in z[] 778 ** then make up some string and store it in the buffer zBuf. 779 */ 780 static const char *recoverUnusedString( 781 const char *z, /* Result must not appear anywhere in z */ 782 const char *zA, const char *zB, /* Try these first */ 783 char *zBuf /* Space to store a generated string */ 784 ){ 785 unsigned i = 0; 786 if( strstr(z, zA)==0 ) return zA; 787 if( strstr(z, zB)==0 ) return zB; 788 do{ 789 sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++); 790 }while( strstr(z,zBuf)!=0 ); 791 return zBuf; 792 } 793 794 /* 795 ** Implementation of scalar SQL function "escape_crlf". The argument passed to 796 ** this function is the output of built-in function quote(). If the first 797 ** character of the input is "'", indicating that the value passed to quote() 798 ** was a text value, then this function searches the input for "\n" and "\r" 799 ** characters and adds a wrapper similar to the following: 800 ** 801 ** replace(replace(, '\n', char(10), '\r', char(13)); 802 ** 803 ** Or, if the first character of the input is not "'", then a copy of the input 804 ** is returned. 805 */ 806 static void recoverEscapeCrlf( 807 sqlite3_context *context, 808 int argc, 809 sqlite3_value **argv 810 ){ 811 const char *zText = (const char*)sqlite3_value_text(argv[0]); 812 (void)argc; 813 if( zText && zText[0]=='\'' ){ 814 int nText = sqlite3_value_bytes(argv[0]); 815 int i; 816 char zBuf1[20]; 817 char zBuf2[20]; 818 const char *zNL = 0; 819 const char *zCR = 0; 820 int nCR = 0; 821 int nNL = 0; 822 823 for(i=0; zText[i]; i++){ 824 if( zNL==0 && zText[i]=='\n' ){ 825 zNL = recoverUnusedString(zText, "\\n", "\\012", zBuf1); 826 nNL = (int)strlen(zNL); 827 } 828 if( zCR==0 && zText[i]=='\r' ){ 829 zCR = recoverUnusedString(zText, "\\r", "\\015", zBuf2); 830 nCR = (int)strlen(zCR); 831 } 832 } 833 834 if( zNL || zCR ){ 835 int iOut = 0; 836 i64 nMax = (nNL > nCR) ? nNL : nCR; 837 i64 nAlloc = nMax * nText + (nMax+64)*2; 838 char *zOut = (char*)sqlite3_malloc64(nAlloc); 839 if( zOut==0 ){ 840 sqlite3_result_error_nomem(context); 841 return; 842 } 843 844 if( zNL && zCR ){ 845 memcpy(&zOut[iOut], "replace(replace(", 16); 846 iOut += 16; 847 }else{ 848 memcpy(&zOut[iOut], "replace(", 8); 849 iOut += 8; 850 } 851 for(i=0; zText[i]; i++){ 852 if( zText[i]=='\n' ){ 853 memcpy(&zOut[iOut], zNL, nNL); 854 iOut += nNL; 855 }else if( zText[i]=='\r' ){ 856 memcpy(&zOut[iOut], zCR, nCR); 857 iOut += nCR; 858 }else{ 859 zOut[iOut] = zText[i]; 860 iOut++; 861 } 862 } 863 864 if( zNL ){ 865 memcpy(&zOut[iOut], ",'", 2); iOut += 2; 866 memcpy(&zOut[iOut], zNL, nNL); iOut += nNL; 867 memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12; 868 } 869 if( zCR ){ 870 memcpy(&zOut[iOut], ",'", 2); iOut += 2; 871 memcpy(&zOut[iOut], zCR, nCR); iOut += nCR; 872 memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12; 873 } 874 875 sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT); 876 sqlite3_free(zOut); 877 return; 878 } 879 } 880 881 sqlite3_result_value(context, argv[0]); 882 } 883 884 /* 885 ** This function is a no-op if recover handle p already contains an error 886 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in 887 ** this case. 888 ** 889 ** Otherwise, attempt to populate temporary table "recovery.schema" with the 890 ** parts of the database schema that can be extracted from the input database. 891 ** 892 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code 893 ** and error message are left in the recover handle and a copy of the 894 ** error code returned. It is not considered an error if part of all of 895 ** the database schema cannot be recovered due to corruption. 896 */ 897 static int recoverCacheSchema(sqlite3_recover *p){ 898 return recoverExec(p, p->dbOut, 899 "WITH RECURSIVE pages(p) AS (" 900 " SELECT 1" 901 " UNION" 902 " SELECT child FROM sqlite_dbptr('getpage()'), pages WHERE pgno=p" 903 ")" 904 "INSERT INTO recovery.schema SELECT" 905 " max(CASE WHEN field=0 THEN value ELSE NULL END)," 906 " max(CASE WHEN field=1 THEN value ELSE NULL END)," 907 " max(CASE WHEN field=2 THEN value ELSE NULL END)," 908 " max(CASE WHEN field=3 THEN value ELSE NULL END)," 909 " max(CASE WHEN field=4 THEN value ELSE NULL END)" 910 "FROM sqlite_dbdata('getpage()') WHERE pgno IN (" 911 " SELECT p FROM pages" 912 ") GROUP BY pgno, cell" 913 ); 914 } 915 916 /* 917 ** If this recover handle is not in SQL callback mode (i.e. was not created 918 ** using sqlite3_recover_init_sql()) of if an error has already occurred, 919 ** this function is a no-op. Otherwise, issue a callback with SQL statement 920 ** zSql as the parameter. 921 ** 922 ** If the callback returns non-zero, set the recover handle error code to 923 ** the value returned (so that the caller will abandon processing). 924 */ 925 static void recoverSqlCallback(sqlite3_recover *p, const char *zSql){ 926 if( p->errCode==SQLITE_OK && p->xSql ){ 927 int res = p->xSql(p->pSqlCtx, zSql); 928 if( res ){ 929 recoverError(p, SQLITE_ERROR, "callback returned an error - %d", res); 930 } 931 } 932 } 933 934 /* 935 ** Transfer the following settings from the input database to the output 936 ** database: 937 ** 938 ** + page-size, 939 ** + auto-vacuum settings, 940 ** + database encoding, 941 ** + user-version (PRAGMA user_version), and 942 ** + application-id (PRAGMA application_id), and 943 */ 944 static void recoverTransferSettings(sqlite3_recover *p){ 945 const char *aPragma[] = { 946 "encoding", 947 "page_size", 948 "auto_vacuum", 949 "user_version", 950 "application_id" 951 }; 952 int ii; 953 954 /* Truncate the output database to 0 pages in size. This is done by 955 ** opening a new, empty, temp db, then using the backup API to clobber 956 ** any existing output db with a copy of it. */ 957 if( p->errCode==SQLITE_OK ){ 958 sqlite3 *db2 = 0; 959 int rc = sqlite3_open("", &db2); 960 if( rc!=SQLITE_OK ){ 961 recoverDbError(p, db2); 962 return; 963 } 964 965 for(ii=0; ii<(int)(sizeof(aPragma)/sizeof(aPragma[0])); ii++){ 966 const char *zPrag = aPragma[ii]; 967 sqlite3_stmt *p1 = 0; 968 p1 = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.%s", p->zDb, zPrag); 969 if( p->errCode==SQLITE_OK && sqlite3_step(p1)==SQLITE_ROW ){ 970 const char *zArg = (const char*)sqlite3_column_text(p1, 0); 971 char *z2 = recoverMPrintf(p, "PRAGMA %s = %Q", zPrag, zArg); 972 recoverSqlCallback(p, z2); 973 recoverExec(p, db2, z2); 974 sqlite3_free(z2); 975 if( zArg==0 ){ 976 recoverError(p, SQLITE_NOMEM, 0); 977 } 978 } 979 recoverFinalize(p, p1); 980 } 981 recoverExec(p, db2, "CREATE TABLE t1(a)"); 982 recoverExec(p, db2, "DROP TABLE t1"); 983 984 if( p->errCode==SQLITE_OK ){ 985 sqlite3 *db = p->dbOut; 986 sqlite3_backup *pBackup = sqlite3_backup_init(db, "main", db2, "main"); 987 if( pBackup ){ 988 sqlite3_backup_step(pBackup, -1); 989 p->errCode = sqlite3_backup_finish(pBackup); 990 }else{ 991 recoverDbError(p, db); 992 } 993 } 994 995 sqlite3_close(db2); 996 } 997 } 998 999 /* 1000 ** This function is a no-op if recover handle p already contains an error 1001 ** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in 1002 ** this case. 1003 ** 1004 ** Otherwise, an attempt is made to open the output database, attach 1005 ** and create the schema of the temporary database used to store 1006 ** intermediate data, and to register all required user functions and 1007 ** virtual table modules with the output handle. 1008 ** 1009 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code 1010 ** and error message are left in the recover handle and a copy of the 1011 ** error code returned. 1012 */ 1013 static int recoverOpenOutput(sqlite3_recover *p){ 1014 struct Func { 1015 const char *zName; 1016 int nArg; 1017 void (*xFunc)(sqlite3_context*,int,sqlite3_value **); 1018 } aFunc[] = { 1019 { "getpage", 1, recoverGetPage }, 1020 { "page_is_used", 1, recoverPageIsUsed }, 1021 { "read_i32", 2, recoverReadI32 }, 1022 { "escape_crlf", 1, recoverEscapeCrlf }, 1023 }; 1024 1025 const int flags = SQLITE_OPEN_URI|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE; 1026 sqlite3 *db = 0; /* New database handle */ 1027 int ii; /* For iterating through aFunc[] */ 1028 1029 assert( p->dbOut==0 ); 1030 1031 if( sqlite3_open_v2(p->zUri, &db, flags, 0) ){ 1032 recoverDbError(p, db); 1033 } 1034 1035 /* Register the sqlite_dbdata and sqlite_dbptr virtual table modules. 1036 ** These two are registered with the output database handle - this 1037 ** module depends on the input handle supporting the sqlite_dbpage 1038 ** virtual table only. */ 1039 if( p->errCode==SQLITE_OK ){ 1040 p->errCode = sqlite3_dbdata_init(db, 0, 0); 1041 } 1042 1043 /* Register the custom user-functions with the output handle. */ 1044 for(ii=0; 1045 p->errCode==SQLITE_OK && ii<(int)(sizeof(aFunc)/sizeof(aFunc[0])); 1046 ii++){ 1047 p->errCode = sqlite3_create_function(db, aFunc[ii].zName, 1048 aFunc[ii].nArg, SQLITE_UTF8, (void*)p, aFunc[ii].xFunc, 0, 0 1049 ); 1050 } 1051 1052 p->dbOut = db; 1053 return p->errCode; 1054 } 1055 1056 /* 1057 ** Attach the auxiliary database 'recovery' to the output database handle. 1058 ** This temporary database is used during the recovery process and then 1059 ** discarded. 1060 */ 1061 static void recoverOpenRecovery(sqlite3_recover *p){ 1062 char *zSql = recoverMPrintf(p, "ATTACH %Q AS recovery;", p->zStateDb); 1063 recoverExec(p, p->dbOut, zSql); 1064 sqlite3_free(zSql); 1065 recoverExec(p, p->dbOut, "PRAGMA writable_schema = 1"); 1066 recoverExec(p, p->dbOut, 1067 "CREATE TABLE recovery.map(pgno INTEGER PRIMARY KEY, parent INT)"); 1068 recoverExec(p, p->dbOut, 1069 "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql)"); 1070 } 1071 1072 1073 /* 1074 ** This function is a no-op if recover handle p already contains an error 1075 ** (if p->errCode!=SQLITE_OK). 1076 ** 1077 ** Otherwise, argument zName must be the name of a table that has just been 1078 ** created in the output database. This function queries the output db 1079 ** for the schema of said table, and creates a RecoverTable object to 1080 ** store the schema in memory. The new RecoverTable object is linked into 1081 ** the list at sqlite3_recover.pTblList. 1082 ** 1083 ** Parameter iRoot must be the root page of table zName in the INPUT 1084 ** database. 1085 */ 1086 static void recoverAddTable( 1087 sqlite3_recover *p, 1088 const char *zName, /* Name of table created in output db */ 1089 i64 iRoot /* Root page of same table in INPUT db */ 1090 ){ 1091 sqlite3_stmt *pStmt = recoverPreparePrintf(p, p->dbOut, 1092 "PRAGMA %Q.table_xinfo(%Q)", p->zDb, zName 1093 ); 1094 1095 if( pStmt ){ 1096 int iPk = -1; 1097 int iBind = 1; 1098 RecoverTable *pNew = 0; 1099 int nCol = 0; 1100 int nName = recoverStrlen(zName); 1101 int nByte = 0; 1102 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 1103 nCol++; 1104 nByte += (sqlite3_column_bytes(pStmt, 1)+1); 1105 } 1106 nByte += sizeof(RecoverTable) + nCol*sizeof(RecoverColumn) + nName+1; 1107 recoverReset(p, pStmt); 1108 1109 pNew = recoverMalloc(p, nByte); 1110 if( pNew ){ 1111 int i = 0; 1112 int iField = 0; 1113 char *csr = 0; 1114 pNew->aCol = (RecoverColumn*)&pNew[1]; 1115 pNew->zTab = csr = (char*)&pNew->aCol[nCol]; 1116 pNew->nCol = nCol; 1117 pNew->iRoot = iRoot; 1118 memcpy(csr, zName, nName); 1119 csr += nName+1; 1120 1121 for(i=0; sqlite3_step(pStmt)==SQLITE_ROW; i++){ 1122 int iPKF = sqlite3_column_int(pStmt, 5); 1123 int n = sqlite3_column_bytes(pStmt, 1); 1124 const char *z = (const char*)sqlite3_column_text(pStmt, 1); 1125 const char *zType = (const char*)sqlite3_column_text(pStmt, 2); 1126 int eHidden = sqlite3_column_int(pStmt, 6); 1127 1128 if( iPk==-1 && iPKF==1 && !sqlite3_stricmp("integer", zType) ) iPk = i; 1129 if( iPKF>1 ) iPk = -2; 1130 pNew->aCol[i].zCol = csr; 1131 pNew->aCol[i].eHidden = eHidden; 1132 if( eHidden==RECOVER_EHIDDEN_VIRTUAL ){ 1133 pNew->aCol[i].iField = -1; 1134 }else{ 1135 pNew->aCol[i].iField = iField++; 1136 } 1137 if( eHidden!=RECOVER_EHIDDEN_VIRTUAL 1138 && eHidden!=RECOVER_EHIDDEN_STORED 1139 ){ 1140 pNew->aCol[i].iBind = iBind++; 1141 } 1142 memcpy(csr, z, n); 1143 csr += (n+1); 1144 } 1145 1146 pNew->nField = iField; 1147 pNew->pNext = p->pTblList; 1148 p->pTblList = pNew; 1149 pNew->bIntkey = 1; 1150 } 1151 1152 recoverFinalize(p, pStmt); 1153 1154 /* If this is a WITHOUT ROWID table, the fields of each record are 1155 ** ordered as reported by PRAGMA index_xinfo on the table. A column may 1156 ** appear more than once if it is listed more than once in the PRIMARY 1157 ** KEY (with different collation sequences). In that case use the first 1158 ** field - the others are redundant copies. */ 1159 pStmt = recoverPreparePrintf(p, p->dbOut, 1160 "PRAGMA %Q.index_xinfo(%Q)", p->zDb, zName); 1161 while( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ 1162 int iField = sqlite3_column_int(pStmt, 0); 1163 int iCol = sqlite3_column_int(pStmt, 1); 1164 1165 assert( iCol>=0 && iColnCol ); 1166 if( pNew->bIntkey ){ 1167 int ii; 1168 for(ii=0; iinCol; ii++) pNew->aCol[ii].iField = -1; 1169 pNew->bIntkey = 0; 1170 } 1171 if( pNew->aCol[iCol].iField<0 ) pNew->aCol[iCol].iField = iField; 1172 pNew->nField = iField+1; 1173 iPk = -2; 1174 } 1175 recoverFinalize(p, pStmt); 1176 1177 /* A column declared as "INTEGER PRIMARY KEY DESC" is not an alias for 1178 ** the rowid. Such a table has an automatic index with origin 'pk', 1179 ** whereas a table with a true rowid alias does not. */ 1180 if( iPk>=0 ){ 1181 pStmt = recoverPreparePrintf(p, p->dbOut, 1182 "SELECT 1 FROM pragma_index_list(%Q, %Q) WHERE origin='pk'", 1183 zName, p->zDb 1184 ); 1185 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ) iPk = -1; 1186 recoverFinalize(p, pStmt); 1187 } 1188 1189 if( p->errCode==SQLITE_OK ){ 1190 if( iPk>=0 ){ 1191 pNew->aCol[iPk].bIPK = 1; 1192 }else if( pNew->bIntkey ){ 1193 /* Find a name for the rowid that is not also the name of a column */ 1194 static const char *azRowid[] = { "_rowid_", "rowid", "oid" }; 1195 int ii, jj; 1196 for(ii=0; ii<(int)(sizeof(azRowid)/sizeof(azRowid[0])); ii++){ 1197 for(jj=0; jjnCol; jj++){ 1198 if( sqlite3_stricmp(azRowid[ii], pNew->aCol[jj].zCol)==0 ) break; 1199 } 1200 if( jj==pNew->nCol ){ 1201 pNew->zRowid = azRowid[ii]; 1202 pNew->iRowidBind = iBind++; 1203 break; 1204 } 1205 } 1206 } 1207 } 1208 } 1209 } 1210 1211 /* 1212 ** This function is called after recoverCacheSchema() has cached those parts 1213 ** of the input database schema that could be recovered in temporary table 1214 ** "recovery.schema". This function creates in the output database copies 1215 ** of all parts of that schema that must be created before the tables can 1216 ** be populated. Specifically, this means: 1217 ** 1218 ** * all tables that are not VIRTUAL, and 1219 ** * UNIQUE indexes. 1220 ** 1221 ** If the recovery handle uses SQL callbacks, then callbacks containing 1222 ** the associated "CREATE TABLE" and "CREATE INDEX" statements are made. 1223 ** 1224 ** Additionally, records are added to the sqlite_schema table of the 1225 ** output database for any VIRTUAL tables. The CREATE VIRTUAL TABLE 1226 ** records are written directly to sqlite_schema, not actually executed. 1227 ** If the handle is in SQL callback mode, then callbacks are invoked 1228 ** with equivalent SQL statements. 1229 */ 1230 static int recoverWriteSchema1(sqlite3_recover *p){ 1231 sqlite3_stmt *pSelect = 0; 1232 sqlite3_stmt *pTblname = 0; 1233 1234 pSelect = recoverPrepare(p, p->dbOut, 1235 "WITH dbschema(rootpage, name, sql, tbl, isVirtual, isIndex) AS (" 1236 " SELECT rootpage, name, sql, " 1237 " type='table', " 1238 " sql LIKE 'create virtual%'," 1239 " (type='index' AND (sql LIKE '%unique%' OR ?1))" 1240 " FROM recovery.schema" 1241 ")" 1242 "SELECT rootpage, tbl, isVirtual, name, sql" 1243 " FROM dbschema " 1244 " WHERE (tbl OR isIndex) AND sql GLOB 'CREATE *'" 1245 " ORDER BY tbl DESC, name=='sqlite_sequence' DESC" 1246 ); 1247 1248 pTblname = recoverPrepare(p, p->dbOut, 1249 "SELECT name FROM sqlite_schema " 1250 "WHERE type='table' ORDER BY rowid DESC LIMIT 1" 1251 ); 1252 1253 if( pSelect ){ 1254 sqlite3_bind_int(pSelect, 1, p->bSlowIndexes); 1255 while( sqlite3_step(pSelect)==SQLITE_ROW ){ 1256 i64 iRoot = sqlite3_column_int64(pSelect, 0); 1257 int bTable = sqlite3_column_int(pSelect, 1); 1258 int bVirtual = sqlite3_column_int(pSelect, 2); 1259 const char *zName = (const char*)sqlite3_column_text(pSelect, 3); 1260 const char *zSql = (const char*)sqlite3_column_text(pSelect, 4); 1261 char *zFree = 0; 1262 int rc = SQLITE_OK; 1263 const char *zTail = 0; 1264 1265 if( bVirtual ){ 1266 zSql = (const char*)(zFree = recoverMPrintf(p, 1267 "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)", 1268 zName, zName, zSql 1269 )); 1270 } 1271 rc = recoverOneStmt(p->dbOut, zSql, &zTail); 1272 if( rc==SQLITE_OK ){ 1273 char *pToFree = 0; 1274 if( zTail && zTail[0] ){ 1275 int n = (int)(zTail - zSql); 1276 while( n>0 && (zSql[n-1]==';' || zSql[n-1]<=' ') ){ n--; } 1277 pToFree = sqlite3_mprintf("%.*s", n, zSql); 1278 zSql = pToFree; 1279 1280 } 1281 recoverSqlCallback(p, zSql); 1282 if( bTable && !bVirtual ){ 1283 if( SQLITE_ROW==sqlite3_step(pTblname) ){ 1284 const char *zTbl = (const char*)sqlite3_column_text(pTblname, 0); 1285 if( zTbl ) recoverAddTable(p, zTbl, iRoot); 1286 } 1287 recoverReset(p, pTblname); 1288 } 1289 sqlite3_free(pToFree); 1290 }else if( rc!=SQLITE_ERROR ){ 1291 recoverDbError(p, p->dbOut); 1292 } 1293 sqlite3_free(zFree); 1294 } 1295 } 1296 recoverFinalize(p, pSelect); 1297 recoverFinalize(p, pTblname); 1298 1299 return p->errCode; 1300 } 1301 1302 /* 1303 ** This function is called after the output database has been populated. It 1304 ** adds all recovered schema elements that were not created in the output 1305 ** database by recoverWriteSchema1() - everything except for tables and 1306 ** UNIQUE indexes. Specifically: 1307 ** 1308 ** * views, 1309 ** * triggers, 1310 ** * non-UNIQUE indexes. 1311 ** 1312 ** If the recover handle is in SQL callback mode, then equivalent callbacks 1313 ** are issued to create the schema elements. 1314 */ 1315 static int recoverWriteSchema2(sqlite3_recover *p){ 1316 sqlite3_stmt *pSelect = 0; 1317 1318 pSelect = recoverPrepare(p, p->dbOut, 1319 p->bSlowIndexes ? 1320 "SELECT rootpage, sql FROM recovery.schema " 1321 " WHERE type!='table' AND type!='index'" 1322 " AND sql GLOB 'CREATE *'" 1323 : 1324 "SELECT rootpage, sql FROM recovery.schema " 1325 " WHERE type!='table' AND (type!='index' OR sql NOT LIKE '%unique%')" 1326 " AND sql GLOB 'CREATE *'" 1327 ); 1328 1329 if( pSelect ){ 1330 while( sqlite3_step(pSelect)==SQLITE_ROW ){ 1331 const char *zSql = (const char*)sqlite3_column_text(pSelect, 1); 1332 const char *zTail = 0; 1333 int rc = recoverOneStmt(p->dbOut, zSql, &zTail); 1334 if( rc==SQLITE_OK ){ 1335 char *pToFree = 0; 1336 if( zTail && zTail[0] ){ 1337 /* Omit any extraneous text that follows the first SQL statement */ 1338 int n = (int)(zTail - zSql); 1339 while( n>0 && (zSql[n-1]==';' || zSql[n-1]<=' ') ){ n--; } 1340 pToFree = sqlite3_mprintf("%.*s", n, zSql); 1341 zSql = pToFree; 1342 } 1343 recoverSqlCallback(p, zSql); 1344 sqlite3_free(pToFree); 1345 }else if( rc!=SQLITE_ERROR ){ 1346 recoverDbError(p, p->dbOut); 1347 } 1348 } 1349 } 1350 recoverFinalize(p, pSelect); 1351 1352 return p->errCode; 1353 } 1354 1355 /* 1356 ** This function is a no-op if recover handle p already contains an error 1357 ** (if p->errCode!=SQLITE_OK). In this case it returns NULL. 1358 ** 1359 ** Otherwise, if the recover handle is configured to create an output 1360 ** database (was created by sqlite3_recover_init()), then this function 1361 ** prepares and returns an SQL statement to INSERT a new record into table 1362 ** pTab, assuming the first nField fields of a record extracted from disk 1363 ** are valid. 1364 ** 1365 ** For example, if table pTab is: 1366 ** 1367 ** CREATE TABLE name(a, b GENERATED ALWAYS AS (a+1) STORED, c, d, e); 1368 ** 1369 ** And nField is 4, then the SQL statement prepared and returned is: 1370 ** 1371 ** INSERT INTO (a, c, d) VALUES (?1, ?2, ?3); 1372 ** 1373 ** In this case even though 4 values were extracted from the input db, 1374 ** only 3 are written to the output, as the generated STORED column 1375 ** cannot be written. 1376 ** 1377 ** If the recover handle is in SQL callback mode, then the SQL statement 1378 ** prepared is such that evaluating it returns a single row containing 1379 ** a single text value - itself an SQL statement similar to the above, 1380 ** except with SQL literals in place of the variables. For example: 1381 ** 1382 ** SELECT 'INSERT INTO (a, c, d) VALUES (' 1383 ** || quote(?1) || ', ' 1384 ** || quote(?2) || ', ' 1385 ** || quote(?3) || ')'; 1386 ** 1387 ** In either case, it is the responsibility of the caller to eventually 1388 ** free the statement handle using sqlite3_finalize(). 1389 */ 1390 static sqlite3_stmt *recoverInsertStmt( 1391 sqlite3_recover *p, 1392 RecoverTable *pTab, 1393 int nField 1394 ){ 1395 sqlite3_stmt *pRet = 0; 1396 const char *zSep = ""; 1397 const char *zSqlSep = ""; 1398 char *zSql = 0; 1399 char *zFinal = 0; 1400 char *zBind = 0; 1401 int ii; 1402 int bSql = p->xSql ? 1 : 0; 1403 1404 if( nField<=0 ) return 0; 1405 1406 assert( nField<=pTab->nField ); 1407 1408 zSql = recoverMPrintf(p, "INSERT OR IGNORE INTO %Q(", pTab->zTab); 1409 1410 if( pTab->iRowidBind ){ 1411 assert( pTab->bIntkey ); 1412 assert( pTab->zRowid ); 1413 zSql = recoverMPrintf(p, "%z%s", zSql, pTab->zRowid); 1414 if( bSql ){ 1415 zBind = recoverMPrintf(p, "%zquote(?%d)", zBind, pTab->iRowidBind); 1416 }else{ 1417 zBind = recoverMPrintf(p, "%z?%d", zBind, pTab->iRowidBind); 1418 } 1419 zSqlSep = "||', '||"; 1420 zSep = ", "; 1421 } 1422 1423 /* Include each column that has a bind parameter and either has a field 1424 ** in the nField-field record or is the IPK. This must match the set of 1425 ** parameters bound by recoverWriteDataStep(). Note that nField counts 1426 ** record fields, not table columns - VIRTUAL generated columns have no 1427 ** field (iField<0), and the order of fields need not match the order of 1428 ** columns (WITHOUT ROWID tables). */ 1429 for(ii=0; iinCol; ii++){ 1430 RecoverColumn *pCol = &pTab->aCol[ii]; 1431 if( pCol->iBind>0 && (pCol->iFieldbIPK) ){ 1432 assert( pCol->iField>=0 ); 1433 assert( pCol->eHidden!=RECOVER_EHIDDEN_VIRTUAL ); 1434 assert( pCol->eHidden!=RECOVER_EHIDDEN_STORED ); 1435 zSql = recoverMPrintf(p, "%z%s%Q", zSql, zSep, pTab->aCol[ii].zCol); 1436 1437 if( bSql ){ 1438 zBind = recoverMPrintf(p, 1439 "%z%sescape_crlf(quote(?%d))", zBind, zSqlSep, pTab->aCol[ii].iBind 1440 ); 1441 zSqlSep = "||', '||"; 1442 }else{ 1443 zBind = recoverMPrintf(p, "%z%s?%d", zBind, zSep, pTab->aCol[ii].iBind); 1444 } 1445 zSep = ", "; 1446 } 1447 } 1448 1449 if( bSql ){ 1450 zFinal = recoverMPrintf(p, "SELECT %Q || ') VALUES (' || %s || ')'", 1451 zSql, zBind 1452 ); 1453 }else{ 1454 zFinal = recoverMPrintf(p, "%s) VALUES (%s)", zSql, zBind); 1455 } 1456 1457 pRet = recoverPrepare(p, p->dbOut, zFinal); 1458 sqlite3_free(zSql); 1459 sqlite3_free(zBind); 1460 sqlite3_free(zFinal); 1461 1462 return pRet; 1463 } 1464 1465 1466 /* 1467 ** Search the list of RecoverTable objects at p->pTblList for one that 1468 ** has root page iRoot in the input database. If such an object is found, 1469 ** return a pointer to it. Otherwise, return NULL. 1470 */ 1471 static RecoverTable *recoverFindTable(sqlite3_recover *p, u32 iRoot){ 1472 RecoverTable *pRet = 0; 1473 for(pRet=p->pTblList; pRet && pRet->iRoot!=iRoot; pRet=pRet->pNext); 1474 return pRet; 1475 } 1476 1477 /* 1478 ** This function attempts to create a lost and found table within the 1479 ** output db. If successful, it returns a pointer to a buffer containing 1480 ** the name of the new table. It is the responsibility of the caller to 1481 ** eventually free this buffer using sqlite3_free(). 1482 ** 1483 ** If an error occurs, NULL is returned and an error code and error 1484 ** message left in the recover handle. 1485 */ 1486 static char *recoverLostAndFoundCreate( 1487 sqlite3_recover *p, /* Recover object */ 1488 int nField /* Number of column fields in new table */ 1489 ){ 1490 char *zTbl = 0; 1491 sqlite3_stmt *pProbe = 0; 1492 int ii = 0; 1493 1494 pProbe = recoverPrepare(p, p->dbOut, 1495 "SELECT 1 FROM sqlite_schema WHERE name=?" 1496 ); 1497 for(ii=-1; zTbl==0 && p->errCode==SQLITE_OK && ii<1000; ii++){ 1498 int bFail = 0; 1499 if( ii<0 ){ 1500 zTbl = recoverMPrintf(p, "%s", p->zLostAndFound); 1501 }else{ 1502 zTbl = recoverMPrintf(p, "%s_%d", p->zLostAndFound, ii); 1503 } 1504 1505 if( p->errCode==SQLITE_OK ){ 1506 sqlite3_bind_text(pProbe, 1, zTbl, -1, SQLITE_STATIC); 1507 if( SQLITE_ROW==sqlite3_step(pProbe) ){ 1508 bFail = 1; 1509 } 1510 recoverReset(p, pProbe); 1511 } 1512 1513 if( bFail ){ 1514 sqlite3_clear_bindings(pProbe); 1515 sqlite3_free(zTbl); 1516 zTbl = 0; 1517 } 1518 } 1519 recoverFinalize(p, pProbe); 1520 1521 if( zTbl ){ 1522 const char *zSep = 0; 1523 char *zField = 0; 1524 char *zSql = 0; 1525 1526 zSep = "rootpgno INTEGER, pgno INTEGER, nfield INTEGER, id INTEGER, "; 1527 for(ii=0; p->errCode==SQLITE_OK && iidbOut, zSql); 1536 recoverSqlCallback(p, zSql); 1537 sqlite3_free(zSql); 1538 }else if( p->errCode==SQLITE_OK ){ 1539 recoverError( 1540 p, SQLITE_ERROR, "failed to create %s output table", p->zLostAndFound 1541 ); 1542 } 1543 1544 return zTbl; 1545 } 1546 1547 /* 1548 ** Synthesize and prepare an INSERT statement to write to the lost_and_found 1549 ** table in the output database. The name of the table is zTab, and it has 1550 ** nField c* fields. 1551 */ 1552 static sqlite3_stmt *recoverLostAndFoundInsert( 1553 sqlite3_recover *p, 1554 const char *zTab, 1555 int nField 1556 ){ 1557 int nTotal = nField + 4; 1558 int ii; 1559 char *zBind = 0; 1560 sqlite3_stmt *pRet = 0; 1561 1562 if( p->xSql==0 ){ 1563 for(ii=0; iidbOut, "INSERT INTO %s VALUES(%s)", zTab, zBind 1568 ); 1569 }else{ 1570 const char *zSep = ""; 1571 for(ii=0; iidbOut, "SELECT 'INSERT INTO %s VALUES(' || %s || ')'", zTab, zBind 1577 ); 1578 } 1579 1580 sqlite3_free(zBind); 1581 return pRet; 1582 } 1583 1584 /* 1585 ** Input database page iPg contains data that will be written to the 1586 ** lost-and-found table of the output database. This function attempts 1587 ** to identify the root page of the tree that page iPg belonged to. 1588 ** If successful, it sets output variable (*piRoot) to the page number 1589 ** of the root page and returns SQLITE_OK. Otherwise, if an error occurs, 1590 ** an SQLite error code is returned and the final value of *piRoot 1591 ** undefined. 1592 */ 1593 static int recoverLostAndFoundFindRoot( 1594 sqlite3_recover *p, 1595 i64 iPg, 1596 i64 *piRoot 1597 ){ 1598 RecoverStateLAF *pLaf = &p->laf; 1599 1600 if( pLaf->pFindRoot==0 ){ 1601 pLaf->pFindRoot = recoverPrepare(p, p->dbOut, 1602 "WITH RECURSIVE p(pgno) AS (" 1603 " SELECT ?" 1604 " UNION" 1605 " SELECT parent FROM recovery.map AS m, p WHERE m.pgno=p.pgno" 1606 ") " 1607 "SELECT p.pgno FROM p, recovery.map m WHERE m.pgno=p.pgno " 1608 " AND m.parent IS NULL" 1609 ); 1610 } 1611 if( p->errCode==SQLITE_OK ){ 1612 sqlite3_bind_int64(pLaf->pFindRoot, 1, iPg); 1613 if( sqlite3_step(pLaf->pFindRoot)==SQLITE_ROW ){ 1614 *piRoot = sqlite3_column_int64(pLaf->pFindRoot, 0); 1615 }else{ 1616 *piRoot = iPg; 1617 } 1618 recoverReset(p, pLaf->pFindRoot); 1619 } 1620 return p->errCode; 1621 } 1622 1623 /* 1624 ** Recover data from page iPage of the input database and write it to 1625 ** the lost-and-found table in the output database. 1626 */ 1627 static void recoverLostAndFoundOnePage(sqlite3_recover *p, i64 iPage){ 1628 RecoverStateLAF *pLaf = &p->laf; 1629 sqlite3_value **apVal = pLaf->apVal; 1630 sqlite3_stmt *pPageData = pLaf->pPageData; 1631 sqlite3_stmt *pInsert = pLaf->pInsert; 1632 1633 int nVal = -1; 1634 int iPrevCell = 0; 1635 i64 iRoot = 0; 1636 int bHaveRowid = 0; 1637 i64 iRowid = 0; 1638 int ii = 0; 1639 1640 if( recoverLostAndFoundFindRoot(p, iPage, &iRoot) ) return; 1641 sqlite3_bind_int64(pPageData, 1, iPage); 1642 while( p->errCode==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPageData) ){ 1643 int iCell = sqlite3_column_int64(pPageData, 0); 1644 int iField = sqlite3_column_int64(pPageData, 1); 1645 1646 if( iPrevCell!=iCell && nVal>=0 ){ 1647 /* Insert the new row */ 1648 sqlite3_bind_int64(pInsert, 1, iRoot); /* rootpgno */ 1649 sqlite3_bind_int64(pInsert, 2, iPage); /* pgno */ 1650 sqlite3_bind_int(pInsert, 3, nVal); /* nfield */ 1651 if( bHaveRowid ){ 1652 sqlite3_bind_int64(pInsert, 4, iRowid); /* id */ 1653 } 1654 for(ii=0; iinMaxField ){ 1680 sqlite3_value *pVal = sqlite3_column_value(pPageData, 2); 1681 apVal[iField] = sqlite3_value_dup(pVal); 1682 assert( iField==nVal || (nVal==-1 && iField==0) ); 1683 nVal = iField+1; 1684 if( apVal[iField]==0 ){ 1685 recoverError(p, SQLITE_NOMEM, 0); 1686 } 1687 } 1688 1689 iPrevCell = iCell; 1690 } 1691 recoverReset(p, pPageData); 1692 1693 for(ii=0; iilaf; 1708 if( p->errCode==SQLITE_OK ){ 1709 if( pLaf->pInsert==0 ){ 1710 return SQLITE_DONE; 1711 }else{ 1712 if( p->errCode==SQLITE_OK ){ 1713 int res = sqlite3_step(pLaf->pAllPage); 1714 if( res==SQLITE_ROW ){ 1715 i64 iPage = sqlite3_column_int64(pLaf->pAllPage, 0); 1716 if( recoverBitmapQuery(pLaf->pUsed, iPage)==0 ){ 1717 recoverLostAndFoundOnePage(p, iPage); 1718 } 1719 }else{ 1720 recoverReset(p, pLaf->pAllPage); 1721 return SQLITE_DONE; 1722 } 1723 } 1724 } 1725 } 1726 return SQLITE_OK; 1727 } 1728 1729 /* 1730 ** Initialize resources required in RECOVER_STATE_LOSTANDFOUND3 1731 ** state - during which the lost-and-found table of the output database 1732 ** is populated with recovered data that can not be assigned to any 1733 ** recovered schema object. 1734 */ 1735 static void recoverLostAndFound3Init(sqlite3_recover *p){ 1736 RecoverStateLAF *pLaf = &p->laf; 1737 1738 if( pLaf->nMaxField>0 ){ 1739 char *zTab = 0; /* Name of lost_and_found table */ 1740 1741 zTab = recoverLostAndFoundCreate(p, pLaf->nMaxField); 1742 pLaf->pInsert = recoverLostAndFoundInsert(p, zTab, pLaf->nMaxField); 1743 sqlite3_free(zTab); 1744 1745 pLaf->pAllPage = recoverPreparePrintf(p, p->dbOut, 1746 "WITH RECURSIVE seq(ii) AS (" 1747 " SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld" 1748 ")" 1749 "SELECT ii FROM seq" , p->laf.nPg 1750 ); 1751 pLaf->pPageData = recoverPrepare(p, p->dbOut, 1752 "SELECT cell, field, value " 1753 "FROM sqlite_dbdata('getpage()') d WHERE d.pgno=? " 1754 "UNION ALL " 1755 "SELECT -1, -1, -1" 1756 ); 1757 1758 pLaf->apVal = (sqlite3_value**)recoverMalloc(p, 1759 pLaf->nMaxField*sizeof(sqlite3_value*) 1760 ); 1761 } 1762 } 1763 1764 /* 1765 ** Initialize resources required in RECOVER_STATE_WRITING state - during which 1766 ** tables recovered from the schema of the input database are populated with 1767 ** recovered data. 1768 */ 1769 static int recoverWriteDataInit(sqlite3_recover *p){ 1770 RecoverStateW1 *p1 = &p->w1; 1771 RecoverTable *pTbl = 0; 1772 int nByte = 0; 1773 1774 /* Figure out the maximum number of fields for any table in the schema */ 1775 assert( p1->nMax==0 ); 1776 for(pTbl=p->pTblList; pTbl; pTbl=pTbl->pNext){ 1777 if( pTbl->nField>p1->nMax ) p1->nMax = pTbl->nField; 1778 } 1779 1780 /* Allocate an array of (sqlite3_value*) in which to accumulate the values 1781 ** that will be written to the output database in a single row. */ 1782 nByte = sizeof(sqlite3_value*) * (p1->nMax+1); 1783 p1->apVal = (sqlite3_value**)recoverMalloc(p, nByte); 1784 if( p1->apVal==0 ) return p->errCode; 1785 1786 /* Prepare the SELECT to loop through schema tables (pTbls) and the SELECT 1787 ** to loop through cells that appear to belong to a single table (pSel). */ 1788 p1->pTbls = recoverPrepare(p, p->dbOut, 1789 "SELECT rootpage FROM recovery.schema " 1790 " WHERE type='table' AND (sql NOT LIKE 'create virtual%')" 1791 " ORDER BY (tbl_name='sqlite_sequence') ASC" 1792 ); 1793 p1->pSel = recoverPrepare(p, p->dbOut, 1794 "WITH RECURSIVE pages(page) AS (" 1795 " SELECT ?1" 1796 " UNION" 1797 " SELECT child FROM sqlite_dbptr('getpage()'), pages " 1798 " WHERE pgno=page" 1799 ") " 1800 "SELECT page, cell, field, value " 1801 "FROM sqlite_dbdata('getpage()') d, pages p WHERE p.page=d.pgno " 1802 "UNION ALL " 1803 "SELECT 0, 0, 0, 0" 1804 ); 1805 1806 return p->errCode; 1807 } 1808 1809 /* 1810 ** Clean up resources allocated by recoverWriteDataInit() (stuff in 1811 ** sqlite3_recover.w1). 1812 */ 1813 static void recoverWriteDataCleanup(sqlite3_recover *p){ 1814 RecoverStateW1 *p1 = &p->w1; 1815 int ii; 1816 for(ii=0; iinVal; ii++){ 1817 sqlite3_value_free(p1->apVal[ii]); 1818 } 1819 sqlite3_free(p1->apVal); 1820 recoverFinalize(p, p1->pInsert); 1821 recoverFinalize(p, p1->pTbls); 1822 recoverFinalize(p, p1->pSel); 1823 memset(p1, 0, sizeof(*p1)); 1824 } 1825 1826 /* 1827 ** Perform one step (sqlite3_recover_step()) of work for the connection 1828 ** passed as the only argument, which is guaranteed to be in 1829 ** RECOVER_STATE_WRITING state - during which tables recovered from the 1830 ** schema of the input database are populated with recovered data. 1831 */ 1832 static int recoverWriteDataStep(sqlite3_recover *p){ 1833 RecoverStateW1 *p1 = &p->w1; 1834 sqlite3_stmt *pSel = p1->pSel; 1835 sqlite3_value **apVal = p1->apVal; 1836 1837 if( p->errCode==SQLITE_OK && p1->pTab==0 ){ 1838 if( sqlite3_step(p1->pTbls)==SQLITE_ROW ){ 1839 i64 iRoot = sqlite3_column_int64(p1->pTbls, 0); 1840 p1->pTab = recoverFindTable(p, iRoot); 1841 1842 recoverFinalize(p, p1->pInsert); 1843 p1->pInsert = 0; 1844 1845 /* If this table is unknown, return early. The caller will invoke this 1846 ** function again and it will move on to the next table. */ 1847 if( p1->pTab==0 ) return p->errCode; 1848 1849 /* If this is the sqlite_sequence table, delete any rows added by 1850 ** earlier INSERT statements on tables with AUTOINCREMENT primary 1851 ** keys before recovering its contents. The p1->pTbls SELECT statement 1852 ** is rigged to deliver "sqlite_sequence" last of all, so we don't 1853 ** worry about it being modified after it is recovered. */ 1854 if( sqlite3_stricmp("sqlite_sequence", p1->pTab->zTab)==0 ){ 1855 recoverExec(p, p->dbOut, "DELETE FROM sqlite_sequence"); 1856 recoverSqlCallback(p, "DELETE FROM sqlite_sequence"); 1857 } 1858 1859 /* Bind the root page of this table within the original database to 1860 ** SELECT statement p1->pSel. The SELECT statement will then iterate 1861 ** through cells that look like they belong to table pTab. */ 1862 sqlite3_bind_int64(pSel, 1, iRoot); 1863 1864 p1->nVal = 0; 1865 p1->bHaveRowid = 0; 1866 p1->iPrevPage = -1; 1867 p1->iPrevCell = -1; 1868 }else{ 1869 return SQLITE_DONE; 1870 } 1871 } 1872 assert( p->errCode!=SQLITE_OK || p1->pTab ); 1873 1874 if( p->errCode==SQLITE_OK && sqlite3_step(pSel)==SQLITE_ROW ){ 1875 RecoverTable *pTab = p1->pTab; 1876 1877 i64 iPage = sqlite3_column_int64(pSel, 0); 1878 int iCell = sqlite3_column_int(pSel, 1); 1879 int iField = sqlite3_column_int(pSel, 2); 1880 sqlite3_value *pVal = sqlite3_column_value(pSel, 3); 1881 int bNewCell = (p1->iPrevPage!=iPage || p1->iPrevCell!=iCell); 1882 1883 assert( bNewCell==0 || (iField==-1 || iField==0) ); 1884 assert( bNewCell || iField==p1->nVal || p1->nVal==pTab->nField ); 1885 1886 if( bNewCell ){ 1887 int ii = 0; 1888 if( p1->nVal>=0 ){ 1889 if( p1->pInsert==0 || p1->nVal!=p1->nInsert ){ 1890 recoverFinalize(p, p1->pInsert); 1891 p1->pInsert = recoverInsertStmt(p, pTab, p1->nVal); 1892 p1->nInsert = p1->nVal; 1893 } 1894 if( p1->nVal>0 ){ 1895 sqlite3_stmt *pInsert = p1->pInsert; 1896 for(ii=0; iinCol; ii++){ 1897 RecoverColumn *pCol = &pTab->aCol[ii]; 1898 int iBind = pCol->iBind; 1899 if( iBind>0 ){ 1900 if( pCol->bIPK ){ 1901 sqlite3_bind_int64(pInsert, iBind, p1->iRowid); 1902 }else if( pCol->iFieldnVal ){ 1903 recoverBindValue(p, pInsert, iBind, apVal[pCol->iField]); 1904 } 1905 } 1906 } 1907 if( p->bRecoverRowid && pTab->iRowidBind>0 && p1->bHaveRowid ){ 1908 sqlite3_bind_int64(pInsert, pTab->iRowidBind, p1->iRowid); 1909 } 1910 if( SQLITE_ROW==sqlite3_step(pInsert) ){ 1911 const char *z = (const char*)sqlite3_column_text(pInsert, 0); 1912 recoverSqlCallback(p, z); 1913 } 1914 recoverReset(p, pInsert); 1915 assert( p->errCode || pInsert ); 1916 if( pInsert ) sqlite3_clear_bindings(pInsert); 1917 } 1918 } 1919 1920 for(ii=0; iinVal; ii++){ 1921 sqlite3_value_free(apVal[ii]); 1922 apVal[ii] = 0; 1923 } 1924 p1->nVal = -1; 1925 p1->bHaveRowid = 0; 1926 } 1927 1928 if( iPage!=0 ){ 1929 if( iField<0 ){ 1930 p1->iRowid = sqlite3_column_int64(pSel, 3); 1931 assert( p1->nVal==-1 ); 1932 p1->nVal = 0; 1933 p1->bHaveRowid = 1; 1934 }else if( iFieldnField ){ 1935 assert( apVal[iField]==0 ); 1936 apVal[iField] = sqlite3_value_dup( pVal ); 1937 if( apVal[iField]==0 ){ 1938 recoverError(p, SQLITE_NOMEM, 0); 1939 } 1940 p1->nVal = iField+1; 1941 }else if( pTab->nField==0 ){ 1942 p1->nVal = pTab->nField; 1943 } 1944 p1->iPrevCell = iCell; 1945 p1->iPrevPage = iPage; 1946 } 1947 }else{ 1948 recoverReset(p, pSel); 1949 p1->pTab = 0; 1950 } 1951 1952 return p->errCode; 1953 } 1954 1955 /* 1956 ** Initialize resources required by sqlite3_recover_step() in 1957 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not 1958 ** already allocated to a recovered schema element is determined. 1959 */ 1960 static void recoverLostAndFound1Init(sqlite3_recover *p){ 1961 RecoverStateLAF *pLaf = &p->laf; 1962 sqlite3_stmt *pStmt = 0; 1963 1964 assert( p->laf.pUsed==0 ); 1965 pLaf->nPg = recoverPageCount(p); 1966 pLaf->pUsed = recoverBitmapAlloc(p, pLaf->nPg); 1967 1968 /* Prepare a statement to iterate through all pages that are part of any tree 1969 ** in the recoverable part of the input database schema to the bitmap. And, 1970 ** if !p->bFreelistCorrupt, add all pages that appear to be part of the 1971 ** freelist. */ 1972 pStmt = recoverPrepare( 1973 p, p->dbOut, 1974 "WITH trunk(pgno) AS (" 1975 " SELECT read_i32(getpage(1), 8) AS x WHERE x>0" 1976 " UNION" 1977 " SELECT read_i32(getpage(trunk.pgno), 0) AS x FROM trunk WHERE x>0" 1978 ")," 1979 "trunkdata(pgno, data) AS (" 1980 " SELECT pgno, getpage(pgno) FROM trunk" 1981 ")," 1982 "freelist(data, n, freepgno) AS (" 1983 " SELECT data, min(16384, read_i32(data, 1)-1), pgno FROM trunkdata" 1984 " UNION ALL" 1985 " SELECT data, n-1, read_i32(data, 2+n) FROM freelist WHERE n>=0" 1986 ")," 1987 "" 1988 "roots(r) AS (" 1989 " SELECT 1 UNION ALL" 1990 " SELECT rootpage FROM recovery.schema WHERE rootpage>0" 1991 ")," 1992 "used(page) AS (" 1993 " SELECT r FROM roots" 1994 " UNION" 1995 " SELECT child FROM sqlite_dbptr('getpage()'), used " 1996 " WHERE pgno=page" 1997 ") " 1998 "SELECT page FROM used" 1999 " UNION ALL " 2000 "SELECT freepgno FROM freelist WHERE NOT ?" 2001 ); 2002 if( pStmt ) sqlite3_bind_int(pStmt, 1, p->bFreelistCorrupt); 2003 pLaf->pUsedPages = pStmt; 2004 } 2005 2006 /* 2007 ** Perform one step (sqlite3_recover_step()) of work for the connection 2008 ** passed as the only argument, which is guaranteed to be in 2009 ** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not 2010 ** already allocated to a recovered schema element is determined. 2011 */ 2012 static int recoverLostAndFound1Step(sqlite3_recover *p){ 2013 RecoverStateLAF *pLaf = &p->laf; 2014 int rc = p->errCode; 2015 if( rc==SQLITE_OK ){ 2016 rc = sqlite3_step(pLaf->pUsedPages); 2017 if( rc==SQLITE_ROW ){ 2018 i64 iPg = sqlite3_column_int64(pLaf->pUsedPages, 0); 2019 recoverBitmapSet(pLaf->pUsed, iPg); 2020 rc = SQLITE_OK; 2021 }else{ 2022 recoverFinalize(p, pLaf->pUsedPages); 2023 pLaf->pUsedPages = 0; 2024 } 2025 } 2026 return rc; 2027 } 2028 2029 /* 2030 ** Initialize resources required by RECOVER_STATE_LOSTANDFOUND2 2031 ** state - during which the pages identified in RECOVER_STATE_LOSTANDFOUND1 2032 ** are sorted into sets that likely belonged to the same database tree. 2033 */ 2034 static void recoverLostAndFound2Init(sqlite3_recover *p){ 2035 RecoverStateLAF *pLaf = &p->laf; 2036 2037 assert( p->laf.pAllAndParent==0 ); 2038 assert( p->laf.pMapInsert==0 ); 2039 assert( p->laf.pMaxField==0 ); 2040 assert( p->laf.nMaxField==0 ); 2041 2042 pLaf->pMapInsert = recoverPrepare(p, p->dbOut, 2043 "INSERT OR IGNORE INTO recovery.map(pgno, parent) VALUES(?, ?)" 2044 ); 2045 pLaf->pAllAndParent = recoverPreparePrintf(p, p->dbOut, 2046 "WITH RECURSIVE seq(ii) AS (" 2047 " SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld" 2048 ")" 2049 "SELECT pgno, child FROM sqlite_dbptr('getpage()') " 2050 " UNION ALL " 2051 "SELECT NULL, ii FROM seq", p->laf.nPg 2052 ); 2053 pLaf->pMaxField = recoverPreparePrintf(p, p->dbOut, 2054 "SELECT max(field)+1 FROM sqlite_dbdata('getpage') WHERE pgno = ?" 2055 ); 2056 } 2057 2058 /* 2059 ** Perform one step (sqlite3_recover_step()) of work for the connection 2060 ** passed as the only argument, which is guaranteed to be in 2061 ** RECOVER_STATE_LOSTANDFOUND2 state - during which the pages identified 2062 ** in RECOVER_STATE_LOSTANDFOUND1 are sorted into sets that likely belonged 2063 ** to the same database tree. 2064 */ 2065 static int recoverLostAndFound2Step(sqlite3_recover *p){ 2066 RecoverStateLAF *pLaf = &p->laf; 2067 if( p->errCode==SQLITE_OK ){ 2068 int res = sqlite3_step(pLaf->pAllAndParent); 2069 if( res==SQLITE_ROW ){ 2070 i64 iChild = sqlite3_column_int(pLaf->pAllAndParent, 1); 2071 if( recoverBitmapQuery(pLaf->pUsed, iChild)==0 ){ 2072 sqlite3_bind_int64(pLaf->pMapInsert, 1, iChild); 2073 sqlite3_bind_value(pLaf->pMapInsert, 2, 2074 sqlite3_column_value(pLaf->pAllAndParent, 0) 2075 ); 2076 sqlite3_step(pLaf->pMapInsert); 2077 recoverReset(p, pLaf->pMapInsert); 2078 sqlite3_bind_int64(pLaf->pMaxField, 1, iChild); 2079 if( SQLITE_ROW==sqlite3_step(pLaf->pMaxField) ){ 2080 int nMax = sqlite3_column_int(pLaf->pMaxField, 0); 2081 if( nMax>pLaf->nMaxField ) pLaf->nMaxField = nMax; 2082 } 2083 recoverReset(p, pLaf->pMaxField); 2084 } 2085 }else{ 2086 recoverFinalize(p, pLaf->pAllAndParent); 2087 pLaf->pAllAndParent =0; 2088 return SQLITE_DONE; 2089 } 2090 } 2091 return p->errCode; 2092 } 2093 2094 /* 2095 ** Free all resources allocated as part of sqlite3_recover_step() calls 2096 ** in one of the RECOVER_STATE_LOSTANDFOUND[123] states. 2097 */ 2098 static void recoverLostAndFoundCleanup(sqlite3_recover *p){ 2099 recoverBitmapFree(p->laf.pUsed); 2100 p->laf.pUsed = 0; 2101 sqlite3_finalize(p->laf.pUsedPages); 2102 sqlite3_finalize(p->laf.pAllAndParent); 2103 sqlite3_finalize(p->laf.pMapInsert); 2104 sqlite3_finalize(p->laf.pMaxField); 2105 sqlite3_finalize(p->laf.pFindRoot); 2106 sqlite3_finalize(p->laf.pInsert); 2107 sqlite3_finalize(p->laf.pAllPage); 2108 sqlite3_finalize(p->laf.pPageData); 2109 p->laf.pUsedPages = 0; 2110 p->laf.pAllAndParent = 0; 2111 p->laf.pMapInsert = 0; 2112 p->laf.pMaxField = 0; 2113 p->laf.pFindRoot = 0; 2114 p->laf.pInsert = 0; 2115 p->laf.pAllPage = 0; 2116 p->laf.pPageData = 0; 2117 sqlite3_free(p->laf.apVal); 2118 p->laf.apVal = 0; 2119 } 2120 2121 /* 2122 ** Free all resources allocated as part of sqlite3_recover_step() calls. 2123 */ 2124 static void recoverFinalCleanup(sqlite3_recover *p){ 2125 RecoverTable *pTab = 0; 2126 RecoverTable *pNext = 0; 2127 2128 recoverWriteDataCleanup(p); 2129 recoverLostAndFoundCleanup(p); 2130 2131 for(pTab=p->pTblList; pTab; pTab=pNext){ 2132 pNext = pTab->pNext; 2133 sqlite3_free(pTab); 2134 } 2135 p->pTblList = 0; 2136 sqlite3_finalize(p->pGetPage); 2137 p->pGetPage = 0; 2138 sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0); 2139 2140 { 2141 #ifndef NDEBUG 2142 int res = 2143 #endif 2144 sqlite3_close(p->dbOut); 2145 assert( res==SQLITE_OK ); 2146 } 2147 p->dbOut = 0; 2148 } 2149 2150 /* 2151 ** Decode and return an unsigned 16-bit big-endian integer value from 2152 ** buffer a[]. 2153 */ 2154 static u32 recoverGetU16(const u8 *a){ 2155 return (((u32)a[0])<<8) + ((u32)a[1]); 2156 } 2157 2158 /* 2159 ** Decode and return an unsigned 32-bit big-endian integer value from 2160 ** buffer a[]. 2161 */ 2162 static u32 recoverGetU32(const u8 *a){ 2163 return (((u32)a[0])<<24) + (((u32)a[1])<<16) + (((u32)a[2])<<8) + ((u32)a[3]); 2164 } 2165 2166 /* 2167 ** Decode an SQLite varint from buffer a[]. Write the decoded value to (*pVal) 2168 ** and return the number of bytes consumed. 2169 */ 2170 static int recoverGetVarint(const u8 *a, i64 *pVal){ 2171 sqlite3_uint64 u = 0; 2172 int i; 2173 for(i=0; i<8; i++){ 2174 u = (u<<7) + (a[i]&0x7f); 2175 if( (a[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; } 2176 } 2177 u = (u<<8) + (a[i]&0xff); 2178 *pVal = (sqlite3_int64)u; 2179 return 9; 2180 } 2181 2182 /* 2183 ** The second argument points to a buffer n bytes in size. If this buffer 2184 ** or a prefix thereof appears to contain a well-formed SQLite b-tree page, 2185 ** return the page-size in bytes. Otherwise, if the buffer does not 2186 ** appear to contain a well-formed b-tree page, return 0. 2187 */ 2188 static int recoverIsValidPage(u8 *aTmp, const u8 *a, int n){ 2189 u8 *aUsed = aTmp; 2190 int nFrag = 0; 2191 int nActual = 0; 2192 int iFree = 0; 2193 int nCell = 0; /* Number of cells on page */ 2194 int iCellOff = 0; /* Offset of cell array in page */ 2195 int iContent = 0; 2196 int eType = 0; 2197 int ii = 0; 2198 2199 eType = (int)a[0]; 2200 if( eType!=0x02 && eType!=0x05 && eType!=0x0A && eType!=0x0D ) return 0; 2201 2202 iFree = (int)recoverGetU16(&a[1]); 2203 nCell = (int)recoverGetU16(&a[3]); 2204 iContent = (int)recoverGetU16(&a[5]); 2205 if( iContent==0 ) iContent = 65536; 2206 nFrag = (int)a[7]; 2207 2208 if( iContent>n ) return 0; 2209 2210 memset(aUsed, 0, n); 2211 memset(aUsed, 0xFF, iContent); 2212 2213 /* Follow the free-list. This is the same format for all b-tree pages. */ 2214 if( iFree && iFree<=iContent ) return 0; 2215 while( iFree ){ 2216 int iNext = 0; 2217 int nByte = 0; 2218 if( iFree>(n-4) ) return 0; 2219 iNext = recoverGetU16(&a[iFree]); 2220 nByte = recoverGetU16(&a[iFree+2]); 2221 if( iFree+nByte>n || nByte<4 ) return 0; 2222 if( iNext && iNextiContent ) return 0; 2234 for(ii=0; iin ){ 2240 return 0; 2241 } 2242 if( eType==0x05 || eType==0x02 ) nByte += 4; 2243 nByte += recoverGetVarint(&a[iOff+nByte], &nPayload); 2244 if( eType==0x0D ){ 2245 i64 dummy = 0; 2246 nByte += recoverGetVarint(&a[iOff+nByte], &dummy); 2247 } 2248 if( eType!=0x05 ){ 2249 int X = (eType==0x0D) ? n-35 : (((n-12)*64/255)-23); 2250 int M = ((n-12)*32/255)-23; 2251 int K = M+((nPayload-M)%(n-4)); 2252 2253 if( nPayloadn ){ 2263 return 0; 2264 } 2265 for(iByte=iOff; iByte<(iOff+nByte); iByte++){ 2266 if( aUsed[iByte]!=0 ){ 2267 return 0; 2268 } 2269 aUsed[iByte] = 0xFF; 2270 } 2271 } 2272 2273 nActual = 0; 2274 for(ii=0; iipMethods!=&recover_methods ); 2324 return pFd->pMethods->xClose(pFd); 2325 } 2326 2327 /* 2328 ** Write value v to buffer a[] as a 16-bit big-endian unsigned integer. 2329 */ 2330 static void recoverPutU16(u8 *a, u32 v){ 2331 a[0] = (v>>8) & 0x00FF; 2332 a[1] = (v>>0) & 0x00FF; 2333 } 2334 2335 /* 2336 ** Write value v to buffer a[] as a 32-bit big-endian unsigned integer. 2337 */ 2338 static void recoverPutU32(u8 *a, u32 v){ 2339 a[0] = (v>>24) & 0x00FF; 2340 a[1] = (v>>16) & 0x00FF; 2341 a[2] = (v>>8) & 0x00FF; 2342 a[3] = (v>>0) & 0x00FF; 2343 } 2344 2345 /* 2346 ** Detect the page-size of the database opened by file-handle pFd by 2347 ** searching the first part of the file for a well-formed SQLite b-tree 2348 ** page. If parameter nReserve is non-zero, then as well as searching for 2349 ** a b-tree page with zero reserved bytes, this function searches for one 2350 ** with nReserve reserved bytes at the end of it. 2351 ** 2352 ** If successful, set variable p->detected_pgsz to the detected page-size 2353 ** in bytes and return SQLITE_OK. Or, if no error occurs but no valid page 2354 ** can be found, return SQLITE_OK but leave p->detected_pgsz set to 0. Or, 2355 ** if an error occurs (e.g. an IO or OOM error), then an SQLite error code 2356 ** is returned. The final value of p->detected_pgsz is undefined in this 2357 ** case. 2358 */ 2359 static int recoverVfsDetectPagesize( 2360 sqlite3_recover *p, /* Recover handle */ 2361 sqlite3_file *pFd, /* File-handle open on input database */ 2362 u32 nReserve, /* Possible nReserve value */ 2363 i64 nSz /* Size of database file in bytes */ 2364 ){ 2365 int rc = SQLITE_OK; 2366 const int nMin = 512; 2367 const int nMax = 65536; 2368 const int nMaxBlk = 4; 2369 u32 pgsz = 0; 2370 int iBlk = 0; 2371 u8 *aPg = 0; 2372 u8 *aTmp = 0; 2373 int nBlk = 0; 2374 2375 aPg = (u8*)sqlite3_malloc(2*nMax); 2376 if( aPg==0 ) return SQLITE_NOMEM; 2377 aTmp = &aPg[nMax]; 2378 2379 nBlk = (nSz+nMax-1)/nMax; 2380 if( nBlk>nMaxBlk ) nBlk = nMaxBlk; 2381 2382 do { 2383 for(iBlk=0; rc==SQLITE_OK && iBlk=((iBlk+1)*nMax)) ? nMax : (nSz % nMax); 2385 memset(aPg, 0, nMax); 2386 rc = pFd->pMethods->xRead(pFd, aPg, nByte, iBlk*nMax); 2387 if( rc==SQLITE_OK ){ 2388 int pgsz2; 2389 for(pgsz2=(pgsz ? pgsz*2 : nMin); pgsz2<=nMax; pgsz2=pgsz2*2){ 2390 int iOff; 2391 for(iOff=0; iOff(u32)p->detected_pgsz ){ 2401 p->detected_pgsz = pgsz; 2402 p->nReserve = nReserve; 2403 } 2404 if( nReserve==0 ) break; 2405 nReserve = 0; 2406 }while( 1 ); 2407 2408 p->detected_pgsz = pgsz; 2409 sqlite3_free(aPg); 2410 return rc; 2411 } 2412 2413 /* 2414 ** The xRead() method of the wrapper VFS. This is used to intercept calls 2415 ** to read page 1 of the input database. 2416 */ 2417 static int recoverVfsRead(sqlite3_file *pFd, void *aBuf, int nByte, i64 iOff){ 2418 int rc = SQLITE_OK; 2419 if( pFd->pMethods==&recover_methods ){ 2420 pFd->pMethods = recover_g.pMethods; 2421 rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff); 2422 if( nByte==16 ){ 2423 sqlite3_randomness(16, aBuf); 2424 }else 2425 if( rc==SQLITE_OK && iOff==0 && nByte>=108 ){ 2426 /* Ensure that the database has a valid header file. The only fields 2427 ** that really matter to recovery are: 2428 ** 2429 ** + Database page size (16-bits at offset 16) 2430 ** + Size of db in pages (32-bits at offset 28) 2431 ** + Database encoding (32-bits at offset 56) 2432 ** 2433 ** Also preserved are: 2434 ** 2435 ** + first freelist page (32-bits at offset 32) 2436 ** + size of freelist (32-bits at offset 36) 2437 ** + the wal-mode flags (16-bits at offset 18) 2438 ** 2439 ** We also try to preserve the auto-vacuum, incr-value, user-version 2440 ** and application-id fields - all 32 bit quantities at offsets 2441 ** 52, 60, 64 and 68. All other fields are set to known good values. 2442 ** 2443 ** Byte offset 105 should also contain the page-size as a 16-bit 2444 ** integer. 2445 */ 2446 const int aPreserve[] = {32, 36, 52, 60, 64, 68}; 2447 u8 aHdr[108] = { 2448 0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66, 2449 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00, 2450 0xFF, 0xFF, 0x01, 0x01, 0x00, 0x40, 0x20, 0x20, 2451 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 2452 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 2453 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 2454 0x00, 0x00, 0x10, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 2455 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 2456 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 2457 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 2458 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 2459 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 2460 0x00, 0x2e, 0x5b, 0x30, 2461 2462 0x0D, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00 2463 }; 2464 u8 *a = (u8*)aBuf; 2465 2466 u32 pgsz = recoverGetU16(&a[16]); 2467 u32 nReserve = a[20]; 2468 u32 enc = recoverGetU32(&a[56]); 2469 u32 dbsz = 0; 2470 i64 dbFileSize = 0; 2471 int ii; 2472 sqlite3_recover *p = recover_g.p; 2473 2474 if( pgsz==0x01 ) pgsz = 65536; 2475 rc = pFd->pMethods->xFileSize(pFd, &dbFileSize); 2476 2477 if( rc==SQLITE_OK && p->detected_pgsz==0 ){ 2478 rc = recoverVfsDetectPagesize(p, pFd, nReserve, dbFileSize); 2479 } 2480 if( p->detected_pgsz ){ 2481 pgsz = p->detected_pgsz; 2482 nReserve = p->nReserve; 2483 } 2484 2485 if( pgsz ){ 2486 dbsz = dbFileSize / pgsz; 2487 } 2488 if( enc!=SQLITE_UTF8 && enc!=SQLITE_UTF16BE && enc!=SQLITE_UTF16LE ){ 2489 enc = SQLITE_UTF8; 2490 } 2491 2492 sqlite3_free(p->pPage1Cache); 2493 p->pPage1Cache = 0; 2494 p->pPage1Disk = 0; 2495 2496 p->pgsz = nByte; 2497 p->pPage1Cache = (u8*)recoverMalloc(p, nByte*2); 2498 if( p->pPage1Cache ){ 2499 p->pPage1Disk = &p->pPage1Cache[nByte]; 2500 memcpy(p->pPage1Disk, aBuf, nByte); 2501 aHdr[18] = a[18]; 2502 aHdr[19] = a[19]; 2503 recoverPutU32(&aHdr[28], dbsz); 2504 recoverPutU32(&aHdr[56], enc); 2505 recoverPutU16(&aHdr[105], pgsz-nReserve); 2506 if( pgsz==65536 ) pgsz = 1; 2507 recoverPutU16(&aHdr[16], pgsz); 2508 aHdr[20] = nReserve; 2509 for(ii=0; ii<(int)(sizeof(aPreserve)/sizeof(aPreserve[0])); ii++){ 2510 memcpy(&aHdr[aPreserve[ii]], &a[aPreserve[ii]], 4); 2511 } 2512 memcpy(aBuf, aHdr, sizeof(aHdr)); 2513 memset(&((u8*)aBuf)[sizeof(aHdr)], 0, nByte-sizeof(aHdr)); 2514 2515 memcpy(p->pPage1Cache, aBuf, nByte); 2516 }else{ 2517 rc = p->errCode; 2518 } 2519 2520 } 2521 pFd->pMethods = &recover_methods; 2522 }else{ 2523 rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff); 2524 } 2525 return rc; 2526 } 2527 2528 /* 2529 ** Used to make sqlite3_io_methods wrapper methods less verbose. 2530 */ 2531 #define RECOVER_VFS_WRAPPER(code) \ 2532 int rc = SQLITE_OK; \ 2533 if( pFd->pMethods==&recover_methods ){ \ 2534 pFd->pMethods = recover_g.pMethods; \ 2535 rc = code; \ 2536 pFd->pMethods = &recover_methods; \ 2537 }else{ \ 2538 rc = code; \ 2539 } \ 2540 return rc; 2541 2542 /* 2543 ** Methods of the wrapper VFS. All methods except for xRead() and xClose() 2544 ** simply uninstall the sqlite3_io_methods wrapper, invoke the equivalent 2545 ** method on the lower level VFS, then reinstall the wrapper before returning. 2546 ** Those that return an integer value use the RECOVER_VFS_WRAPPER macro. 2547 */ 2548 static int recoverVfsWrite( 2549 sqlite3_file *pFd, const void *aBuf, int nByte, i64 iOff 2550 ){ 2551 RECOVER_VFS_WRAPPER ( 2552 pFd->pMethods->xWrite(pFd, aBuf, nByte, iOff) 2553 ); 2554 } 2555 static int recoverVfsTruncate(sqlite3_file *pFd, sqlite3_int64 size){ 2556 RECOVER_VFS_WRAPPER ( 2557 pFd->pMethods->xTruncate(pFd, size) 2558 ); 2559 } 2560 static int recoverVfsSync(sqlite3_file *pFd, int flags){ 2561 RECOVER_VFS_WRAPPER ( 2562 pFd->pMethods->xSync(pFd, flags) 2563 ); 2564 } 2565 static int recoverVfsFileSize(sqlite3_file *pFd, sqlite3_int64 *pSize){ 2566 RECOVER_VFS_WRAPPER ( 2567 pFd->pMethods->xFileSize(pFd, pSize) 2568 ); 2569 } 2570 static int recoverVfsLock(sqlite3_file *pFd, int eLock){ 2571 RECOVER_VFS_WRAPPER ( 2572 pFd->pMethods->xLock(pFd, eLock) 2573 ); 2574 } 2575 static int recoverVfsUnlock(sqlite3_file *pFd, int eLock){ 2576 RECOVER_VFS_WRAPPER ( 2577 pFd->pMethods->xUnlock(pFd, eLock) 2578 ); 2579 } 2580 static int recoverVfsCheckReservedLock(sqlite3_file *pFd, int *pResOut){ 2581 RECOVER_VFS_WRAPPER ( 2582 pFd->pMethods->xCheckReservedLock(pFd, pResOut) 2583 ); 2584 } 2585 static int recoverVfsFileControl(sqlite3_file *pFd, int op, void *pArg){ 2586 RECOVER_VFS_WRAPPER ( 2587 (pFd->pMethods ? pFd->pMethods->xFileControl(pFd, op, pArg) : SQLITE_NOTFOUND) 2588 ); 2589 } 2590 static int recoverVfsSectorSize(sqlite3_file *pFd){ 2591 RECOVER_VFS_WRAPPER ( 2592 pFd->pMethods->xSectorSize(pFd) 2593 ); 2594 } 2595 static int recoverVfsDeviceCharacteristics(sqlite3_file *pFd){ 2596 RECOVER_VFS_WRAPPER ( 2597 pFd->pMethods->xDeviceCharacteristics(pFd) 2598 ); 2599 } 2600 static int recoverVfsShmMap( 2601 sqlite3_file *pFd, int iPg, int pgsz, int bExtend, void volatile **pp 2602 ){ 2603 RECOVER_VFS_WRAPPER ( 2604 pFd->pMethods->xShmMap(pFd, iPg, pgsz, bExtend, pp) 2605 ); 2606 } 2607 static int recoverVfsShmLock(sqlite3_file *pFd, int offset, int n, int flags){ 2608 RECOVER_VFS_WRAPPER ( 2609 pFd->pMethods->xShmLock(pFd, offset, n, flags) 2610 ); 2611 } 2612 static void recoverVfsShmBarrier(sqlite3_file *pFd){ 2613 if( pFd->pMethods==&recover_methods ){ 2614 pFd->pMethods = recover_g.pMethods; 2615 pFd->pMethods->xShmBarrier(pFd); 2616 pFd->pMethods = &recover_methods; 2617 }else{ 2618 pFd->pMethods->xShmBarrier(pFd); 2619 } 2620 } 2621 static int recoverVfsShmUnmap(sqlite3_file *pFd, int deleteFlag){ 2622 RECOVER_VFS_WRAPPER ( 2623 pFd->pMethods->xShmUnmap(pFd, deleteFlag) 2624 ); 2625 } 2626 2627 static int recoverVfsFetch( 2628 sqlite3_file *pFd, 2629 sqlite3_int64 iOff, 2630 int iAmt, 2631 void **pp 2632 ){ 2633 (void)pFd; 2634 (void)iOff; 2635 (void)iAmt; 2636 *pp = 0; 2637 return SQLITE_OK; 2638 } 2639 static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p){ 2640 (void)pFd; 2641 (void)iOff; 2642 (void)p; 2643 return SQLITE_OK; 2644 } 2645 2646 /* 2647 ** Install the VFS wrapper around the file-descriptor open on the input 2648 ** database for recover handle p. Mutex RECOVER_MUTEX_ID must be held 2649 ** when this function is called. 2650 */ 2651 static void recoverInstallWrapper(sqlite3_recover *p){ 2652 sqlite3_file *pFd = 0; 2653 assert( recover_g.pMethods==0 ); 2654 recoverAssertMutexHeld(); 2655 sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_FILE_POINTER, (void*)&pFd); 2656 assert( pFd==0 || pFd->pMethods!=&recover_methods ); 2657 if( pFd && pFd->pMethods ){ 2658 int iVersion = 1 + (pFd->pMethods->iVersion>1 && pFd->pMethods->xShmMap!=0); 2659 recover_g.pMethods = pFd->pMethods; 2660 recover_g.p = p; 2661 recover_methods.iVersion = iVersion; 2662 pFd->pMethods = &recover_methods; 2663 } 2664 } 2665 2666 /* 2667 ** Uninstall the VFS wrapper that was installed around the file-descriptor open 2668 ** on the input database for recover handle p. Mutex RECOVER_MUTEX_ID must be 2669 ** held when this function is called. 2670 */ 2671 static void recoverUninstallWrapper(sqlite3_recover *p){ 2672 sqlite3_file *pFd = 0; 2673 recoverAssertMutexHeld(); 2674 sqlite3_file_control(p->dbIn, p->zDb,SQLITE_FCNTL_FILE_POINTER,(void*)&pFd); 2675 if( pFd && pFd->pMethods ){ 2676 pFd->pMethods = recover_g.pMethods; 2677 recover_g.pMethods = 0; 2678 recover_g.p = 0; 2679 } 2680 } 2681 2682 /* 2683 ** This function does the work of a single sqlite3_recover_step() call. It 2684 ** is guaranteed that the handle is not in an error state when this 2685 ** function is called. 2686 */ 2687 static void recoverStep(sqlite3_recover *p){ 2688 assert( p && p->errCode==SQLITE_OK ); 2689 switch( p->eState ){ 2690 case RECOVER_STATE_INIT: { 2691 int bUseWrapper = 1; 2692 /* This is the very first call to sqlite3_recover_step() on this object. 2693 */ 2694 recoverSqlCallback(p, "BEGIN"); 2695 recoverSqlCallback(p, "PRAGMA writable_schema = on"); 2696 recoverSqlCallback(p, "PRAGMA foreign_keys = off"); 2697 2698 recoverEnterMutex(); 2699 2700 /* Open the output database. And register required virtual tables and 2701 ** user functions with the new handle. */ 2702 recoverOpenOutput(p); 2703 2704 /* Attempt to open a transaction and read page 1 of the input database. 2705 ** Two attempts may be made - one with a wrapper installed to ensure 2706 ** that the database header is sane, and then if that attempt returns 2707 ** SQLITE_NOTADB, then again with no wrapper. The second attempt is 2708 ** required for encrypted databases. */ 2709 if( p->errCode==SQLITE_OK ){ 2710 do{ 2711 p->errCode = SQLITE_OK; 2712 if( bUseWrapper ) recoverInstallWrapper(p); 2713 2714 /* Open a transaction on the input database. */ 2715 sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0); 2716 recoverExec(p, p->dbIn, "PRAGMA writable_schema = on"); 2717 recoverExec(p, p->dbIn, "BEGIN"); 2718 if( p->errCode==SQLITE_OK ) p->bCloseTransaction = 1; 2719 recoverExec(p, p->dbIn, "SELECT 1 FROM sqlite_schema"); 2720 recoverTransferSettings(p); 2721 recoverOpenRecovery(p); 2722 recoverCacheSchema(p); 2723 2724 if( bUseWrapper ) recoverUninstallWrapper(p); 2725 }while( p->errCode==SQLITE_NOTADB 2726 && (bUseWrapper--) 2727 && SQLITE_OK==recoverOneStmt(p->dbIn, "ROLLBACK", 0) 2728 ); 2729 } 2730 2731 recoverLeaveMutex(); 2732 recoverExec(p, p->dbOut, "BEGIN"); 2733 recoverWriteSchema1(p); 2734 p->eState = RECOVER_STATE_WRITING; 2735 break; 2736 } 2737 2738 case RECOVER_STATE_WRITING: { 2739 if( p->w1.pTbls==0 ){ 2740 recoverWriteDataInit(p); 2741 } 2742 if( SQLITE_DONE==recoverWriteDataStep(p) ){ 2743 recoverWriteDataCleanup(p); 2744 if( p->zLostAndFound ){ 2745 p->eState = RECOVER_STATE_LOSTANDFOUND1; 2746 }else{ 2747 p->eState = RECOVER_STATE_SCHEMA2; 2748 } 2749 } 2750 break; 2751 } 2752 2753 case RECOVER_STATE_LOSTANDFOUND1: { 2754 if( p->laf.pUsed==0 ){ 2755 recoverLostAndFound1Init(p); 2756 } 2757 if( SQLITE_DONE==recoverLostAndFound1Step(p) ){ 2758 p->eState = RECOVER_STATE_LOSTANDFOUND2; 2759 } 2760 break; 2761 } 2762 case RECOVER_STATE_LOSTANDFOUND2: { 2763 if( p->laf.pAllAndParent==0 ){ 2764 recoverLostAndFound2Init(p); 2765 } 2766 if( SQLITE_DONE==recoverLostAndFound2Step(p) ){ 2767 p->eState = RECOVER_STATE_LOSTANDFOUND3; 2768 } 2769 break; 2770 } 2771 2772 case RECOVER_STATE_LOSTANDFOUND3: { 2773 if( p->laf.pInsert==0 ){ 2774 recoverLostAndFound3Init(p); 2775 } 2776 if( SQLITE_DONE==recoverLostAndFound3Step(p) ){ 2777 p->eState = RECOVER_STATE_SCHEMA2; 2778 } 2779 break; 2780 } 2781 2782 case RECOVER_STATE_SCHEMA2: { 2783 int rc = SQLITE_OK; 2784 2785 recoverWriteSchema2(p); 2786 p->eState = RECOVER_STATE_DONE; 2787 2788 /* If no error has occurred, commit the write transaction on the output 2789 ** database. Regardless of whether or not an error has occurred, make 2790 ** an attempt to end the read transaction on the input database. */ 2791 recoverExec(p, p->dbOut, "COMMIT"); 2792 rc = recoverOneStmt(p->dbIn, "END", 0); 2793 if( p->errCode==SQLITE_OK ) p->errCode = rc; 2794 2795 recoverSqlCallback(p, "PRAGMA writable_schema = off"); 2796 recoverSqlCallback(p, "COMMIT"); 2797 p->eState = RECOVER_STATE_DONE; 2798 recoverFinalCleanup(p); 2799 break; 2800 }; 2801 2802 case RECOVER_STATE_DONE: { 2803 /* no-op */ 2804 break; 2805 }; 2806 } 2807 } 2808 2809 2810 /* 2811 ** This is a worker function that does the heavy lifting for both init 2812 ** functions: 2813 ** 2814 ** sqlite3_recover_init() 2815 ** sqlite3_recover_init_sql() 2816 ** 2817 ** All this function does is allocate space for the recover handle and 2818 ** take copies of the input parameters. All the real work is done within 2819 ** sqlite3_recover_run(). 2820 */ 2821 sqlite3_recover *recoverInit( 2822 sqlite3* db, 2823 const char *zDb, 2824 const char *zUri, /* Output URI for _recover_init() */ 2825 int (*xSql)(void*, const char*),/* SQL callback for _recover_init_sql() */ 2826 void *pSqlCtx /* Context arg for _recover_init_sql() */ 2827 ){ 2828 sqlite3_recover *pRet = 0; 2829 int nDb = 0; 2830 int nUri = 0; 2831 int nByte = 0; 2832 2833 if( zDb==0 ){ zDb = "main"; } 2834 2835 nDb = recoverStrlen(zDb); 2836 nUri = recoverStrlen(zUri); 2837 2838 nByte = sizeof(sqlite3_recover) + nDb+1 + nUri+1; 2839 pRet = (sqlite3_recover*)sqlite3_malloc(nByte); 2840 if( pRet ){ 2841 memset(pRet, 0, nByte); 2842 pRet->dbIn = db; 2843 pRet->zDb = (char*)&pRet[1]; 2844 pRet->zUri = &pRet->zDb[nDb+1]; 2845 memcpy(pRet->zDb, zDb, nDb); 2846 if( nUri>0 && zUri ) memcpy(pRet->zUri, zUri, nUri); 2847 pRet->xSql = xSql; 2848 pRet->pSqlCtx = pSqlCtx; 2849 pRet->bRecoverRowid = RECOVER_ROWID_DEFAULT; 2850 } 2851 2852 return pRet; 2853 } 2854 2855 /* 2856 ** Initialize a recovery handle that creates a new database containing 2857 ** the recovered data. 2858 */ 2859 sqlite3_recover *sqlite3_recover_init( 2860 sqlite3* db, 2861 const char *zDb, 2862 const char *zUri 2863 ){ 2864 return recoverInit(db, zDb, zUri, 0, 0); 2865 } 2866 2867 /* 2868 ** Initialize a recovery handle that returns recovered data in the 2869 ** form of SQL statements via a callback. 2870 */ 2871 sqlite3_recover *sqlite3_recover_init_sql( 2872 sqlite3* db, 2873 const char *zDb, 2874 int (*xSql)(void*, const char*), 2875 void *pSqlCtx 2876 ){ 2877 return recoverInit(db, zDb, 0, xSql, pSqlCtx); 2878 } 2879 2880 /* 2881 ** Return the handle error message, if any. 2882 */ 2883 const char *sqlite3_recover_errmsg(sqlite3_recover *p){ 2884 return (p && p->errCode!=SQLITE_NOMEM) ? p->zErrMsg : "out of memory"; 2885 } 2886 2887 /* 2888 ** Return the handle error code. 2889 */ 2890 int sqlite3_recover_errcode(sqlite3_recover *p){ 2891 return p ? p->errCode : SQLITE_NOMEM; 2892 } 2893 2894 /* 2895 ** Configure the handle. 2896 */ 2897 int sqlite3_recover_config(sqlite3_recover *p, int op, void *pArg){ 2898 int rc = SQLITE_OK; 2899 if( p==0 ){ 2900 rc = SQLITE_NOMEM; 2901 }else if( p->eState!=RECOVER_STATE_INIT ){ 2902 rc = SQLITE_MISUSE; 2903 }else{ 2904 switch( op ){ 2905 case 789: 2906 /* This undocumented magic configuration option is used to set the 2907 ** name of the auxiliary database that is ATTACH-ed to the database 2908 ** connection and used to hold state information during the 2909 ** recovery process. This option is for debugging use only and 2910 ** is subject to change or removal at any time. */ 2911 sqlite3_free(p->zStateDb); 2912 p->zStateDb = recoverMPrintf(p, "%s", (char*)pArg); 2913 break; 2914 2915 case SQLITE_RECOVER_LOST_AND_FOUND: { 2916 const char *zArg = (const char*)pArg; 2917 sqlite3_free(p->zLostAndFound); 2918 if( zArg ){ 2919 p->zLostAndFound = recoverMPrintf(p, "%s", zArg); 2920 }else{ 2921 p->zLostAndFound = 0; 2922 } 2923 break; 2924 } 2925 2926 case SQLITE_RECOVER_FREELIST_CORRUPT: 2927 p->bFreelistCorrupt = *(int*)pArg; 2928 break; 2929 2930 case SQLITE_RECOVER_ROWIDS: 2931 p->bRecoverRowid = *(int*)pArg; 2932 break; 2933 2934 case SQLITE_RECOVER_SLOWINDEXES: 2935 p->bSlowIndexes = *(int*)pArg; 2936 break; 2937 2938 default: 2939 rc = SQLITE_NOTFOUND; 2940 break; 2941 } 2942 } 2943 2944 return rc; 2945 } 2946 2947 /* 2948 ** Do a unit of work towards the recovery job. Return SQLITE_OK if 2949 ** no error has occurred but database recovery is not finished, SQLITE_DONE 2950 ** if database recovery has been successfully completed, or an SQLite 2951 ** error code if an error has occurred. 2952 */ 2953 int sqlite3_recover_step(sqlite3_recover *p){ 2954 if( p==0 ) return SQLITE_NOMEM; 2955 if( p->errCode==SQLITE_OK ) recoverStep(p); 2956 if( p->eState==RECOVER_STATE_DONE && p->errCode==SQLITE_OK ){ 2957 return SQLITE_DONE; 2958 } 2959 return p->errCode; 2960 } 2961 2962 /* 2963 ** Do the configured recovery operation. Return SQLITE_OK if successful, or 2964 ** else an SQLite error code. 2965 */ 2966 int sqlite3_recover_run(sqlite3_recover *p){ 2967 while( SQLITE_OK==sqlite3_recover_step(p) ); 2968 return sqlite3_recover_errcode(p); 2969 } 2970 2971 2972 /* 2973 ** Free all resources associated with the recover handle passed as the only 2974 ** argument. The results of using a handle with any sqlite3_recover_** 2975 ** API function after it has been passed to this function are undefined. 2976 ** 2977 ** A copy of the value returned by the first call made to sqlite3_recover_run() 2978 ** on this handle is returned, or SQLITE_OK if sqlite3_recover_run() has 2979 ** not been called on this handle. 2980 */ 2981 int sqlite3_recover_finish(sqlite3_recover *p){ 2982 int rc; 2983 if( p==0 ){ 2984 rc = SQLITE_NOMEM; 2985 }else{ 2986 recoverFinalCleanup(p); 2987 if( p->bCloseTransaction && sqlite3_get_autocommit(p->dbIn)==0 ){ 2988 rc = recoverOneStmt(p->dbIn, "END", 0); 2989 if( p->errCode==SQLITE_OK ) p->errCode = rc; 2990 } 2991 rc = p->errCode; 2992 sqlite3_free(p->zErrMsg); 2993 sqlite3_free(p->zStateDb); 2994 sqlite3_free(p->zLostAndFound); 2995 sqlite3_free(p->pPage1Cache); 2996 sqlite3_free(p); 2997 } 2998 return rc; 2999 } 3000 3001 #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */