sqlite3recover.c 86 KB

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