You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2870 lines
86 KiB

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