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.

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