ActorsChild.cpp 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  4. * You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. #include "ActorsChild.h"
  6. #include "BackgroundChildImpl.h"
  7. #include "IDBDatabase.h"
  8. #include "IDBEvents.h"
  9. #include "IDBFactory.h"
  10. #include "IDBIndex.h"
  11. #include "IDBMutableFile.h"
  12. #include "IDBObjectStore.h"
  13. #include "IDBMutableFile.h"
  14. #include "IDBRequest.h"
  15. #include "IDBTransaction.h"
  16. #include "IndexedDatabase.h"
  17. #include "IndexedDatabaseInlines.h"
  18. #include "mozilla/BasicEvents.h"
  19. #include "mozilla/Maybe.h"
  20. #include "mozilla/TypeTraits.h"
  21. #include "mozilla/dom/Element.h"
  22. #include "mozilla/dom/PermissionMessageUtils.h"
  23. #include "mozilla/dom/TabChild.h"
  24. #include "mozilla/dom/indexedDB/PBackgroundIDBDatabaseFileChild.h"
  25. #include "mozilla/dom/indexedDB/PIndexedDBPermissionRequestChild.h"
  26. #include "mozilla/dom/ipc/BlobChild.h"
  27. #include "mozilla/ipc/BackgroundUtils.h"
  28. #include "nsCOMPtr.h"
  29. #include "nsContentUtils.h"
  30. #include "nsIBFCacheEntry.h"
  31. #include "nsIDocument.h"
  32. #include "nsIDOMEvent.h"
  33. #include "nsIEventTarget.h"
  34. #include "nsIFileStreams.h"
  35. #include "nsNetCID.h"
  36. #include "nsPIDOMWindow.h"
  37. #include "nsThreadUtils.h"
  38. #include "nsTraceRefcnt.h"
  39. #include "PermissionRequestBase.h"
  40. #include "ProfilerHelpers.h"
  41. #include "ReportInternalError.h"
  42. #include "WorkerPrivate.h"
  43. #include "WorkerRunnable.h"
  44. #ifdef DEBUG
  45. #include "IndexedDatabaseManager.h"
  46. #endif
  47. #define GC_ON_IPC_MESSAGES 0
  48. #if defined(DEBUG) || GC_ON_IPC_MESSAGES
  49. #include "js/GCAPI.h"
  50. #include "nsJSEnvironment.h"
  51. #define BUILD_GC_ON_IPC_MESSAGES
  52. #endif // DEBUG || GC_ON_IPC_MESSAGES
  53. namespace mozilla {
  54. using ipc::PrincipalInfo;
  55. namespace dom {
  56. using namespace workers;
  57. namespace indexedDB {
  58. /*******************************************************************************
  59. * ThreadLocal
  60. ******************************************************************************/
  61. ThreadLocal::ThreadLocal(const nsID& aBackgroundChildLoggingId)
  62. : mLoggingInfo(aBackgroundChildLoggingId, 1, -1, 1)
  63. , mCurrentTransaction(0)
  64. #ifdef DEBUG
  65. , mOwningThread(PR_GetCurrentThread())
  66. #endif
  67. {
  68. MOZ_ASSERT(mOwningThread);
  69. MOZ_COUNT_CTOR(mozilla::dom::indexedDB::ThreadLocal);
  70. // NSID_LENGTH counts the null terminator, SetLength() does not.
  71. mLoggingIdString.SetLength(NSID_LENGTH - 1);
  72. aBackgroundChildLoggingId.ToProvidedString(
  73. *reinterpret_cast<char(*)[NSID_LENGTH]>(mLoggingIdString.BeginWriting()));
  74. }
  75. ThreadLocal::~ThreadLocal()
  76. {
  77. MOZ_COUNT_DTOR(mozilla::dom::indexedDB::ThreadLocal);
  78. }
  79. #ifdef DEBUG
  80. void
  81. ThreadLocal::AssertIsOnOwningThread() const
  82. {
  83. MOZ_ASSERT(PR_GetCurrentThread() == mOwningThread);
  84. }
  85. #endif // DEBUG
  86. /*******************************************************************************
  87. * Helpers
  88. ******************************************************************************/
  89. namespace {
  90. void
  91. MaybeCollectGarbageOnIPCMessage()
  92. {
  93. #ifdef BUILD_GC_ON_IPC_MESSAGES
  94. static const bool kCollectGarbageOnIPCMessages =
  95. #if GC_ON_IPC_MESSAGES
  96. true;
  97. #else
  98. false;
  99. #endif // GC_ON_IPC_MESSAGES
  100. if (!kCollectGarbageOnIPCMessages) {
  101. return;
  102. }
  103. static bool haveWarnedAboutGC = false;
  104. static bool haveWarnedAboutNonMainThread = false;
  105. if (!haveWarnedAboutGC) {
  106. haveWarnedAboutGC = true;
  107. NS_WARNING("IndexedDB child actor GC debugging enabled!");
  108. }
  109. if (!NS_IsMainThread()) {
  110. if (!haveWarnedAboutNonMainThread) {
  111. haveWarnedAboutNonMainThread = true;
  112. NS_WARNING("Don't know how to GC on a non-main thread yet.");
  113. }
  114. return;
  115. }
  116. nsJSContext::GarbageCollectNow(JS::gcreason::DOM_IPC);
  117. nsJSContext::CycleCollectNow();
  118. #endif // BUILD_GC_ON_IPC_MESSAGES
  119. }
  120. class MOZ_STACK_CLASS AutoSetCurrentTransaction final
  121. {
  122. typedef mozilla::ipc::BackgroundChildImpl BackgroundChildImpl;
  123. IDBTransaction* const mTransaction;
  124. IDBTransaction* mPreviousTransaction;
  125. ThreadLocal* mThreadLocal;
  126. public:
  127. explicit AutoSetCurrentTransaction(IDBTransaction* aTransaction)
  128. : mTransaction(aTransaction)
  129. , mPreviousTransaction(nullptr)
  130. , mThreadLocal(nullptr)
  131. {
  132. if (aTransaction) {
  133. BackgroundChildImpl::ThreadLocal* threadLocal =
  134. BackgroundChildImpl::GetThreadLocalForCurrentThread();
  135. MOZ_ASSERT(threadLocal);
  136. // Hang onto this for resetting later.
  137. mThreadLocal = threadLocal->mIndexedDBThreadLocal;
  138. MOZ_ASSERT(mThreadLocal);
  139. // Save the current value.
  140. mPreviousTransaction = mThreadLocal->GetCurrentTransaction();
  141. // Set the new value.
  142. mThreadLocal->SetCurrentTransaction(aTransaction);
  143. }
  144. }
  145. ~AutoSetCurrentTransaction()
  146. {
  147. MOZ_ASSERT_IF(mThreadLocal, mTransaction);
  148. MOZ_ASSERT_IF(mThreadLocal,
  149. mThreadLocal->GetCurrentTransaction() == mTransaction);
  150. if (mThreadLocal) {
  151. // Reset old value.
  152. mThreadLocal->SetCurrentTransaction(mPreviousTransaction);
  153. }
  154. }
  155. IDBTransaction*
  156. Transaction() const
  157. {
  158. return mTransaction;
  159. }
  160. };
  161. class MOZ_STACK_CLASS ResultHelper final
  162. : public IDBRequest::ResultCallback
  163. {
  164. IDBRequest* mRequest;
  165. AutoSetCurrentTransaction mAutoTransaction;
  166. union
  167. {
  168. IDBDatabase* mDatabase;
  169. IDBCursor* mCursor;
  170. IDBMutableFile* mMutableFile;
  171. StructuredCloneReadInfo* mStructuredClone;
  172. const nsTArray<StructuredCloneReadInfo>* mStructuredCloneArray;
  173. const Key* mKey;
  174. const nsTArray<Key>* mKeyArray;
  175. const JS::Value* mJSVal;
  176. const JS::Handle<JS::Value>* mJSValHandle;
  177. } mResult;
  178. enum
  179. {
  180. ResultTypeDatabase,
  181. ResultTypeCursor,
  182. ResultTypeMutableFile,
  183. ResultTypeStructuredClone,
  184. ResultTypeStructuredCloneArray,
  185. ResultTypeKey,
  186. ResultTypeKeyArray,
  187. ResultTypeJSVal,
  188. ResultTypeJSValHandle,
  189. } mResultType;
  190. public:
  191. ResultHelper(IDBRequest* aRequest,
  192. IDBTransaction* aTransaction,
  193. IDBDatabase* aResult)
  194. : mRequest(aRequest)
  195. , mAutoTransaction(aTransaction)
  196. , mResultType(ResultTypeDatabase)
  197. {
  198. MOZ_ASSERT(aRequest);
  199. MOZ_ASSERT(aResult);
  200. mResult.mDatabase = aResult;
  201. }
  202. ResultHelper(IDBRequest* aRequest,
  203. IDBTransaction* aTransaction,
  204. IDBCursor* aResult)
  205. : mRequest(aRequest)
  206. , mAutoTransaction(aTransaction)
  207. , mResultType(ResultTypeCursor)
  208. {
  209. MOZ_ASSERT(aRequest);
  210. mResult.mCursor = aResult;
  211. }
  212. ResultHelper(IDBRequest* aRequest,
  213. IDBTransaction* aTransaction,
  214. IDBMutableFile* aResult)
  215. : mRequest(aRequest)
  216. , mAutoTransaction(aTransaction)
  217. , mResultType(ResultTypeMutableFile)
  218. {
  219. MOZ_ASSERT(aRequest);
  220. mResult.mMutableFile = aResult;
  221. }
  222. ResultHelper(IDBRequest* aRequest,
  223. IDBTransaction* aTransaction,
  224. StructuredCloneReadInfo* aResult)
  225. : mRequest(aRequest)
  226. , mAutoTransaction(aTransaction)
  227. , mResultType(ResultTypeStructuredClone)
  228. {
  229. MOZ_ASSERT(aRequest);
  230. MOZ_ASSERT(aResult);
  231. mResult.mStructuredClone = aResult;
  232. }
  233. ResultHelper(IDBRequest* aRequest,
  234. IDBTransaction* aTransaction,
  235. const nsTArray<StructuredCloneReadInfo>* aResult)
  236. : mRequest(aRequest)
  237. , mAutoTransaction(aTransaction)
  238. , mResultType(ResultTypeStructuredCloneArray)
  239. {
  240. MOZ_ASSERT(aRequest);
  241. MOZ_ASSERT(aResult);
  242. mResult.mStructuredCloneArray = aResult;
  243. }
  244. ResultHelper(IDBRequest* aRequest,
  245. IDBTransaction* aTransaction,
  246. const Key* aResult)
  247. : mRequest(aRequest)
  248. , mAutoTransaction(aTransaction)
  249. , mResultType(ResultTypeKey)
  250. {
  251. MOZ_ASSERT(aRequest);
  252. MOZ_ASSERT(aResult);
  253. mResult.mKey = aResult;
  254. }
  255. ResultHelper(IDBRequest* aRequest,
  256. IDBTransaction* aTransaction,
  257. const nsTArray<Key>* aResult)
  258. : mRequest(aRequest)
  259. , mAutoTransaction(aTransaction)
  260. , mResultType(ResultTypeKeyArray)
  261. {
  262. MOZ_ASSERT(aRequest);
  263. MOZ_ASSERT(aResult);
  264. mResult.mKeyArray = aResult;
  265. }
  266. ResultHelper(IDBRequest* aRequest,
  267. IDBTransaction* aTransaction,
  268. const JS::Value* aResult)
  269. : mRequest(aRequest)
  270. , mAutoTransaction(aTransaction)
  271. , mResultType(ResultTypeJSVal)
  272. {
  273. MOZ_ASSERT(aRequest);
  274. MOZ_ASSERT(!aResult->isGCThing());
  275. mResult.mJSVal = aResult;
  276. }
  277. ResultHelper(IDBRequest* aRequest,
  278. IDBTransaction* aTransaction,
  279. const JS::Handle<JS::Value>* aResult)
  280. : mRequest(aRequest)
  281. , mAutoTransaction(aTransaction)
  282. , mResultType(ResultTypeJSValHandle)
  283. {
  284. MOZ_ASSERT(aRequest);
  285. mResult.mJSValHandle = aResult;
  286. }
  287. IDBRequest*
  288. Request() const
  289. {
  290. return mRequest;
  291. }
  292. IDBTransaction*
  293. Transaction() const
  294. {
  295. return mAutoTransaction.Transaction();
  296. }
  297. virtual nsresult
  298. GetResult(JSContext* aCx, JS::MutableHandle<JS::Value> aResult) override
  299. {
  300. MOZ_ASSERT(aCx);
  301. MOZ_ASSERT(mRequest);
  302. switch (mResultType) {
  303. case ResultTypeDatabase:
  304. return GetResult(aCx, mResult.mDatabase, aResult);
  305. case ResultTypeCursor:
  306. return GetResult(aCx, mResult.mCursor, aResult);
  307. case ResultTypeMutableFile:
  308. return GetResult(aCx, mResult.mMutableFile, aResult);
  309. case ResultTypeStructuredClone:
  310. return GetResult(aCx, mResult.mStructuredClone, aResult);
  311. case ResultTypeStructuredCloneArray:
  312. return GetResult(aCx, mResult.mStructuredCloneArray, aResult);
  313. case ResultTypeKey:
  314. return GetResult(aCx, mResult.mKey, aResult);
  315. case ResultTypeKeyArray:
  316. return GetResult(aCx, mResult.mKeyArray, aResult);
  317. case ResultTypeJSVal:
  318. aResult.set(*mResult.mJSVal);
  319. return NS_OK;
  320. case ResultTypeJSValHandle:
  321. aResult.set(*mResult.mJSValHandle);
  322. return NS_OK;
  323. default:
  324. MOZ_CRASH("Unknown result type!");
  325. }
  326. MOZ_CRASH("Should never get here!");
  327. }
  328. private:
  329. template <class T>
  330. typename EnableIf<IsSame<T, IDBDatabase>::value ||
  331. IsSame<T, IDBCursor>::value ||
  332. IsSame<T, IDBMutableFile>::value,
  333. nsresult>::Type
  334. GetResult(JSContext* aCx,
  335. T* aDOMObject,
  336. JS::MutableHandle<JS::Value> aResult)
  337. {
  338. if (!aDOMObject) {
  339. aResult.setNull();
  340. return NS_OK;
  341. }
  342. bool ok = GetOrCreateDOMReflector(aCx, aDOMObject, aResult);
  343. if (NS_WARN_IF(!ok)) {
  344. IDB_REPORT_INTERNAL_ERR();
  345. return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
  346. }
  347. return NS_OK;
  348. }
  349. nsresult
  350. GetResult(JSContext* aCx,
  351. StructuredCloneReadInfo* aCloneInfo,
  352. JS::MutableHandle<JS::Value> aResult)
  353. {
  354. bool ok = IDBObjectStore::DeserializeValue(aCx, *aCloneInfo, aResult);
  355. if (NS_WARN_IF(!ok)) {
  356. return NS_ERROR_DOM_DATA_CLONE_ERR;
  357. }
  358. return NS_OK;
  359. }
  360. nsresult
  361. GetResult(JSContext* aCx,
  362. const nsTArray<StructuredCloneReadInfo>* aCloneInfos,
  363. JS::MutableHandle<JS::Value> aResult)
  364. {
  365. JS::Rooted<JSObject*> array(aCx, JS_NewArrayObject(aCx, 0));
  366. if (NS_WARN_IF(!array)) {
  367. IDB_REPORT_INTERNAL_ERR();
  368. return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
  369. }
  370. if (!aCloneInfos->IsEmpty()) {
  371. const uint32_t count = aCloneInfos->Length();
  372. if (NS_WARN_IF(!JS_SetArrayLength(aCx, array, count))) {
  373. IDB_REPORT_INTERNAL_ERR();
  374. return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
  375. }
  376. for (uint32_t index = 0; index < count; index++) {
  377. auto& cloneInfo =
  378. const_cast<StructuredCloneReadInfo&>(aCloneInfos->ElementAt(index));
  379. JS::Rooted<JS::Value> value(aCx);
  380. nsresult rv = GetResult(aCx, &cloneInfo, &value);
  381. if (NS_WARN_IF(NS_FAILED(rv))) {
  382. return rv;
  383. }
  384. if (NS_WARN_IF(!JS_DefineElement(aCx, array, index, value,
  385. JSPROP_ENUMERATE))) {
  386. IDB_REPORT_INTERNAL_ERR();
  387. return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
  388. }
  389. }
  390. }
  391. aResult.setObject(*array);
  392. return NS_OK;
  393. }
  394. nsresult
  395. GetResult(JSContext* aCx,
  396. const Key* aKey,
  397. JS::MutableHandle<JS::Value> aResult)
  398. {
  399. nsresult rv = aKey->ToJSVal(aCx, aResult);
  400. if (NS_WARN_IF(NS_FAILED(rv))) {
  401. return rv;
  402. }
  403. return NS_OK;
  404. }
  405. nsresult
  406. GetResult(JSContext* aCx,
  407. const nsTArray<Key>* aKeys,
  408. JS::MutableHandle<JS::Value> aResult)
  409. {
  410. JS::Rooted<JSObject*> array(aCx, JS_NewArrayObject(aCx, 0));
  411. if (NS_WARN_IF(!array)) {
  412. IDB_REPORT_INTERNAL_ERR();
  413. return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
  414. }
  415. if (!aKeys->IsEmpty()) {
  416. const uint32_t count = aKeys->Length();
  417. if (NS_WARN_IF(!JS_SetArrayLength(aCx, array, count))) {
  418. IDB_REPORT_INTERNAL_ERR();
  419. return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
  420. }
  421. for (uint32_t index = 0; index < count; index++) {
  422. const Key& key = aKeys->ElementAt(index);
  423. MOZ_ASSERT(!key.IsUnset());
  424. JS::Rooted<JS::Value> value(aCx);
  425. nsresult rv = GetResult(aCx, &key, &value);
  426. if (NS_WARN_IF(NS_FAILED(rv))) {
  427. return rv;
  428. }
  429. if (NS_WARN_IF(!JS_DefineElement(aCx, array, index, value,
  430. JSPROP_ENUMERATE))) {
  431. IDB_REPORT_INTERNAL_ERR();
  432. return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
  433. }
  434. }
  435. }
  436. aResult.setObject(*array);
  437. return NS_OK;
  438. }
  439. };
  440. class PermissionRequestMainProcessHelper final
  441. : public PermissionRequestBase
  442. {
  443. BackgroundFactoryRequestChild* mActor;
  444. RefPtr<IDBFactory> mFactory;
  445. public:
  446. PermissionRequestMainProcessHelper(BackgroundFactoryRequestChild* aActor,
  447. IDBFactory* aFactory,
  448. Element* aOwnerElement,
  449. nsIPrincipal* aPrincipal)
  450. : PermissionRequestBase(aOwnerElement, aPrincipal)
  451. , mActor(aActor)
  452. , mFactory(aFactory)
  453. {
  454. MOZ_ASSERT(aActor);
  455. MOZ_ASSERT(aFactory);
  456. aActor->AssertIsOnOwningThread();
  457. }
  458. protected:
  459. ~PermissionRequestMainProcessHelper()
  460. { }
  461. private:
  462. virtual void
  463. OnPromptComplete(PermissionValue aPermissionValue) override;
  464. };
  465. class PermissionRequestChildProcessActor final
  466. : public PIndexedDBPermissionRequestChild
  467. {
  468. BackgroundFactoryRequestChild* mActor;
  469. RefPtr<IDBFactory> mFactory;
  470. public:
  471. PermissionRequestChildProcessActor(BackgroundFactoryRequestChild* aActor,
  472. IDBFactory* aFactory)
  473. : mActor(aActor)
  474. , mFactory(aFactory)
  475. {
  476. MOZ_ASSERT(aActor);
  477. MOZ_ASSERT(aFactory);
  478. aActor->AssertIsOnOwningThread();
  479. }
  480. protected:
  481. ~PermissionRequestChildProcessActor()
  482. { }
  483. virtual bool
  484. Recv__delete__(const uint32_t& aPermission) override;
  485. };
  486. void
  487. DeserializeStructuredCloneFiles(
  488. IDBDatabase* aDatabase,
  489. const nsTArray<SerializedStructuredCloneFile>& aSerializedFiles,
  490. const nsTArray<RefPtr<JS::WasmModule>>* aModuleSet,
  491. nsTArray<StructuredCloneFile>& aFiles)
  492. {
  493. MOZ_ASSERT_IF(aModuleSet, !aModuleSet->IsEmpty());
  494. MOZ_ASSERT(aFiles.IsEmpty());
  495. if (!aSerializedFiles.IsEmpty()) {
  496. uint32_t moduleIndex = 0;
  497. const uint32_t count = aSerializedFiles.Length();
  498. aFiles.SetCapacity(count);
  499. for (uint32_t index = 0; index < count; index++) {
  500. const SerializedStructuredCloneFile& serializedFile =
  501. aSerializedFiles[index];
  502. const BlobOrMutableFile& blobOrMutableFile = serializedFile.file();
  503. switch (serializedFile.type()) {
  504. case StructuredCloneFile::eBlob: {
  505. MOZ_ASSERT(blobOrMutableFile.type() == BlobOrMutableFile::TPBlobChild);
  506. auto* actor =
  507. static_cast<BlobChild*>(blobOrMutableFile.get_PBlobChild());
  508. RefPtr<BlobImpl> blobImpl = actor->GetBlobImpl();
  509. MOZ_ASSERT(blobImpl);
  510. RefPtr<Blob> blob = Blob::Create(aDatabase->GetOwner(), blobImpl);
  511. aDatabase->NoteReceivedBlob(blob);
  512. StructuredCloneFile* file = aFiles.AppendElement();
  513. MOZ_ASSERT(file);
  514. file->mType = StructuredCloneFile::eBlob;
  515. file->mBlob.swap(blob);
  516. break;
  517. }
  518. case StructuredCloneFile::eMutableFile: {
  519. MOZ_ASSERT(blobOrMutableFile.type() == BlobOrMutableFile::Tnull_t ||
  520. blobOrMutableFile.type() ==
  521. BlobOrMutableFile::TPBackgroundMutableFileChild);
  522. switch (blobOrMutableFile.type()) {
  523. case BlobOrMutableFile::Tnull_t: {
  524. StructuredCloneFile* file = aFiles.AppendElement();
  525. MOZ_ASSERT(file);
  526. file->mType = StructuredCloneFile::eMutableFile;
  527. break;
  528. }
  529. case BlobOrMutableFile::TPBackgroundMutableFileChild: {
  530. auto* actor =
  531. static_cast<BackgroundMutableFileChild*>(
  532. blobOrMutableFile.get_PBackgroundMutableFileChild());
  533. MOZ_ASSERT(actor);
  534. actor->EnsureDOMObject();
  535. auto* mutableFile =
  536. static_cast<IDBMutableFile*>(actor->GetDOMObject());
  537. MOZ_ASSERT(mutableFile);
  538. StructuredCloneFile* file = aFiles.AppendElement();
  539. MOZ_ASSERT(file);
  540. file->mType = StructuredCloneFile::eMutableFile;
  541. file->mMutableFile = mutableFile;
  542. actor->ReleaseDOMObject();
  543. break;
  544. }
  545. default:
  546. MOZ_CRASH("Should never get here!");
  547. }
  548. break;
  549. }
  550. case StructuredCloneFile::eStructuredClone: {
  551. StructuredCloneFile* file = aFiles.AppendElement();
  552. MOZ_ASSERT(file);
  553. file->mType = StructuredCloneFile::eStructuredClone;
  554. break;
  555. }
  556. case StructuredCloneFile::eWasmBytecode:
  557. case StructuredCloneFile::eWasmCompiled: {
  558. if (aModuleSet) {
  559. MOZ_ASSERT(blobOrMutableFile.type() == BlobOrMutableFile::Tnull_t);
  560. StructuredCloneFile* file = aFiles.AppendElement();
  561. MOZ_ASSERT(file);
  562. file->mType = serializedFile.type();
  563. MOZ_ASSERT(moduleIndex < aModuleSet->Length());
  564. file->mWasmModule = aModuleSet->ElementAt(moduleIndex);
  565. if (serializedFile.type() == StructuredCloneFile::eWasmCompiled) {
  566. moduleIndex++;
  567. }
  568. break;
  569. }
  570. MOZ_ASSERT(blobOrMutableFile.type() ==
  571. BlobOrMutableFile::TPBlobChild);
  572. auto* actor =
  573. static_cast<BlobChild*>(blobOrMutableFile.get_PBlobChild());
  574. RefPtr<BlobImpl> blobImpl = actor->GetBlobImpl();
  575. MOZ_ASSERT(blobImpl);
  576. RefPtr<Blob> blob = Blob::Create(aDatabase->GetOwner(), blobImpl);
  577. aDatabase->NoteReceivedBlob(blob);
  578. StructuredCloneFile* file = aFiles.AppendElement();
  579. MOZ_ASSERT(file);
  580. file->mType = serializedFile.type();
  581. file->mBlob.swap(blob);
  582. break;
  583. }
  584. default:
  585. MOZ_CRASH("Should never get here!");
  586. }
  587. }
  588. }
  589. }
  590. void
  591. DispatchErrorEvent(IDBRequest* aRequest,
  592. nsresult aErrorCode,
  593. IDBTransaction* aTransaction = nullptr,
  594. nsIDOMEvent* aEvent = nullptr)
  595. {
  596. MOZ_ASSERT(aRequest);
  597. aRequest->AssertIsOnOwningThread();
  598. MOZ_ASSERT(NS_FAILED(aErrorCode));
  599. MOZ_ASSERT(NS_ERROR_GET_MODULE(aErrorCode) == NS_ERROR_MODULE_DOM_INDEXEDDB);
  600. PROFILER_LABEL("IndexedDB",
  601. "DispatchErrorEvent",
  602. js::ProfileEntry::Category::STORAGE);
  603. RefPtr<IDBRequest> request = aRequest;
  604. RefPtr<IDBTransaction> transaction = aTransaction;
  605. request->SetError(aErrorCode);
  606. nsCOMPtr<nsIDOMEvent> errorEvent;
  607. if (!aEvent) {
  608. // Make an error event and fire it at the target.
  609. errorEvent = CreateGenericEvent(request,
  610. nsDependentString(kErrorEventType),
  611. eDoesBubble,
  612. eCancelable);
  613. MOZ_ASSERT(errorEvent);
  614. aEvent = errorEvent;
  615. }
  616. Maybe<AutoSetCurrentTransaction> asct;
  617. if (aTransaction) {
  618. asct.emplace(aTransaction);
  619. }
  620. if (transaction) {
  621. IDB_LOG_MARK("IndexedDB %s: Child Transaction[%lld] Request[%llu]: "
  622. "Firing %s event with error 0x%x",
  623. "IndexedDB %s: C T[%lld] R[%llu]: %s (0x%x)",
  624. IDB_LOG_ID_STRING(),
  625. transaction->LoggingSerialNumber(),
  626. request->LoggingSerialNumber(),
  627. IDB_LOG_STRINGIFY(aEvent, kErrorEventType),
  628. aErrorCode);
  629. } else {
  630. IDB_LOG_MARK("IndexedDB %s: Child Request[%llu]: "
  631. "Firing %s event with error 0x%x",
  632. "IndexedDB %s: C R[%llu]: %s (0x%x)",
  633. IDB_LOG_ID_STRING(),
  634. request->LoggingSerialNumber(),
  635. IDB_LOG_STRINGIFY(aEvent, kErrorEventType),
  636. aErrorCode);
  637. }
  638. bool doDefault;
  639. nsresult rv = request->DispatchEvent(aEvent, &doDefault);
  640. if (NS_WARN_IF(NS_FAILED(rv))) {
  641. return;
  642. }
  643. MOZ_ASSERT(!transaction || transaction->IsOpen() || transaction->IsAborted());
  644. // Do not abort the transaction here if this request is failed due to the
  645. // abortion of its transaction to ensure that the correct error cause of
  646. // the abort event be set in IDBTransaction::FireCompleteOrAbortEvents() later.
  647. if (transaction && transaction->IsOpen() &&
  648. aErrorCode != NS_ERROR_DOM_INDEXEDDB_ABORT_ERR) {
  649. WidgetEvent* internalEvent = aEvent->WidgetEventPtr();
  650. MOZ_ASSERT(internalEvent);
  651. if (internalEvent->mFlags.mExceptionWasRaised) {
  652. transaction->Abort(NS_ERROR_DOM_INDEXEDDB_ABORT_ERR);
  653. } else if (doDefault) {
  654. transaction->Abort(request);
  655. }
  656. }
  657. }
  658. void
  659. DispatchSuccessEvent(ResultHelper* aResultHelper,
  660. nsIDOMEvent* aEvent = nullptr)
  661. {
  662. MOZ_ASSERT(aResultHelper);
  663. PROFILER_LABEL("IndexedDB",
  664. "DispatchSuccessEvent",
  665. js::ProfileEntry::Category::STORAGE);
  666. RefPtr<IDBRequest> request = aResultHelper->Request();
  667. MOZ_ASSERT(request);
  668. request->AssertIsOnOwningThread();
  669. RefPtr<IDBTransaction> transaction = aResultHelper->Transaction();
  670. if (transaction && transaction->IsAborted()) {
  671. DispatchErrorEvent(request, transaction->AbortCode(), transaction);
  672. return;
  673. }
  674. nsCOMPtr<nsIDOMEvent> successEvent;
  675. if (!aEvent) {
  676. successEvent = CreateGenericEvent(request,
  677. nsDependentString(kSuccessEventType),
  678. eDoesNotBubble,
  679. eNotCancelable);
  680. MOZ_ASSERT(successEvent);
  681. aEvent = successEvent;
  682. }
  683. request->SetResultCallback(aResultHelper);
  684. MOZ_ASSERT(aEvent);
  685. MOZ_ASSERT_IF(transaction, transaction->IsOpen());
  686. if (transaction) {
  687. IDB_LOG_MARK("IndexedDB %s: Child Transaction[%lld] Request[%llu]: "
  688. "Firing %s event",
  689. "IndexedDB %s: C T[%lld] R[%llu]: %s",
  690. IDB_LOG_ID_STRING(),
  691. transaction->LoggingSerialNumber(),
  692. request->LoggingSerialNumber(),
  693. IDB_LOG_STRINGIFY(aEvent, kSuccessEventType));
  694. } else {
  695. IDB_LOG_MARK("IndexedDB %s: Child Request[%llu]: Firing %s event",
  696. "IndexedDB %s: C R[%llu]: %s",
  697. IDB_LOG_ID_STRING(),
  698. request->LoggingSerialNumber(),
  699. IDB_LOG_STRINGIFY(aEvent, kSuccessEventType));
  700. }
  701. bool dummy;
  702. nsresult rv = request->DispatchEvent(aEvent, &dummy);
  703. if (NS_WARN_IF(NS_FAILED(rv))) {
  704. return;
  705. }
  706. MOZ_ASSERT_IF(transaction,
  707. transaction->IsOpen() || transaction->IsAborted());
  708. WidgetEvent* internalEvent = aEvent->WidgetEventPtr();
  709. MOZ_ASSERT(internalEvent);
  710. if (transaction &&
  711. transaction->IsOpen() &&
  712. internalEvent->mFlags.mExceptionWasRaised) {
  713. transaction->Abort(NS_ERROR_DOM_INDEXEDDB_ABORT_ERR);
  714. }
  715. }
  716. PRFileDesc*
  717. GetFileDescriptorFromStream(nsIInputStream* aStream)
  718. {
  719. MOZ_ASSERT(aStream);
  720. nsCOMPtr<nsIFileMetadata> fileMetadata = do_QueryInterface(aStream);
  721. if (NS_WARN_IF(!fileMetadata)) {
  722. return nullptr;
  723. }
  724. PRFileDesc* fileDesc;
  725. nsresult rv = fileMetadata->GetFileDescriptor(&fileDesc);
  726. if (NS_WARN_IF(NS_FAILED(rv))) {
  727. return nullptr;
  728. }
  729. MOZ_ASSERT(fileDesc);
  730. return fileDesc;
  731. }
  732. class WorkerPermissionChallenge;
  733. // This class calles WorkerPermissionChallenge::OperationCompleted() in the
  734. // worker thread.
  735. class WorkerPermissionOperationCompleted final : public WorkerControlRunnable
  736. {
  737. RefPtr<WorkerPermissionChallenge> mChallenge;
  738. public:
  739. WorkerPermissionOperationCompleted(WorkerPrivate* aWorkerPrivate,
  740. WorkerPermissionChallenge* aChallenge)
  741. : WorkerControlRunnable(aWorkerPrivate, WorkerThreadUnchangedBusyCount)
  742. , mChallenge(aChallenge)
  743. {
  744. MOZ_ASSERT(NS_IsMainThread());
  745. }
  746. virtual bool
  747. WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override;
  748. };
  749. // This class used to do prompting in the main thread and main process.
  750. class WorkerPermissionRequest final : public PermissionRequestBase
  751. {
  752. RefPtr<WorkerPermissionChallenge> mChallenge;
  753. public:
  754. WorkerPermissionRequest(Element* aElement,
  755. nsIPrincipal* aPrincipal,
  756. WorkerPermissionChallenge* aChallenge)
  757. : PermissionRequestBase(aElement, aPrincipal)
  758. , mChallenge(aChallenge)
  759. {
  760. MOZ_ASSERT(XRE_IsParentProcess());
  761. MOZ_ASSERT(NS_IsMainThread());
  762. MOZ_ASSERT(aChallenge);
  763. }
  764. private:
  765. ~WorkerPermissionRequest()
  766. {
  767. MOZ_ASSERT(NS_IsMainThread());
  768. }
  769. virtual void
  770. OnPromptComplete(PermissionValue aPermissionValue) override;
  771. };
  772. // This class is used in the main thread of all child processes.
  773. class WorkerPermissionRequestChildProcessActor final
  774. : public PIndexedDBPermissionRequestChild
  775. {
  776. RefPtr<WorkerPermissionChallenge> mChallenge;
  777. public:
  778. explicit WorkerPermissionRequestChildProcessActor(
  779. WorkerPermissionChallenge* aChallenge)
  780. : mChallenge(aChallenge)
  781. {
  782. MOZ_ASSERT(!XRE_IsParentProcess());
  783. MOZ_ASSERT(NS_IsMainThread());
  784. MOZ_ASSERT(aChallenge);
  785. }
  786. protected:
  787. ~WorkerPermissionRequestChildProcessActor()
  788. {}
  789. virtual bool
  790. Recv__delete__(const uint32_t& aPermission) override;
  791. };
  792. class WorkerPermissionChallenge final : public Runnable
  793. {
  794. public:
  795. WorkerPermissionChallenge(WorkerPrivate* aWorkerPrivate,
  796. BackgroundFactoryRequestChild* aActor,
  797. IDBFactory* aFactory,
  798. const PrincipalInfo& aPrincipalInfo)
  799. : mWorkerPrivate(aWorkerPrivate)
  800. , mActor(aActor)
  801. , mFactory(aFactory)
  802. , mPrincipalInfo(aPrincipalInfo)
  803. {
  804. MOZ_ASSERT(mWorkerPrivate);
  805. MOZ_ASSERT(aActor);
  806. MOZ_ASSERT(aFactory);
  807. mWorkerPrivate->AssertIsOnWorkerThread();
  808. }
  809. bool
  810. Dispatch()
  811. {
  812. mWorkerPrivate->AssertIsOnWorkerThread();
  813. if (NS_WARN_IF(!mWorkerPrivate->ModifyBusyCountFromWorker(true))) {
  814. return false;
  815. }
  816. if (NS_WARN_IF(NS_FAILED(NS_DispatchToMainThread(this)))) {
  817. mWorkerPrivate->ModifyBusyCountFromWorker(false);
  818. return false;
  819. }
  820. return true;
  821. }
  822. NS_IMETHOD
  823. Run() override
  824. {
  825. bool completed = RunInternal();
  826. if (completed) {
  827. OperationCompleted();
  828. }
  829. return NS_OK;
  830. }
  831. void
  832. OperationCompleted()
  833. {
  834. if (NS_IsMainThread()) {
  835. RefPtr<WorkerPermissionOperationCompleted> runnable =
  836. new WorkerPermissionOperationCompleted(mWorkerPrivate, this);
  837. MOZ_ALWAYS_TRUE(runnable->Dispatch());
  838. return;
  839. }
  840. MOZ_ASSERT(mActor);
  841. mActor->AssertIsOnOwningThread();
  842. MaybeCollectGarbageOnIPCMessage();
  843. RefPtr<IDBFactory> factory;
  844. mFactory.swap(factory);
  845. mActor->SendPermissionRetry();
  846. mActor = nullptr;
  847. mWorkerPrivate->AssertIsOnWorkerThread();
  848. mWorkerPrivate->ModifyBusyCountFromWorker(false);
  849. }
  850. private:
  851. bool
  852. RunInternal()
  853. {
  854. MOZ_ASSERT(NS_IsMainThread());
  855. // Walk up to our containing page
  856. WorkerPrivate* wp = mWorkerPrivate;
  857. while (wp->GetParent()) {
  858. wp = wp->GetParent();
  859. }
  860. nsPIDOMWindowInner* window = wp->GetWindow();
  861. if (!window) {
  862. return true;
  863. }
  864. nsresult rv;
  865. nsCOMPtr<nsIPrincipal> principal =
  866. mozilla::ipc::PrincipalInfoToPrincipal(mPrincipalInfo, &rv);
  867. if (NS_WARN_IF(NS_FAILED(rv))) {
  868. return true;
  869. }
  870. if (XRE_IsParentProcess()) {
  871. nsCOMPtr<Element> ownerElement =
  872. do_QueryInterface(window->GetChromeEventHandler());
  873. if (NS_WARN_IF(!ownerElement)) {
  874. return true;
  875. }
  876. RefPtr<WorkerPermissionRequest> helper =
  877. new WorkerPermissionRequest(ownerElement, principal, this);
  878. PermissionRequestBase::PermissionValue permission;
  879. if (NS_WARN_IF(NS_FAILED(helper->PromptIfNeeded(&permission)))) {
  880. return true;
  881. }
  882. MOZ_ASSERT(permission == PermissionRequestBase::kPermissionAllowed ||
  883. permission == PermissionRequestBase::kPermissionDenied ||
  884. permission == PermissionRequestBase::kPermissionPrompt);
  885. return permission != PermissionRequestBase::kPermissionPrompt;
  886. }
  887. TabChild* tabChild = TabChild::GetFrom(window);
  888. MOZ_ASSERT(tabChild);
  889. IPC::Principal ipcPrincipal(principal);
  890. auto* actor = new WorkerPermissionRequestChildProcessActor(this);
  891. tabChild->SendPIndexedDBPermissionRequestConstructor(actor, ipcPrincipal);
  892. return false;
  893. }
  894. private:
  895. WorkerPrivate* mWorkerPrivate;
  896. BackgroundFactoryRequestChild* mActor;
  897. RefPtr<IDBFactory> mFactory;
  898. PrincipalInfo mPrincipalInfo;
  899. };
  900. void
  901. WorkerPermissionRequest::OnPromptComplete(PermissionValue aPermissionValue)
  902. {
  903. MOZ_ASSERT(NS_IsMainThread());
  904. mChallenge->OperationCompleted();
  905. }
  906. bool
  907. WorkerPermissionOperationCompleted::WorkerRun(JSContext* aCx,
  908. WorkerPrivate* aWorkerPrivate)
  909. {
  910. aWorkerPrivate->AssertIsOnWorkerThread();
  911. mChallenge->OperationCompleted();
  912. return true;
  913. }
  914. bool
  915. WorkerPermissionRequestChildProcessActor::Recv__delete__(
  916. const uint32_t& /* aPermission */)
  917. {
  918. MOZ_ASSERT(NS_IsMainThread());
  919. mChallenge->OperationCompleted();
  920. return true;
  921. }
  922. } // namespace
  923. /*******************************************************************************
  924. * Actor class declarations
  925. ******************************************************************************/
  926. // CancelableRunnable is used to make workers happy.
  927. class BackgroundRequestChild::PreprocessHelper final
  928. : public CancelableRunnable
  929. {
  930. typedef std::pair<nsCOMPtr<nsIInputStream>,
  931. nsCOMPtr<nsIInputStream>> StreamPair;
  932. nsCOMPtr<nsIEventTarget> mOwningThread;
  933. nsTArray<StreamPair> mStreamPairs;
  934. nsTArray<RefPtr<JS::WasmModule>> mModuleSet;
  935. BackgroundRequestChild* mActor;
  936. uint32_t mModuleSetIndex;
  937. nsresult mResultCode;
  938. public:
  939. PreprocessHelper(uint32_t aModuleSetIndex, BackgroundRequestChild* aActor)
  940. : mOwningThread(NS_GetCurrentThread())
  941. , mActor(aActor)
  942. , mModuleSetIndex(aModuleSetIndex)
  943. , mResultCode(NS_OK)
  944. {
  945. AssertIsOnOwningThread();
  946. MOZ_ASSERT(aActor);
  947. aActor->AssertIsOnOwningThread();
  948. }
  949. bool
  950. IsOnOwningThread() const
  951. {
  952. MOZ_ASSERT(mOwningThread);
  953. bool current;
  954. return NS_SUCCEEDED(mOwningThread->IsOnCurrentThread(&current)) && current;
  955. }
  956. void
  957. AssertIsOnOwningThread() const
  958. {
  959. MOZ_ASSERT(IsOnOwningThread());
  960. }
  961. void
  962. ClearActor()
  963. {
  964. AssertIsOnOwningThread();
  965. mActor = nullptr;
  966. }
  967. nsresult
  968. Init(const nsTArray<StructuredCloneFile>& aFiles);
  969. nsresult
  970. Dispatch();
  971. private:
  972. ~PreprocessHelper()
  973. { }
  974. void
  975. RunOnOwningThread();
  976. nsresult
  977. RunOnStreamTransportThread();
  978. NS_DECL_NSIRUNNABLE
  979. virtual nsresult
  980. Cancel() override;
  981. };
  982. /*******************************************************************************
  983. * Local class implementations
  984. ******************************************************************************/
  985. void
  986. PermissionRequestMainProcessHelper::OnPromptComplete(
  987. PermissionValue aPermissionValue)
  988. {
  989. MOZ_ASSERT(mActor);
  990. mActor->AssertIsOnOwningThread();
  991. MaybeCollectGarbageOnIPCMessage();
  992. mActor->SendPermissionRetry();
  993. mActor = nullptr;
  994. mFactory = nullptr;
  995. }
  996. bool
  997. PermissionRequestChildProcessActor::Recv__delete__(
  998. const uint32_t& /* aPermission */)
  999. {
  1000. MOZ_ASSERT(mActor);
  1001. mActor->AssertIsOnOwningThread();
  1002. MOZ_ASSERT(mFactory);
  1003. MaybeCollectGarbageOnIPCMessage();
  1004. RefPtr<IDBFactory> factory;
  1005. mFactory.swap(factory);
  1006. mActor->SendPermissionRetry();
  1007. mActor = nullptr;
  1008. return true;
  1009. }
  1010. /*******************************************************************************
  1011. * BackgroundRequestChildBase
  1012. ******************************************************************************/
  1013. BackgroundRequestChildBase::BackgroundRequestChildBase(IDBRequest* aRequest)
  1014. : mRequest(aRequest)
  1015. {
  1016. MOZ_ASSERT(aRequest);
  1017. aRequest->AssertIsOnOwningThread();
  1018. MOZ_COUNT_CTOR(indexedDB::BackgroundRequestChildBase);
  1019. }
  1020. BackgroundRequestChildBase::~BackgroundRequestChildBase()
  1021. {
  1022. AssertIsOnOwningThread();
  1023. MOZ_COUNT_DTOR(indexedDB::BackgroundRequestChildBase);
  1024. }
  1025. #ifdef DEBUG
  1026. void
  1027. BackgroundRequestChildBase::AssertIsOnOwningThread() const
  1028. {
  1029. MOZ_ASSERT(mRequest);
  1030. mRequest->AssertIsOnOwningThread();
  1031. }
  1032. #endif // DEBUG
  1033. /*******************************************************************************
  1034. * BackgroundFactoryChild
  1035. ******************************************************************************/
  1036. BackgroundFactoryChild::BackgroundFactoryChild(IDBFactory* aFactory)
  1037. : mFactory(aFactory)
  1038. #ifdef DEBUG
  1039. , mOwningThread(NS_GetCurrentThread())
  1040. #endif
  1041. {
  1042. AssertIsOnOwningThread();
  1043. MOZ_ASSERT(aFactory);
  1044. aFactory->AssertIsOnOwningThread();
  1045. MOZ_COUNT_CTOR(indexedDB::BackgroundFactoryChild);
  1046. }
  1047. BackgroundFactoryChild::~BackgroundFactoryChild()
  1048. {
  1049. MOZ_COUNT_DTOR(indexedDB::BackgroundFactoryChild);
  1050. }
  1051. #ifdef DEBUG
  1052. void
  1053. BackgroundFactoryChild::AssertIsOnOwningThread() const
  1054. {
  1055. MOZ_ASSERT(mOwningThread);
  1056. bool current;
  1057. MOZ_ASSERT(NS_SUCCEEDED(mOwningThread->IsOnCurrentThread(&current)));
  1058. MOZ_ASSERT(current);
  1059. }
  1060. nsIEventTarget*
  1061. BackgroundFactoryChild::OwningThread() const
  1062. {
  1063. MOZ_ASSERT(mOwningThread);
  1064. return mOwningThread;
  1065. }
  1066. #endif // DEBUG
  1067. void
  1068. BackgroundFactoryChild::SendDeleteMeInternal()
  1069. {
  1070. AssertIsOnOwningThread();
  1071. if (mFactory) {
  1072. mFactory->ClearBackgroundActor();
  1073. mFactory = nullptr;
  1074. MOZ_ALWAYS_TRUE(PBackgroundIDBFactoryChild::SendDeleteMe());
  1075. }
  1076. }
  1077. void
  1078. BackgroundFactoryChild::ActorDestroy(ActorDestroyReason aWhy)
  1079. {
  1080. AssertIsOnOwningThread();
  1081. MaybeCollectGarbageOnIPCMessage();
  1082. if (mFactory) {
  1083. mFactory->ClearBackgroundActor();
  1084. #ifdef DEBUG
  1085. mFactory = nullptr;
  1086. #endif
  1087. }
  1088. }
  1089. PBackgroundIDBFactoryRequestChild*
  1090. BackgroundFactoryChild::AllocPBackgroundIDBFactoryRequestChild(
  1091. const FactoryRequestParams& aParams)
  1092. {
  1093. MOZ_CRASH("PBackgroundIDBFactoryRequestChild actors should be manually "
  1094. "constructed!");
  1095. }
  1096. bool
  1097. BackgroundFactoryChild::DeallocPBackgroundIDBFactoryRequestChild(
  1098. PBackgroundIDBFactoryRequestChild* aActor)
  1099. {
  1100. MOZ_ASSERT(aActor);
  1101. delete static_cast<BackgroundFactoryRequestChild*>(aActor);
  1102. return true;
  1103. }
  1104. PBackgroundIDBDatabaseChild*
  1105. BackgroundFactoryChild::AllocPBackgroundIDBDatabaseChild(
  1106. const DatabaseSpec& aSpec,
  1107. PBackgroundIDBFactoryRequestChild* aRequest)
  1108. {
  1109. AssertIsOnOwningThread();
  1110. auto request = static_cast<BackgroundFactoryRequestChild*>(aRequest);
  1111. MOZ_ASSERT(request);
  1112. return new BackgroundDatabaseChild(aSpec, request);
  1113. }
  1114. bool
  1115. BackgroundFactoryChild::DeallocPBackgroundIDBDatabaseChild(
  1116. PBackgroundIDBDatabaseChild* aActor)
  1117. {
  1118. MOZ_ASSERT(aActor);
  1119. delete static_cast<BackgroundDatabaseChild*>(aActor);
  1120. return true;
  1121. }
  1122. /*******************************************************************************
  1123. * BackgroundFactoryRequestChild
  1124. ******************************************************************************/
  1125. BackgroundFactoryRequestChild::BackgroundFactoryRequestChild(
  1126. IDBFactory* aFactory,
  1127. IDBOpenDBRequest* aOpenRequest,
  1128. bool aIsDeleteOp,
  1129. uint64_t aRequestedVersion)
  1130. : BackgroundRequestChildBase(aOpenRequest)
  1131. , mFactory(aFactory)
  1132. , mRequestedVersion(aRequestedVersion)
  1133. , mIsDeleteOp(aIsDeleteOp)
  1134. {
  1135. // Can't assert owning thread here because IPDL has not yet set our manager!
  1136. MOZ_ASSERT(aFactory);
  1137. aFactory->AssertIsOnOwningThread();
  1138. MOZ_ASSERT(aOpenRequest);
  1139. MOZ_COUNT_CTOR(indexedDB::BackgroundFactoryRequestChild);
  1140. }
  1141. BackgroundFactoryRequestChild::~BackgroundFactoryRequestChild()
  1142. {
  1143. MOZ_COUNT_DTOR(indexedDB::BackgroundFactoryRequestChild);
  1144. }
  1145. IDBOpenDBRequest*
  1146. BackgroundFactoryRequestChild::GetOpenDBRequest() const
  1147. {
  1148. AssertIsOnOwningThread();
  1149. return static_cast<IDBOpenDBRequest*>(mRequest.get());
  1150. }
  1151. bool
  1152. BackgroundFactoryRequestChild::HandleResponse(nsresult aResponse)
  1153. {
  1154. AssertIsOnOwningThread();
  1155. MOZ_ASSERT(NS_FAILED(aResponse));
  1156. MOZ_ASSERT(NS_ERROR_GET_MODULE(aResponse) == NS_ERROR_MODULE_DOM_INDEXEDDB);
  1157. mRequest->Reset();
  1158. DispatchErrorEvent(mRequest, aResponse);
  1159. return true;
  1160. }
  1161. bool
  1162. BackgroundFactoryRequestChild::HandleResponse(
  1163. const OpenDatabaseRequestResponse& aResponse)
  1164. {
  1165. AssertIsOnOwningThread();
  1166. mRequest->Reset();
  1167. auto databaseActor =
  1168. static_cast<BackgroundDatabaseChild*>(aResponse.databaseChild());
  1169. MOZ_ASSERT(databaseActor);
  1170. IDBDatabase* database = databaseActor->GetDOMObject();
  1171. if (!database) {
  1172. databaseActor->EnsureDOMObject();
  1173. database = databaseActor->GetDOMObject();
  1174. MOZ_ASSERT(database);
  1175. MOZ_ASSERT(!database->IsClosed());
  1176. }
  1177. if (database->IsClosed()) {
  1178. // If the database was closed already, which is only possible if we fired an
  1179. // "upgradeneeded" event, then we shouldn't fire a "success" event here.
  1180. // Instead we fire an error event with AbortErr.
  1181. DispatchErrorEvent(mRequest, NS_ERROR_DOM_INDEXEDDB_ABORT_ERR);
  1182. } else {
  1183. ResultHelper helper(mRequest, nullptr, database);
  1184. DispatchSuccessEvent(&helper);
  1185. }
  1186. databaseActor->ReleaseDOMObject();
  1187. return true;
  1188. }
  1189. bool
  1190. BackgroundFactoryRequestChild::HandleResponse(
  1191. const DeleteDatabaseRequestResponse& aResponse)
  1192. {
  1193. AssertIsOnOwningThread();
  1194. ResultHelper helper(mRequest, nullptr, &JS::UndefinedHandleValue);
  1195. nsCOMPtr<nsIDOMEvent> successEvent =
  1196. IDBVersionChangeEvent::Create(mRequest,
  1197. nsDependentString(kSuccessEventType),
  1198. aResponse.previousVersion());
  1199. MOZ_ASSERT(successEvent);
  1200. DispatchSuccessEvent(&helper, successEvent);
  1201. return true;
  1202. }
  1203. void
  1204. BackgroundFactoryRequestChild::ActorDestroy(ActorDestroyReason aWhy)
  1205. {
  1206. AssertIsOnOwningThread();
  1207. MaybeCollectGarbageOnIPCMessage();
  1208. if (aWhy != Deletion) {
  1209. IDBOpenDBRequest* openRequest = GetOpenDBRequest();
  1210. if (openRequest) {
  1211. openRequest->NoteComplete();
  1212. }
  1213. }
  1214. }
  1215. bool
  1216. BackgroundFactoryRequestChild::Recv__delete__(
  1217. const FactoryRequestResponse& aResponse)
  1218. {
  1219. AssertIsOnOwningThread();
  1220. MOZ_ASSERT(mRequest);
  1221. MaybeCollectGarbageOnIPCMessage();
  1222. bool result;
  1223. switch (aResponse.type()) {
  1224. case FactoryRequestResponse::Tnsresult:
  1225. result = HandleResponse(aResponse.get_nsresult());
  1226. break;
  1227. case FactoryRequestResponse::TOpenDatabaseRequestResponse:
  1228. result = HandleResponse(aResponse.get_OpenDatabaseRequestResponse());
  1229. break;
  1230. case FactoryRequestResponse::TDeleteDatabaseRequestResponse:
  1231. result = HandleResponse(aResponse.get_DeleteDatabaseRequestResponse());
  1232. break;
  1233. default:
  1234. MOZ_CRASH("Unknown response type!");
  1235. }
  1236. IDBOpenDBRequest* request = GetOpenDBRequest();
  1237. MOZ_ASSERT(request);
  1238. request->NoteComplete();
  1239. if (NS_WARN_IF(!result)) {
  1240. return false;
  1241. }
  1242. return true;
  1243. }
  1244. bool
  1245. BackgroundFactoryRequestChild::RecvPermissionChallenge(
  1246. const PrincipalInfo& aPrincipalInfo)
  1247. {
  1248. AssertIsOnOwningThread();
  1249. MaybeCollectGarbageOnIPCMessage();
  1250. if (!NS_IsMainThread()) {
  1251. WorkerPrivate* workerPrivate = GetCurrentThreadWorkerPrivate();
  1252. MOZ_ASSERT(workerPrivate);
  1253. workerPrivate->AssertIsOnWorkerThread();
  1254. RefPtr<WorkerPermissionChallenge> challenge =
  1255. new WorkerPermissionChallenge(workerPrivate, this, mFactory,
  1256. aPrincipalInfo);
  1257. return challenge->Dispatch();
  1258. }
  1259. nsresult rv;
  1260. nsCOMPtr<nsIPrincipal> principal =
  1261. mozilla::ipc::PrincipalInfoToPrincipal(aPrincipalInfo, &rv);
  1262. if (NS_WARN_IF(NS_FAILED(rv))) {
  1263. return false;
  1264. }
  1265. if (XRE_IsParentProcess()) {
  1266. nsCOMPtr<nsPIDOMWindowInner> window = mFactory->GetParentObject();
  1267. MOZ_ASSERT(window);
  1268. nsCOMPtr<Element> ownerElement =
  1269. do_QueryInterface(window->GetChromeEventHandler());
  1270. if (NS_WARN_IF(!ownerElement)) {
  1271. // If this fails, the page was navigated. Fail the permission check by
  1272. // forcing an immediate retry.
  1273. return SendPermissionRetry();
  1274. }
  1275. RefPtr<PermissionRequestMainProcessHelper> helper =
  1276. new PermissionRequestMainProcessHelper(this, mFactory, ownerElement, principal);
  1277. PermissionRequestBase::PermissionValue permission;
  1278. if (NS_WARN_IF(NS_FAILED(helper->PromptIfNeeded(&permission)))) {
  1279. return false;
  1280. }
  1281. MOZ_ASSERT(permission == PermissionRequestBase::kPermissionAllowed ||
  1282. permission == PermissionRequestBase::kPermissionDenied ||
  1283. permission == PermissionRequestBase::kPermissionPrompt);
  1284. if (permission != PermissionRequestBase::kPermissionPrompt) {
  1285. SendPermissionRetry();
  1286. }
  1287. return true;
  1288. }
  1289. RefPtr<TabChild> tabChild = mFactory->GetTabChild();
  1290. MOZ_ASSERT(tabChild);
  1291. IPC::Principal ipcPrincipal(principal);
  1292. auto* actor = new PermissionRequestChildProcessActor(this, mFactory);
  1293. tabChild->SendPIndexedDBPermissionRequestConstructor(actor, ipcPrincipal);
  1294. return true;
  1295. }
  1296. bool
  1297. BackgroundFactoryRequestChild::RecvBlocked(const uint64_t& aCurrentVersion)
  1298. {
  1299. AssertIsOnOwningThread();
  1300. MOZ_ASSERT(mRequest);
  1301. MaybeCollectGarbageOnIPCMessage();
  1302. const nsDependentString type(kBlockedEventType);
  1303. nsCOMPtr<nsIDOMEvent> blockedEvent;
  1304. if (mIsDeleteOp) {
  1305. blockedEvent =
  1306. IDBVersionChangeEvent::Create(mRequest, type, aCurrentVersion);
  1307. MOZ_ASSERT(blockedEvent);
  1308. } else {
  1309. blockedEvent =
  1310. IDBVersionChangeEvent::Create(mRequest,
  1311. type,
  1312. aCurrentVersion,
  1313. mRequestedVersion);
  1314. MOZ_ASSERT(blockedEvent);
  1315. }
  1316. RefPtr<IDBRequest> kungFuDeathGrip = mRequest;
  1317. IDB_LOG_MARK("IndexedDB %s: Child Request[%llu]: Firing \"blocked\" event",
  1318. "IndexedDB %s: C R[%llu]: \"blocked\"",
  1319. IDB_LOG_ID_STRING(),
  1320. kungFuDeathGrip->LoggingSerialNumber());
  1321. bool dummy;
  1322. if (NS_FAILED(kungFuDeathGrip->DispatchEvent(blockedEvent, &dummy))) {
  1323. NS_WARNING("Failed to dispatch event!");
  1324. }
  1325. return true;
  1326. }
  1327. /*******************************************************************************
  1328. * BackgroundDatabaseChild
  1329. ******************************************************************************/
  1330. BackgroundDatabaseChild::BackgroundDatabaseChild(
  1331. const DatabaseSpec& aSpec,
  1332. BackgroundFactoryRequestChild* aOpenRequestActor)
  1333. : mSpec(new DatabaseSpec(aSpec))
  1334. , mOpenRequestActor(aOpenRequestActor)
  1335. , mDatabase(nullptr)
  1336. {
  1337. // Can't assert owning thread here because IPDL has not yet set our manager!
  1338. MOZ_ASSERT(aOpenRequestActor);
  1339. MOZ_COUNT_CTOR(indexedDB::BackgroundDatabaseChild);
  1340. }
  1341. BackgroundDatabaseChild::~BackgroundDatabaseChild()
  1342. {
  1343. MOZ_COUNT_DTOR(indexedDB::BackgroundDatabaseChild);
  1344. }
  1345. void
  1346. BackgroundDatabaseChild::SendDeleteMeInternal()
  1347. {
  1348. AssertIsOnOwningThread();
  1349. MOZ_ASSERT(!mTemporaryStrongDatabase);
  1350. MOZ_ASSERT(!mOpenRequestActor);
  1351. if (mDatabase) {
  1352. mDatabase->ClearBackgroundActor();
  1353. mDatabase = nullptr;
  1354. MOZ_ALWAYS_TRUE(PBackgroundIDBDatabaseChild::SendDeleteMe());
  1355. }
  1356. }
  1357. void
  1358. BackgroundDatabaseChild::EnsureDOMObject()
  1359. {
  1360. AssertIsOnOwningThread();
  1361. MOZ_ASSERT(mOpenRequestActor);
  1362. if (mTemporaryStrongDatabase) {
  1363. MOZ_ASSERT(!mSpec);
  1364. return;
  1365. }
  1366. MOZ_ASSERT(mSpec);
  1367. auto request = mOpenRequestActor->GetOpenDBRequest();
  1368. MOZ_ASSERT(request);
  1369. auto factory =
  1370. static_cast<BackgroundFactoryChild*>(Manager())->GetDOMObject();
  1371. MOZ_ASSERT(factory);
  1372. mTemporaryStrongDatabase =
  1373. IDBDatabase::Create(request, factory, this, mSpec);
  1374. MOZ_ASSERT(mTemporaryStrongDatabase);
  1375. mTemporaryStrongDatabase->AssertIsOnOwningThread();
  1376. mDatabase = mTemporaryStrongDatabase;
  1377. mSpec.forget();
  1378. }
  1379. void
  1380. BackgroundDatabaseChild::ReleaseDOMObject()
  1381. {
  1382. AssertIsOnOwningThread();
  1383. MOZ_ASSERT(mTemporaryStrongDatabase);
  1384. mTemporaryStrongDatabase->AssertIsOnOwningThread();
  1385. MOZ_ASSERT(mOpenRequestActor);
  1386. MOZ_ASSERT(mDatabase == mTemporaryStrongDatabase);
  1387. mOpenRequestActor = nullptr;
  1388. // This may be the final reference to the IDBDatabase object so we may end up
  1389. // calling SendDeleteMeInternal() here. Make sure everything is cleaned up
  1390. // properly before proceeding.
  1391. mTemporaryStrongDatabase = nullptr;
  1392. }
  1393. void
  1394. BackgroundDatabaseChild::ActorDestroy(ActorDestroyReason aWhy)
  1395. {
  1396. AssertIsOnOwningThread();
  1397. MaybeCollectGarbageOnIPCMessage();
  1398. if (mDatabase) {
  1399. mDatabase->ClearBackgroundActor();
  1400. #ifdef DEBUG
  1401. mDatabase = nullptr;
  1402. #endif
  1403. }
  1404. }
  1405. PBackgroundIDBDatabaseFileChild*
  1406. BackgroundDatabaseChild::AllocPBackgroundIDBDatabaseFileChild(
  1407. PBlobChild* aBlobChild)
  1408. {
  1409. MOZ_CRASH("PBackgroundIDBFileChild actors should be manually constructed!");
  1410. }
  1411. bool
  1412. BackgroundDatabaseChild::DeallocPBackgroundIDBDatabaseFileChild(
  1413. PBackgroundIDBDatabaseFileChild* aActor)
  1414. {
  1415. AssertIsOnOwningThread();
  1416. MOZ_ASSERT(aActor);
  1417. delete aActor;
  1418. return true;
  1419. }
  1420. PBackgroundIDBDatabaseRequestChild*
  1421. BackgroundDatabaseChild::AllocPBackgroundIDBDatabaseRequestChild(
  1422. const DatabaseRequestParams& aParams)
  1423. {
  1424. MOZ_CRASH("PBackgroundIDBDatabaseRequestChild actors should be manually "
  1425. "constructed!");
  1426. }
  1427. bool
  1428. BackgroundDatabaseChild::DeallocPBackgroundIDBDatabaseRequestChild(
  1429. PBackgroundIDBDatabaseRequestChild* aActor)
  1430. {
  1431. MOZ_ASSERT(aActor);
  1432. delete static_cast<BackgroundDatabaseRequestChild*>(aActor);
  1433. return true;
  1434. }
  1435. PBackgroundIDBTransactionChild*
  1436. BackgroundDatabaseChild::AllocPBackgroundIDBTransactionChild(
  1437. const nsTArray<nsString>& aObjectStoreNames,
  1438. const Mode& aMode)
  1439. {
  1440. MOZ_CRASH("PBackgroundIDBTransactionChild actors should be manually "
  1441. "constructed!");
  1442. }
  1443. bool
  1444. BackgroundDatabaseChild::DeallocPBackgroundIDBTransactionChild(
  1445. PBackgroundIDBTransactionChild* aActor)
  1446. {
  1447. MOZ_ASSERT(aActor);
  1448. delete static_cast<BackgroundTransactionChild*>(aActor);
  1449. return true;
  1450. }
  1451. PBackgroundIDBVersionChangeTransactionChild*
  1452. BackgroundDatabaseChild::AllocPBackgroundIDBVersionChangeTransactionChild(
  1453. const uint64_t& aCurrentVersion,
  1454. const uint64_t& aRequestedVersion,
  1455. const int64_t& aNextObjectStoreId,
  1456. const int64_t& aNextIndexId)
  1457. {
  1458. AssertIsOnOwningThread();
  1459. IDBOpenDBRequest* request = mOpenRequestActor->GetOpenDBRequest();
  1460. MOZ_ASSERT(request);
  1461. return new BackgroundVersionChangeTransactionChild(request);
  1462. }
  1463. bool
  1464. BackgroundDatabaseChild::RecvPBackgroundIDBVersionChangeTransactionConstructor(
  1465. PBackgroundIDBVersionChangeTransactionChild* aActor,
  1466. const uint64_t& aCurrentVersion,
  1467. const uint64_t& aRequestedVersion,
  1468. const int64_t& aNextObjectStoreId,
  1469. const int64_t& aNextIndexId)
  1470. {
  1471. AssertIsOnOwningThread();
  1472. MOZ_ASSERT(aActor);
  1473. MOZ_ASSERT(mOpenRequestActor);
  1474. MaybeCollectGarbageOnIPCMessage();
  1475. EnsureDOMObject();
  1476. auto* actor = static_cast<BackgroundVersionChangeTransactionChild*>(aActor);
  1477. RefPtr<IDBOpenDBRequest> request = mOpenRequestActor->GetOpenDBRequest();
  1478. MOZ_ASSERT(request);
  1479. RefPtr<IDBTransaction> transaction =
  1480. IDBTransaction::CreateVersionChange(mDatabase,
  1481. actor,
  1482. request,
  1483. aNextObjectStoreId,
  1484. aNextIndexId);
  1485. if (NS_WARN_IF(!transaction)) {
  1486. // This can happen if we receive events after a worker has begun its
  1487. // shutdown process.
  1488. MOZ_ASSERT(!NS_IsMainThread());
  1489. // Report this to the console.
  1490. IDB_REPORT_INTERNAL_ERR();
  1491. MOZ_ALWAYS_TRUE(aActor->SendDeleteMe());
  1492. return true;
  1493. }
  1494. transaction->AssertIsOnOwningThread();
  1495. actor->SetDOMTransaction(transaction);
  1496. mDatabase->EnterSetVersionTransaction(aRequestedVersion);
  1497. request->SetTransaction(transaction);
  1498. nsCOMPtr<nsIDOMEvent> upgradeNeededEvent =
  1499. IDBVersionChangeEvent::Create(request,
  1500. nsDependentString(kUpgradeNeededEventType),
  1501. aCurrentVersion,
  1502. aRequestedVersion);
  1503. MOZ_ASSERT(upgradeNeededEvent);
  1504. ResultHelper helper(request, transaction, mDatabase);
  1505. DispatchSuccessEvent(&helper, upgradeNeededEvent);
  1506. return true;
  1507. }
  1508. bool
  1509. BackgroundDatabaseChild::DeallocPBackgroundIDBVersionChangeTransactionChild(
  1510. PBackgroundIDBVersionChangeTransactionChild* aActor)
  1511. {
  1512. MOZ_ASSERT(aActor);
  1513. delete static_cast<BackgroundVersionChangeTransactionChild*>(aActor);
  1514. return true;
  1515. }
  1516. PBackgroundMutableFileChild*
  1517. BackgroundDatabaseChild::AllocPBackgroundMutableFileChild(const nsString& aName,
  1518. const nsString& aType)
  1519. {
  1520. AssertIsOnOwningThread();
  1521. #ifdef DEBUG
  1522. nsCOMPtr<nsIThread> owningThread = do_QueryInterface(OwningThread());
  1523. PRThread* owningPRThread;
  1524. owningThread->GetPRThread(&owningPRThread);
  1525. #endif
  1526. return new BackgroundMutableFileChild(DEBUGONLY(owningPRThread,)
  1527. aName,
  1528. aType);
  1529. }
  1530. bool
  1531. BackgroundDatabaseChild::DeallocPBackgroundMutableFileChild(
  1532. PBackgroundMutableFileChild* aActor)
  1533. {
  1534. MOZ_ASSERT(aActor);
  1535. delete static_cast<BackgroundMutableFileChild*>(aActor);
  1536. return true;
  1537. }
  1538. bool
  1539. BackgroundDatabaseChild::RecvVersionChange(const uint64_t& aOldVersion,
  1540. const NullableVersion& aNewVersion)
  1541. {
  1542. AssertIsOnOwningThread();
  1543. MaybeCollectGarbageOnIPCMessage();
  1544. if (!mDatabase || mDatabase->IsClosed()) {
  1545. return true;
  1546. }
  1547. RefPtr<IDBDatabase> kungFuDeathGrip = mDatabase;
  1548. // Handle bfcache'd windows.
  1549. if (nsPIDOMWindowInner* owner = kungFuDeathGrip->GetOwner()) {
  1550. // The database must be closed if the window is already frozen.
  1551. bool shouldAbortAndClose = owner->IsFrozen();
  1552. // Anything in the bfcache has to be evicted and then we have to close the
  1553. // database also.
  1554. if (nsCOMPtr<nsIDocument> doc = owner->GetExtantDoc()) {
  1555. if (nsCOMPtr<nsIBFCacheEntry> bfCacheEntry = doc->GetBFCacheEntry()) {
  1556. bfCacheEntry->RemoveFromBFCacheSync();
  1557. shouldAbortAndClose = true;
  1558. }
  1559. }
  1560. if (shouldAbortAndClose) {
  1561. // Invalidate() doesn't close the database in the parent, so we have
  1562. // to call Close() and AbortTransactions() manually.
  1563. kungFuDeathGrip->AbortTransactions(/* aShouldWarn */ false);
  1564. kungFuDeathGrip->Close();
  1565. return true;
  1566. }
  1567. }
  1568. // Otherwise fire a versionchange event.
  1569. const nsDependentString type(kVersionChangeEventType);
  1570. nsCOMPtr<nsIDOMEvent> versionChangeEvent;
  1571. switch (aNewVersion.type()) {
  1572. case NullableVersion::Tnull_t:
  1573. versionChangeEvent =
  1574. IDBVersionChangeEvent::Create(kungFuDeathGrip, type, aOldVersion);
  1575. MOZ_ASSERT(versionChangeEvent);
  1576. break;
  1577. case NullableVersion::Tuint64_t:
  1578. versionChangeEvent =
  1579. IDBVersionChangeEvent::Create(kungFuDeathGrip,
  1580. type,
  1581. aOldVersion,
  1582. aNewVersion.get_uint64_t());
  1583. MOZ_ASSERT(versionChangeEvent);
  1584. break;
  1585. default:
  1586. MOZ_CRASH("Should never get here!");
  1587. }
  1588. IDB_LOG_MARK("IndexedDB %s: Child : Firing \"versionchange\" event",
  1589. "IndexedDB %s: C: IDBDatabase \"versionchange\" event",
  1590. IDB_LOG_ID_STRING());
  1591. bool dummy;
  1592. if (NS_FAILED(kungFuDeathGrip->DispatchEvent(versionChangeEvent, &dummy))) {
  1593. NS_WARNING("Failed to dispatch event!");
  1594. }
  1595. if (!kungFuDeathGrip->IsClosed()) {
  1596. SendBlocked();
  1597. }
  1598. return true;
  1599. }
  1600. bool
  1601. BackgroundDatabaseChild::RecvInvalidate()
  1602. {
  1603. AssertIsOnOwningThread();
  1604. MaybeCollectGarbageOnIPCMessage();
  1605. if (mDatabase) {
  1606. mDatabase->Invalidate();
  1607. }
  1608. return true;
  1609. }
  1610. bool
  1611. BackgroundDatabaseChild::RecvCloseAfterInvalidationComplete()
  1612. {
  1613. AssertIsOnOwningThread();
  1614. MaybeCollectGarbageOnIPCMessage();
  1615. if (mDatabase) {
  1616. mDatabase->DispatchTrustedEvent(nsDependentString(kCloseEventType));
  1617. }
  1618. return true;
  1619. }
  1620. /*******************************************************************************
  1621. * BackgroundDatabaseRequestChild
  1622. ******************************************************************************/
  1623. BackgroundDatabaseRequestChild::BackgroundDatabaseRequestChild(
  1624. IDBDatabase* aDatabase,
  1625. IDBRequest* aRequest)
  1626. : BackgroundRequestChildBase(aRequest)
  1627. , mDatabase(aDatabase)
  1628. {
  1629. // Can't assert owning thread here because IPDL has not yet set our manager!
  1630. MOZ_ASSERT(aDatabase);
  1631. aDatabase->AssertIsOnOwningThread();
  1632. MOZ_ASSERT(aRequest);
  1633. MOZ_COUNT_CTOR(indexedDB::BackgroundDatabaseRequestChild);
  1634. }
  1635. BackgroundDatabaseRequestChild::~BackgroundDatabaseRequestChild()
  1636. {
  1637. MOZ_COUNT_DTOR(indexedDB::BackgroundDatabaseRequestChild);
  1638. }
  1639. bool
  1640. BackgroundDatabaseRequestChild::HandleResponse(nsresult aResponse)
  1641. {
  1642. AssertIsOnOwningThread();
  1643. MOZ_ASSERT(NS_FAILED(aResponse));
  1644. MOZ_ASSERT(NS_ERROR_GET_MODULE(aResponse) == NS_ERROR_MODULE_DOM_INDEXEDDB);
  1645. mRequest->Reset();
  1646. DispatchErrorEvent(mRequest, aResponse);
  1647. return true;
  1648. }
  1649. bool
  1650. BackgroundDatabaseRequestChild::HandleResponse(
  1651. const CreateFileRequestResponse& aResponse)
  1652. {
  1653. AssertIsOnOwningThread();
  1654. mRequest->Reset();
  1655. auto mutableFileActor =
  1656. static_cast<BackgroundMutableFileChild*>(aResponse.mutableFileChild());
  1657. MOZ_ASSERT(mutableFileActor);
  1658. mutableFileActor->EnsureDOMObject();
  1659. auto mutableFile =
  1660. static_cast<IDBMutableFile*>(mutableFileActor->GetDOMObject());
  1661. MOZ_ASSERT(mutableFile);
  1662. ResultHelper helper(mRequest, nullptr, mutableFile);
  1663. DispatchSuccessEvent(&helper);
  1664. mutableFileActor->ReleaseDOMObject();
  1665. return true;
  1666. }
  1667. bool
  1668. BackgroundDatabaseRequestChild::Recv__delete__(
  1669. const DatabaseRequestResponse& aResponse)
  1670. {
  1671. AssertIsOnOwningThread();
  1672. MOZ_ASSERT(mRequest);
  1673. switch (aResponse.type()) {
  1674. case DatabaseRequestResponse::Tnsresult:
  1675. return HandleResponse(aResponse.get_nsresult());
  1676. case DatabaseRequestResponse::TCreateFileRequestResponse:
  1677. return HandleResponse(aResponse.get_CreateFileRequestResponse());
  1678. default:
  1679. MOZ_CRASH("Unknown response type!");
  1680. }
  1681. MOZ_CRASH("Should never get here!");
  1682. }
  1683. /*******************************************************************************
  1684. * BackgroundTransactionBase
  1685. ******************************************************************************/
  1686. BackgroundTransactionBase::BackgroundTransactionBase()
  1687. : mTransaction(nullptr)
  1688. {
  1689. MOZ_COUNT_CTOR(indexedDB::BackgroundTransactionBase);
  1690. }
  1691. BackgroundTransactionBase::BackgroundTransactionBase(
  1692. IDBTransaction* aTransaction)
  1693. : mTemporaryStrongTransaction(aTransaction)
  1694. , mTransaction(aTransaction)
  1695. {
  1696. MOZ_ASSERT(aTransaction);
  1697. aTransaction->AssertIsOnOwningThread();
  1698. MOZ_COUNT_CTOR(indexedDB::BackgroundTransactionBase);
  1699. }
  1700. BackgroundTransactionBase::~BackgroundTransactionBase()
  1701. {
  1702. MOZ_COUNT_DTOR(indexedDB::BackgroundTransactionBase);
  1703. }
  1704. #ifdef DEBUG
  1705. void
  1706. BackgroundTransactionBase::AssertIsOnOwningThread() const
  1707. {
  1708. MOZ_ASSERT(mTransaction);
  1709. mTransaction->AssertIsOnOwningThread();
  1710. }
  1711. #endif // DEBUG
  1712. void
  1713. BackgroundTransactionBase::NoteActorDestroyed()
  1714. {
  1715. AssertIsOnOwningThread();
  1716. MOZ_ASSERT_IF(mTemporaryStrongTransaction, mTransaction);
  1717. if (mTransaction) {
  1718. mTransaction->ClearBackgroundActor();
  1719. // Normally this would be DEBUG-only but NoteActorDestroyed is also called
  1720. // from SendDeleteMeInternal. In that case we're going to receive an actual
  1721. // ActorDestroy call later and we don't want to touch a dead object.
  1722. mTemporaryStrongTransaction = nullptr;
  1723. mTransaction = nullptr;
  1724. }
  1725. }
  1726. void
  1727. BackgroundTransactionBase::SetDOMTransaction(IDBTransaction* aTransaction)
  1728. {
  1729. AssertIsOnOwningThread();
  1730. MOZ_ASSERT(aTransaction);
  1731. aTransaction->AssertIsOnOwningThread();
  1732. MOZ_ASSERT(!mTemporaryStrongTransaction);
  1733. MOZ_ASSERT(!mTransaction);
  1734. mTemporaryStrongTransaction = aTransaction;
  1735. mTransaction = aTransaction;
  1736. }
  1737. void
  1738. BackgroundTransactionBase::NoteComplete()
  1739. {
  1740. AssertIsOnOwningThread();
  1741. MOZ_ASSERT_IF(mTransaction, mTemporaryStrongTransaction);
  1742. mTemporaryStrongTransaction = nullptr;
  1743. }
  1744. /*******************************************************************************
  1745. * BackgroundTransactionChild
  1746. ******************************************************************************/
  1747. BackgroundTransactionChild::BackgroundTransactionChild(
  1748. IDBTransaction* aTransaction)
  1749. : BackgroundTransactionBase(aTransaction)
  1750. {
  1751. MOZ_ASSERT(aTransaction);
  1752. aTransaction->AssertIsOnOwningThread();
  1753. MOZ_COUNT_CTOR(indexedDB::BackgroundTransactionChild);
  1754. }
  1755. BackgroundTransactionChild::~BackgroundTransactionChild()
  1756. {
  1757. MOZ_COUNT_DTOR(indexedDB::BackgroundTransactionChild);
  1758. }
  1759. #ifdef DEBUG
  1760. void
  1761. BackgroundTransactionChild::AssertIsOnOwningThread() const
  1762. {
  1763. static_cast<BackgroundDatabaseChild*>(Manager())->AssertIsOnOwningThread();
  1764. }
  1765. #endif // DEBUG
  1766. void
  1767. BackgroundTransactionChild::SendDeleteMeInternal()
  1768. {
  1769. AssertIsOnOwningThread();
  1770. if (mTransaction) {
  1771. NoteActorDestroyed();
  1772. MOZ_ALWAYS_TRUE(PBackgroundIDBTransactionChild::SendDeleteMe());
  1773. }
  1774. }
  1775. void
  1776. BackgroundTransactionChild::ActorDestroy(ActorDestroyReason aWhy)
  1777. {
  1778. AssertIsOnOwningThread();
  1779. MaybeCollectGarbageOnIPCMessage();
  1780. NoteActorDestroyed();
  1781. }
  1782. bool
  1783. BackgroundTransactionChild::RecvComplete(const nsresult& aResult)
  1784. {
  1785. AssertIsOnOwningThread();
  1786. MOZ_ASSERT(mTransaction);
  1787. MaybeCollectGarbageOnIPCMessage();
  1788. mTransaction->FireCompleteOrAbortEvents(aResult);
  1789. NoteComplete();
  1790. return true;
  1791. }
  1792. PBackgroundIDBRequestChild*
  1793. BackgroundTransactionChild::AllocPBackgroundIDBRequestChild(
  1794. const RequestParams& aParams)
  1795. {
  1796. MOZ_CRASH("PBackgroundIDBRequestChild actors should be manually "
  1797. "constructed!");
  1798. }
  1799. bool
  1800. BackgroundTransactionChild::DeallocPBackgroundIDBRequestChild(
  1801. PBackgroundIDBRequestChild* aActor)
  1802. {
  1803. MOZ_ASSERT(aActor);
  1804. delete static_cast<BackgroundRequestChild*>(aActor);
  1805. return true;
  1806. }
  1807. PBackgroundIDBCursorChild*
  1808. BackgroundTransactionChild::AllocPBackgroundIDBCursorChild(
  1809. const OpenCursorParams& aParams)
  1810. {
  1811. AssertIsOnOwningThread();
  1812. MOZ_CRASH("PBackgroundIDBCursorChild actors should be manually constructed!");
  1813. }
  1814. bool
  1815. BackgroundTransactionChild::DeallocPBackgroundIDBCursorChild(
  1816. PBackgroundIDBCursorChild* aActor)
  1817. {
  1818. MOZ_ASSERT(aActor);
  1819. delete static_cast<BackgroundCursorChild*>(aActor);
  1820. return true;
  1821. }
  1822. /*******************************************************************************
  1823. * BackgroundVersionChangeTransactionChild
  1824. ******************************************************************************/
  1825. BackgroundVersionChangeTransactionChild::
  1826. BackgroundVersionChangeTransactionChild(IDBOpenDBRequest* aOpenDBRequest)
  1827. : mOpenDBRequest(aOpenDBRequest)
  1828. {
  1829. MOZ_ASSERT(aOpenDBRequest);
  1830. aOpenDBRequest->AssertIsOnOwningThread();
  1831. MOZ_COUNT_CTOR(indexedDB::BackgroundVersionChangeTransactionChild);
  1832. }
  1833. BackgroundVersionChangeTransactionChild::
  1834. ~BackgroundVersionChangeTransactionChild()
  1835. {
  1836. AssertIsOnOwningThread();
  1837. MOZ_COUNT_DTOR(indexedDB::BackgroundVersionChangeTransactionChild);
  1838. }
  1839. #ifdef DEBUG
  1840. void
  1841. BackgroundVersionChangeTransactionChild::AssertIsOnOwningThread() const
  1842. {
  1843. static_cast<BackgroundDatabaseChild*>(Manager())->AssertIsOnOwningThread();
  1844. }
  1845. #endif // DEBUG
  1846. void
  1847. BackgroundVersionChangeTransactionChild::SendDeleteMeInternal(
  1848. bool aFailedConstructor)
  1849. {
  1850. AssertIsOnOwningThread();
  1851. if (mTransaction || aFailedConstructor) {
  1852. NoteActorDestroyed();
  1853. MOZ_ALWAYS_TRUE(PBackgroundIDBVersionChangeTransactionChild::
  1854. SendDeleteMe());
  1855. }
  1856. }
  1857. void
  1858. BackgroundVersionChangeTransactionChild::ActorDestroy(ActorDestroyReason aWhy)
  1859. {
  1860. AssertIsOnOwningThread();
  1861. MaybeCollectGarbageOnIPCMessage();
  1862. mOpenDBRequest = nullptr;
  1863. NoteActorDestroyed();
  1864. }
  1865. bool
  1866. BackgroundVersionChangeTransactionChild::RecvComplete(const nsresult& aResult)
  1867. {
  1868. AssertIsOnOwningThread();
  1869. MaybeCollectGarbageOnIPCMessage();
  1870. if (!mTransaction) {
  1871. return true;
  1872. }
  1873. MOZ_ASSERT(mOpenDBRequest);
  1874. IDBDatabase* database = mTransaction->Database();
  1875. MOZ_ASSERT(database);
  1876. database->ExitSetVersionTransaction();
  1877. if (NS_FAILED(aResult)) {
  1878. database->Close();
  1879. }
  1880. RefPtr<IDBOpenDBRequest> request = mOpenDBRequest;
  1881. MOZ_ASSERT(request);
  1882. mTransaction->FireCompleteOrAbortEvents(aResult);
  1883. request->SetTransaction(nullptr);
  1884. request = nullptr;
  1885. mOpenDBRequest = nullptr;
  1886. NoteComplete();
  1887. return true;
  1888. }
  1889. PBackgroundIDBRequestChild*
  1890. BackgroundVersionChangeTransactionChild::AllocPBackgroundIDBRequestChild(
  1891. const RequestParams& aParams)
  1892. {
  1893. MOZ_CRASH("PBackgroundIDBRequestChild actors should be manually "
  1894. "constructed!");
  1895. }
  1896. bool
  1897. BackgroundVersionChangeTransactionChild::DeallocPBackgroundIDBRequestChild(
  1898. PBackgroundIDBRequestChild* aActor)
  1899. {
  1900. MOZ_ASSERT(aActor);
  1901. delete static_cast<BackgroundRequestChild*>(aActor);
  1902. return true;
  1903. }
  1904. PBackgroundIDBCursorChild*
  1905. BackgroundVersionChangeTransactionChild::AllocPBackgroundIDBCursorChild(
  1906. const OpenCursorParams& aParams)
  1907. {
  1908. AssertIsOnOwningThread();
  1909. MOZ_CRASH("PBackgroundIDBCursorChild actors should be manually constructed!");
  1910. }
  1911. bool
  1912. BackgroundVersionChangeTransactionChild::DeallocPBackgroundIDBCursorChild(
  1913. PBackgroundIDBCursorChild* aActor)
  1914. {
  1915. MOZ_ASSERT(aActor);
  1916. delete static_cast<BackgroundCursorChild*>(aActor);
  1917. return true;
  1918. }
  1919. /*******************************************************************************
  1920. * BackgroundMutableFileChild
  1921. ******************************************************************************/
  1922. BackgroundMutableFileChild::BackgroundMutableFileChild(
  1923. DEBUGONLY(PRThread* aOwningThread,)
  1924. const nsAString& aName,
  1925. const nsAString& aType)
  1926. : BackgroundMutableFileChildBase(DEBUGONLY(aOwningThread))
  1927. , mName(aName)
  1928. , mType(aType)
  1929. {
  1930. // Can't assert owning thread here because IPDL has not yet set our manager!
  1931. MOZ_COUNT_CTOR(indexedDB::BackgroundMutableFileChild);
  1932. }
  1933. BackgroundMutableFileChild::~BackgroundMutableFileChild()
  1934. {
  1935. MOZ_COUNT_DTOR(indexedDB::BackgroundMutableFileChild);
  1936. }
  1937. already_AddRefed<MutableFileBase>
  1938. BackgroundMutableFileChild::CreateMutableFile()
  1939. {
  1940. auto database =
  1941. static_cast<BackgroundDatabaseChild*>(Manager())->GetDOMObject();
  1942. MOZ_ASSERT(database);
  1943. RefPtr<IDBMutableFile> mutableFile =
  1944. new IDBMutableFile(database, this, mName, mType);
  1945. return mutableFile.forget();
  1946. }
  1947. /*******************************************************************************
  1948. * BackgroundRequestChild
  1949. ******************************************************************************/
  1950. BackgroundRequestChild::BackgroundRequestChild(IDBRequest* aRequest)
  1951. : BackgroundRequestChildBase(aRequest)
  1952. , mTransaction(aRequest->GetTransaction())
  1953. , mRunningPreprocessHelpers(0)
  1954. , mCurrentModuleSetIndex(0)
  1955. , mPreprocessResultCode(NS_OK)
  1956. , mGetAll(false)
  1957. {
  1958. MOZ_ASSERT(mTransaction);
  1959. mTransaction->AssertIsOnOwningThread();
  1960. MOZ_COUNT_CTOR(indexedDB::BackgroundRequestChild);
  1961. }
  1962. BackgroundRequestChild::~BackgroundRequestChild()
  1963. {
  1964. AssertIsOnOwningThread();
  1965. MOZ_ASSERT(!mTransaction);
  1966. MOZ_COUNT_DTOR(indexedDB::BackgroundRequestChild);
  1967. }
  1968. void
  1969. BackgroundRequestChild::MaybeSendContinue()
  1970. {
  1971. AssertIsOnOwningThread();
  1972. MOZ_ASSERT(mRunningPreprocessHelpers > 0);
  1973. if (--mRunningPreprocessHelpers == 0) {
  1974. PreprocessResponse response;
  1975. if (NS_SUCCEEDED(mPreprocessResultCode)) {
  1976. if (mGetAll) {
  1977. response = ObjectStoreGetAllPreprocessResponse();
  1978. } else {
  1979. response = ObjectStoreGetPreprocessResponse();
  1980. }
  1981. } else {
  1982. response = mPreprocessResultCode;
  1983. }
  1984. MOZ_ALWAYS_TRUE(SendContinue(response));
  1985. }
  1986. }
  1987. void
  1988. BackgroundRequestChild::OnPreprocessFinished(
  1989. uint32_t aModuleSetIndex,
  1990. nsTArray<RefPtr<JS::WasmModule>>& aModuleSet)
  1991. {
  1992. AssertIsOnOwningThread();
  1993. MOZ_ASSERT(aModuleSetIndex < mPreprocessHelpers.Length());
  1994. MOZ_ASSERT(!aModuleSet.IsEmpty());
  1995. MOZ_ASSERT(mPreprocessHelpers[aModuleSetIndex]);
  1996. MOZ_ASSERT(mModuleSets[aModuleSetIndex].IsEmpty());
  1997. mModuleSets[aModuleSetIndex].SwapElements(aModuleSet);
  1998. MaybeSendContinue();
  1999. mPreprocessHelpers[aModuleSetIndex] = nullptr;
  2000. }
  2001. void
  2002. BackgroundRequestChild::OnPreprocessFailed(uint32_t aModuleSetIndex,
  2003. nsresult aErrorCode)
  2004. {
  2005. AssertIsOnOwningThread();
  2006. MOZ_ASSERT(aModuleSetIndex < mPreprocessHelpers.Length());
  2007. MOZ_ASSERT(NS_FAILED(aErrorCode));
  2008. MOZ_ASSERT(mPreprocessHelpers[aModuleSetIndex]);
  2009. MOZ_ASSERT(mModuleSets[aModuleSetIndex].IsEmpty());
  2010. if (NS_SUCCEEDED(mPreprocessResultCode)) {
  2011. mPreprocessResultCode = aErrorCode;
  2012. }
  2013. MaybeSendContinue();
  2014. mPreprocessHelpers[aModuleSetIndex] = nullptr;
  2015. }
  2016. const nsTArray<RefPtr<JS::WasmModule>>*
  2017. BackgroundRequestChild::GetNextModuleSet(const StructuredCloneReadInfo& aInfo)
  2018. {
  2019. if (!aInfo.mHasPreprocessInfo) {
  2020. return nullptr;
  2021. }
  2022. MOZ_ASSERT(mCurrentModuleSetIndex < mModuleSets.Length());
  2023. MOZ_ASSERT(!mModuleSets[mCurrentModuleSetIndex].IsEmpty());
  2024. return &mModuleSets[mCurrentModuleSetIndex++];
  2025. }
  2026. void
  2027. BackgroundRequestChild::HandleResponse(nsresult aResponse)
  2028. {
  2029. AssertIsOnOwningThread();
  2030. MOZ_ASSERT(NS_FAILED(aResponse));
  2031. MOZ_ASSERT(NS_ERROR_GET_MODULE(aResponse) == NS_ERROR_MODULE_DOM_INDEXEDDB);
  2032. MOZ_ASSERT(mTransaction);
  2033. DispatchErrorEvent(mRequest, aResponse, mTransaction);
  2034. }
  2035. void
  2036. BackgroundRequestChild::HandleResponse(const Key& aResponse)
  2037. {
  2038. AssertIsOnOwningThread();
  2039. ResultHelper helper(mRequest, mTransaction, &aResponse);
  2040. DispatchSuccessEvent(&helper);
  2041. }
  2042. void
  2043. BackgroundRequestChild::HandleResponse(const nsTArray<Key>& aResponse)
  2044. {
  2045. AssertIsOnOwningThread();
  2046. ResultHelper helper(mRequest, mTransaction, &aResponse);
  2047. DispatchSuccessEvent(&helper);
  2048. }
  2049. void
  2050. BackgroundRequestChild::HandleResponse(
  2051. const SerializedStructuredCloneReadInfo& aResponse)
  2052. {
  2053. AssertIsOnOwningThread();
  2054. // XXX Fix this somehow...
  2055. auto& serializedCloneInfo =
  2056. const_cast<SerializedStructuredCloneReadInfo&>(aResponse);
  2057. StructuredCloneReadInfo cloneReadInfo(Move(serializedCloneInfo));
  2058. DeserializeStructuredCloneFiles(mTransaction->Database(),
  2059. aResponse.files(),
  2060. GetNextModuleSet(cloneReadInfo),
  2061. cloneReadInfo.mFiles);
  2062. ResultHelper helper(mRequest, mTransaction, &cloneReadInfo);
  2063. DispatchSuccessEvent(&helper);
  2064. }
  2065. void
  2066. BackgroundRequestChild::HandleResponse(
  2067. const nsTArray<SerializedStructuredCloneReadInfo>& aResponse)
  2068. {
  2069. AssertIsOnOwningThread();
  2070. nsTArray<StructuredCloneReadInfo> cloneReadInfos;
  2071. if (!aResponse.IsEmpty()) {
  2072. const uint32_t count = aResponse.Length();
  2073. cloneReadInfos.SetCapacity(count);
  2074. IDBDatabase* database = mTransaction->Database();
  2075. for (uint32_t index = 0; index < count; index++) {
  2076. // XXX Fix this somehow...
  2077. auto& serializedCloneInfo =
  2078. const_cast<SerializedStructuredCloneReadInfo&>(aResponse[index]);
  2079. StructuredCloneReadInfo* cloneReadInfo = cloneReadInfos.AppendElement();
  2080. // Move relevant data into the cloneReadInfo
  2081. *cloneReadInfo = Move(serializedCloneInfo);
  2082. // Get the files
  2083. nsTArray<StructuredCloneFile> files;
  2084. DeserializeStructuredCloneFiles(database,
  2085. serializedCloneInfo.files(),
  2086. GetNextModuleSet(*cloneReadInfo),
  2087. files);
  2088. cloneReadInfo->mFiles = Move(files);
  2089. }
  2090. }
  2091. ResultHelper helper(mRequest, mTransaction, &cloneReadInfos);
  2092. DispatchSuccessEvent(&helper);
  2093. }
  2094. void
  2095. BackgroundRequestChild::HandleResponse(JS::Handle<JS::Value> aResponse)
  2096. {
  2097. AssertIsOnOwningThread();
  2098. ResultHelper helper(mRequest, mTransaction, &aResponse);
  2099. DispatchSuccessEvent(&helper);
  2100. }
  2101. void
  2102. BackgroundRequestChild::HandleResponse(uint64_t aResponse)
  2103. {
  2104. AssertIsOnOwningThread();
  2105. JS::Value response(JS::NumberValue(aResponse));
  2106. ResultHelper helper(mRequest, mTransaction, &response);
  2107. DispatchSuccessEvent(&helper);
  2108. }
  2109. nsresult
  2110. BackgroundRequestChild::HandlePreprocess(
  2111. const WasmModulePreprocessInfo& aPreprocessInfo)
  2112. {
  2113. AssertIsOnOwningThread();
  2114. IDBDatabase* database = mTransaction->Database();
  2115. mPreprocessHelpers.SetLength(1);
  2116. nsTArray<StructuredCloneFile> files;
  2117. DeserializeStructuredCloneFiles(database,
  2118. aPreprocessInfo.files(),
  2119. nullptr,
  2120. files);
  2121. RefPtr<PreprocessHelper>& preprocessHelper = mPreprocessHelpers[0];
  2122. preprocessHelper = new PreprocessHelper(0, this);
  2123. nsresult rv = preprocessHelper->Init(files);
  2124. if (NS_WARN_IF(NS_FAILED(rv))) {
  2125. return rv;
  2126. }
  2127. rv = preprocessHelper->Dispatch();
  2128. if (NS_WARN_IF(NS_FAILED(rv))) {
  2129. return rv;
  2130. }
  2131. mRunningPreprocessHelpers++;
  2132. mModuleSets.SetLength(1);
  2133. return NS_OK;
  2134. }
  2135. nsresult
  2136. BackgroundRequestChild::HandlePreprocess(
  2137. const nsTArray<WasmModulePreprocessInfo>& aPreprocessInfos)
  2138. {
  2139. AssertIsOnOwningThread();
  2140. IDBDatabase* database = mTransaction->Database();
  2141. uint32_t count = aPreprocessInfos.Length();
  2142. mPreprocessHelpers.SetLength(count);
  2143. // TODO: Since we use the stream transport service, this can spawn 25 threads
  2144. // and has the potential to cause some annoying browser hiccups.
  2145. // Consider using a single thread or a very small threadpool.
  2146. for (uint32_t index = 0; index < count; index++) {
  2147. const WasmModulePreprocessInfo& preprocessInfo = aPreprocessInfos[index];
  2148. nsTArray<StructuredCloneFile> files;
  2149. DeserializeStructuredCloneFiles(database,
  2150. preprocessInfo.files(),
  2151. nullptr,
  2152. files);
  2153. RefPtr<PreprocessHelper>& preprocessHelper = mPreprocessHelpers[index];
  2154. preprocessHelper = new PreprocessHelper(index, this);
  2155. nsresult rv = preprocessHelper->Init(files);
  2156. if (NS_WARN_IF(NS_FAILED(rv))) {
  2157. return rv;
  2158. }
  2159. rv = preprocessHelper->Dispatch();
  2160. if (NS_WARN_IF(NS_FAILED(rv))) {
  2161. return rv;
  2162. }
  2163. mRunningPreprocessHelpers++;
  2164. }
  2165. mModuleSets.SetLength(count);
  2166. mGetAll = true;
  2167. return NS_OK;
  2168. }
  2169. void
  2170. BackgroundRequestChild::ActorDestroy(ActorDestroyReason aWhy)
  2171. {
  2172. AssertIsOnOwningThread();
  2173. MaybeCollectGarbageOnIPCMessage();
  2174. for (uint32_t count = mPreprocessHelpers.Length(), index = 0;
  2175. index < count;
  2176. index++) {
  2177. RefPtr<PreprocessHelper>& preprocessHelper = mPreprocessHelpers[index];
  2178. if (preprocessHelper) {
  2179. preprocessHelper->ClearActor();
  2180. preprocessHelper = nullptr;
  2181. }
  2182. }
  2183. if (mTransaction) {
  2184. mTransaction->AssertIsOnOwningThread();
  2185. mTransaction->OnRequestFinished(/* aActorDestroyedNormally */
  2186. aWhy == Deletion);
  2187. #ifdef DEBUG
  2188. mTransaction = nullptr;
  2189. #endif
  2190. }
  2191. }
  2192. bool
  2193. BackgroundRequestChild::Recv__delete__(const RequestResponse& aResponse)
  2194. {
  2195. AssertIsOnOwningThread();
  2196. MOZ_ASSERT(mRequest);
  2197. MOZ_ASSERT(mTransaction);
  2198. MaybeCollectGarbageOnIPCMessage();
  2199. if (mTransaction->IsAborted()) {
  2200. // Always fire an "error" event with ABORT_ERR if the transaction was
  2201. // aborted, even if the request succeeded or failed with another error.
  2202. HandleResponse(NS_ERROR_DOM_INDEXEDDB_ABORT_ERR);
  2203. } else {
  2204. switch (aResponse.type()) {
  2205. case RequestResponse::Tnsresult:
  2206. HandleResponse(aResponse.get_nsresult());
  2207. break;
  2208. case RequestResponse::TObjectStoreAddResponse:
  2209. HandleResponse(aResponse.get_ObjectStoreAddResponse().key());
  2210. break;
  2211. case RequestResponse::TObjectStorePutResponse:
  2212. HandleResponse(aResponse.get_ObjectStorePutResponse().key());
  2213. break;
  2214. case RequestResponse::TObjectStoreGetResponse:
  2215. HandleResponse(aResponse.get_ObjectStoreGetResponse().cloneInfo());
  2216. break;
  2217. case RequestResponse::TObjectStoreGetKeyResponse:
  2218. HandleResponse(aResponse.get_ObjectStoreGetKeyResponse().key());
  2219. break;
  2220. case RequestResponse::TObjectStoreGetAllResponse:
  2221. HandleResponse(aResponse.get_ObjectStoreGetAllResponse().cloneInfos());
  2222. break;
  2223. case RequestResponse::TObjectStoreGetAllKeysResponse:
  2224. HandleResponse(aResponse.get_ObjectStoreGetAllKeysResponse().keys());
  2225. break;
  2226. case RequestResponse::TObjectStoreDeleteResponse:
  2227. HandleResponse(JS::UndefinedHandleValue);
  2228. break;
  2229. case RequestResponse::TObjectStoreClearResponse:
  2230. HandleResponse(JS::UndefinedHandleValue);
  2231. break;
  2232. case RequestResponse::TObjectStoreCountResponse:
  2233. HandleResponse(aResponse.get_ObjectStoreCountResponse().count());
  2234. break;
  2235. case RequestResponse::TIndexGetResponse:
  2236. HandleResponse(aResponse.get_IndexGetResponse().cloneInfo());
  2237. break;
  2238. case RequestResponse::TIndexGetKeyResponse:
  2239. HandleResponse(aResponse.get_IndexGetKeyResponse().key());
  2240. break;
  2241. case RequestResponse::TIndexGetAllResponse:
  2242. HandleResponse(aResponse.get_IndexGetAllResponse().cloneInfos());
  2243. break;
  2244. case RequestResponse::TIndexGetAllKeysResponse:
  2245. HandleResponse(aResponse.get_IndexGetAllKeysResponse().keys());
  2246. break;
  2247. case RequestResponse::TIndexCountResponse:
  2248. HandleResponse(aResponse.get_IndexCountResponse().count());
  2249. break;
  2250. default:
  2251. MOZ_CRASH("Unknown response type!");
  2252. }
  2253. }
  2254. mTransaction->OnRequestFinished(/* aActorDestroyedNormally */ true);
  2255. // Null this out so that we don't try to call OnRequestFinished() again in
  2256. // ActorDestroy.
  2257. mTransaction = nullptr;
  2258. return true;
  2259. }
  2260. bool
  2261. BackgroundRequestChild::RecvPreprocess(const PreprocessParams& aParams)
  2262. {
  2263. AssertIsOnOwningThread();
  2264. MOZ_ASSERT(mTransaction);
  2265. MaybeCollectGarbageOnIPCMessage();
  2266. nsresult rv;
  2267. switch (aParams.type()) {
  2268. case PreprocessParams::TObjectStoreGetPreprocessParams: {
  2269. ObjectStoreGetPreprocessParams params =
  2270. aParams.get_ObjectStoreGetPreprocessParams();
  2271. rv = HandlePreprocess(params.preprocessInfo());
  2272. break;
  2273. }
  2274. case PreprocessParams::TObjectStoreGetAllPreprocessParams: {
  2275. ObjectStoreGetAllPreprocessParams params =
  2276. aParams.get_ObjectStoreGetAllPreprocessParams();
  2277. rv = HandlePreprocess(params.preprocessInfos());
  2278. break;
  2279. }
  2280. default:
  2281. MOZ_CRASH("Unknown params type!");
  2282. }
  2283. if (NS_WARN_IF(NS_FAILED(rv))) {
  2284. return SendContinue(rv);
  2285. }
  2286. return true;
  2287. }
  2288. nsresult
  2289. BackgroundRequestChild::
  2290. PreprocessHelper::Init(const nsTArray<StructuredCloneFile>& aFiles)
  2291. {
  2292. AssertIsOnOwningThread();
  2293. MOZ_ASSERT(!aFiles.IsEmpty());
  2294. uint32_t count = aFiles.Length();
  2295. // We should receive even number of files.
  2296. MOZ_ASSERT(count % 2 == 0);
  2297. // Let's process it as pairs.
  2298. count = count / 2;
  2299. nsTArray<StreamPair> streamPairs;
  2300. for (uint32_t index = 0; index < count; index++) {
  2301. uint32_t bytecodeIndex = index * 2;
  2302. uint32_t compiledIndex = bytecodeIndex + 1;
  2303. const StructuredCloneFile& bytecodeFile = aFiles[bytecodeIndex];
  2304. const StructuredCloneFile& compiledFile = aFiles[compiledIndex];
  2305. MOZ_ASSERT(bytecodeFile.mType == StructuredCloneFile::eWasmBytecode);
  2306. MOZ_ASSERT(bytecodeFile.mBlob);
  2307. MOZ_ASSERT(compiledFile.mType == StructuredCloneFile::eWasmCompiled);
  2308. MOZ_ASSERT(compiledFile.mBlob);
  2309. ErrorResult errorResult;
  2310. nsCOMPtr<nsIInputStream> bytecodeStream;
  2311. bytecodeFile.mBlob->GetInternalStream(getter_AddRefs(bytecodeStream),
  2312. errorResult);
  2313. if (NS_WARN_IF(errorResult.Failed())) {
  2314. return errorResult.StealNSResult();
  2315. }
  2316. nsCOMPtr<nsIInputStream> compiledStream;
  2317. compiledFile.mBlob->GetInternalStream(getter_AddRefs(compiledStream),
  2318. errorResult);
  2319. if (NS_WARN_IF(errorResult.Failed())) {
  2320. return errorResult.StealNSResult();
  2321. }
  2322. streamPairs.AppendElement(StreamPair(bytecodeStream, compiledStream));
  2323. }
  2324. mStreamPairs = Move(streamPairs);
  2325. return NS_OK;
  2326. }
  2327. nsresult
  2328. BackgroundRequestChild::
  2329. PreprocessHelper::Dispatch()
  2330. {
  2331. AssertIsOnOwningThread();
  2332. // The stream transport service is used for asynchronous processing. It has
  2333. // a threadpool with a high cap of 25 threads. Fortunately, the service can
  2334. // be used on workers too.
  2335. nsCOMPtr<nsIEventTarget> target =
  2336. do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
  2337. MOZ_ASSERT(target);
  2338. nsresult rv = target->Dispatch(this, NS_DISPATCH_NORMAL);
  2339. if (NS_WARN_IF(NS_FAILED(rv))) {
  2340. return rv;
  2341. }
  2342. return NS_OK;
  2343. }
  2344. void
  2345. BackgroundRequestChild::
  2346. PreprocessHelper::RunOnOwningThread()
  2347. {
  2348. AssertIsOnOwningThread();
  2349. if (mActor) {
  2350. if (NS_SUCCEEDED(mResultCode)) {
  2351. mActor->OnPreprocessFinished(mModuleSetIndex, mModuleSet);
  2352. MOZ_ASSERT(mModuleSet.IsEmpty());
  2353. } else {
  2354. mActor->OnPreprocessFailed(mModuleSetIndex, mResultCode);
  2355. }
  2356. }
  2357. }
  2358. nsresult
  2359. BackgroundRequestChild::
  2360. PreprocessHelper::RunOnStreamTransportThread()
  2361. {
  2362. MOZ_ASSERT(!IsOnOwningThread());
  2363. MOZ_ASSERT(!mStreamPairs.IsEmpty());
  2364. MOZ_ASSERT(mModuleSet.IsEmpty());
  2365. const uint32_t count = mStreamPairs.Length();
  2366. for (uint32_t index = 0; index < count; index++) {
  2367. const StreamPair& streamPair = mStreamPairs[index];
  2368. const nsCOMPtr<nsIInputStream>& bytecodeStream = streamPair.first;
  2369. MOZ_ASSERT(bytecodeStream);
  2370. PRFileDesc* bytecodeFileDesc = GetFileDescriptorFromStream(bytecodeStream);
  2371. if (NS_WARN_IF(!bytecodeFileDesc)) {
  2372. return NS_ERROR_FAILURE;
  2373. }
  2374. const nsCOMPtr<nsIInputStream>& compiledStream = streamPair.second;
  2375. MOZ_ASSERT(compiledStream);
  2376. PRFileDesc* compiledFileDesc = GetFileDescriptorFromStream(compiledStream);
  2377. if (NS_WARN_IF(!compiledFileDesc)) {
  2378. return NS_ERROR_FAILURE;
  2379. }
  2380. JS::BuildIdCharVector buildId;
  2381. bool ok = GetBuildId(&buildId);
  2382. if (NS_WARN_IF(!ok)) {
  2383. return NS_ERROR_FAILURE;
  2384. }
  2385. RefPtr<JS::WasmModule> module = JS::DeserializeWasmModule(bytecodeFileDesc,
  2386. compiledFileDesc,
  2387. Move(buildId),
  2388. nullptr,
  2389. 0,
  2390. 0);
  2391. if (NS_WARN_IF(!module)) {
  2392. return NS_ERROR_FAILURE;
  2393. }
  2394. mModuleSet.AppendElement(module);
  2395. }
  2396. mStreamPairs.Clear();
  2397. return NS_OK;
  2398. }
  2399. NS_IMETHODIMP
  2400. BackgroundRequestChild::
  2401. PreprocessHelper::Run()
  2402. {
  2403. if (IsOnOwningThread()) {
  2404. RunOnOwningThread();
  2405. } else {
  2406. nsresult rv = RunOnStreamTransportThread();
  2407. if (NS_WARN_IF(NS_FAILED(rv))) {
  2408. MOZ_ASSERT(mResultCode == NS_OK);
  2409. mResultCode = rv;
  2410. }
  2411. MOZ_ALWAYS_SUCCEEDS(mOwningThread->Dispatch(this, NS_DISPATCH_NORMAL));
  2412. }
  2413. return NS_OK;
  2414. }
  2415. nsresult
  2416. BackgroundRequestChild::
  2417. PreprocessHelper::Cancel()
  2418. {
  2419. return NS_OK;
  2420. }
  2421. /*******************************************************************************
  2422. * BackgroundCursorChild
  2423. ******************************************************************************/
  2424. // Does not need to be threadsafe since this only runs on one thread, but
  2425. // inheriting from CancelableRunnable is easy.
  2426. class BackgroundCursorChild::DelayedActionRunnable final
  2427. : public CancelableRunnable
  2428. {
  2429. using ActionFunc = void (BackgroundCursorChild::*)();
  2430. BackgroundCursorChild* mActor;
  2431. RefPtr<IDBRequest> mRequest;
  2432. ActionFunc mActionFunc;
  2433. public:
  2434. explicit
  2435. DelayedActionRunnable(BackgroundCursorChild* aActor, ActionFunc aActionFunc)
  2436. : mActor(aActor)
  2437. , mRequest(aActor->mRequest)
  2438. , mActionFunc(aActionFunc)
  2439. {
  2440. MOZ_ASSERT(aActor);
  2441. aActor->AssertIsOnOwningThread();
  2442. MOZ_ASSERT(mRequest);
  2443. MOZ_ASSERT(mActionFunc);
  2444. }
  2445. private:
  2446. ~DelayedActionRunnable()
  2447. { }
  2448. NS_DECL_NSIRUNNABLE
  2449. nsresult Cancel() override;
  2450. };
  2451. BackgroundCursorChild::BackgroundCursorChild(IDBRequest* aRequest,
  2452. IDBObjectStore* aObjectStore,
  2453. Direction aDirection)
  2454. : mRequest(aRequest)
  2455. , mTransaction(aRequest->GetTransaction())
  2456. , mObjectStore(aObjectStore)
  2457. , mIndex(nullptr)
  2458. , mCursor(nullptr)
  2459. , mStrongRequest(aRequest)
  2460. , mDirection(aDirection)
  2461. {
  2462. MOZ_ASSERT(aObjectStore);
  2463. aObjectStore->AssertIsOnOwningThread();
  2464. MOZ_ASSERT(mTransaction);
  2465. MOZ_COUNT_CTOR(indexedDB::BackgroundCursorChild);
  2466. #ifdef DEBUG
  2467. mOwningThread = PR_GetCurrentThread();
  2468. MOZ_ASSERT(mOwningThread);
  2469. #endif
  2470. }
  2471. BackgroundCursorChild::BackgroundCursorChild(IDBRequest* aRequest,
  2472. IDBIndex* aIndex,
  2473. Direction aDirection)
  2474. : mRequest(aRequest)
  2475. , mTransaction(aRequest->GetTransaction())
  2476. , mObjectStore(nullptr)
  2477. , mIndex(aIndex)
  2478. , mCursor(nullptr)
  2479. , mStrongRequest(aRequest)
  2480. , mDirection(aDirection)
  2481. {
  2482. MOZ_ASSERT(aIndex);
  2483. aIndex->AssertIsOnOwningThread();
  2484. MOZ_ASSERT(mTransaction);
  2485. MOZ_COUNT_CTOR(indexedDB::BackgroundCursorChild);
  2486. #ifdef DEBUG
  2487. mOwningThread = PR_GetCurrentThread();
  2488. MOZ_ASSERT(mOwningThread);
  2489. #endif
  2490. }
  2491. BackgroundCursorChild::~BackgroundCursorChild()
  2492. {
  2493. MOZ_COUNT_DTOR(indexedDB::BackgroundCursorChild);
  2494. }
  2495. #ifdef DEBUG
  2496. void
  2497. BackgroundCursorChild::AssertIsOnOwningThread() const
  2498. {
  2499. MOZ_ASSERT(mOwningThread == PR_GetCurrentThread());
  2500. }
  2501. #endif // DEBUG
  2502. void
  2503. BackgroundCursorChild::SendContinueInternal(const CursorRequestParams& aParams)
  2504. {
  2505. AssertIsOnOwningThread();
  2506. MOZ_ASSERT(mRequest);
  2507. MOZ_ASSERT(mTransaction);
  2508. MOZ_ASSERT(mCursor);
  2509. MOZ_ASSERT(!mStrongRequest);
  2510. MOZ_ASSERT(!mStrongCursor);
  2511. // Make sure all our DOM objects stay alive.
  2512. mStrongCursor = mCursor;
  2513. MOZ_ASSERT(mRequest->ReadyState() == IDBRequestReadyState::Done);
  2514. mRequest->Reset();
  2515. mTransaction->OnNewRequest();
  2516. MOZ_ALWAYS_TRUE(PBackgroundIDBCursorChild::SendContinue(aParams));
  2517. }
  2518. void
  2519. BackgroundCursorChild::SendDeleteMeInternal()
  2520. {
  2521. AssertIsOnOwningThread();
  2522. MOZ_ASSERT(!mStrongRequest);
  2523. MOZ_ASSERT(!mStrongCursor);
  2524. mRequest = nullptr;
  2525. mTransaction = nullptr;
  2526. mObjectStore = nullptr;
  2527. mIndex = nullptr;
  2528. if (mCursor) {
  2529. mCursor->ClearBackgroundActor();
  2530. mCursor = nullptr;
  2531. MOZ_ALWAYS_TRUE(PBackgroundIDBCursorChild::SendDeleteMe());
  2532. }
  2533. }
  2534. void
  2535. BackgroundCursorChild::HandleResponse(nsresult aResponse)
  2536. {
  2537. AssertIsOnOwningThread();
  2538. MOZ_ASSERT(NS_FAILED(aResponse));
  2539. MOZ_ASSERT(NS_ERROR_GET_MODULE(aResponse) == NS_ERROR_MODULE_DOM_INDEXEDDB);
  2540. MOZ_ASSERT(mRequest);
  2541. MOZ_ASSERT(mTransaction);
  2542. MOZ_ASSERT(!mStrongRequest);
  2543. MOZ_ASSERT(!mStrongCursor);
  2544. DispatchErrorEvent(mRequest, aResponse, mTransaction);
  2545. }
  2546. void
  2547. BackgroundCursorChild::HandleResponse(const void_t& aResponse)
  2548. {
  2549. AssertIsOnOwningThread();
  2550. MOZ_ASSERT(mRequest);
  2551. MOZ_ASSERT(mTransaction);
  2552. MOZ_ASSERT(!mStrongRequest);
  2553. MOZ_ASSERT(!mStrongCursor);
  2554. if (mCursor) {
  2555. mCursor->Reset();
  2556. }
  2557. ResultHelper helper(mRequest, mTransaction, &JS::NullHandleValue);
  2558. DispatchSuccessEvent(&helper);
  2559. if (!mCursor) {
  2560. nsCOMPtr<nsIRunnable> deleteRunnable = new DelayedActionRunnable(
  2561. this, &BackgroundCursorChild::SendDeleteMeInternal);
  2562. MOZ_ALWAYS_SUCCEEDS(NS_DispatchToCurrentThread(deleteRunnable));
  2563. }
  2564. }
  2565. void
  2566. BackgroundCursorChild::HandleResponse(
  2567. const nsTArray<ObjectStoreCursorResponse>& aResponses)
  2568. {
  2569. AssertIsOnOwningThread();
  2570. MOZ_ASSERT(mRequest);
  2571. MOZ_ASSERT(mTransaction);
  2572. MOZ_ASSERT(mObjectStore);
  2573. MOZ_ASSERT(!mStrongRequest);
  2574. MOZ_ASSERT(!mStrongCursor);
  2575. MOZ_ASSERT(aResponses.Length() == 1);
  2576. // XXX Fix this somehow...
  2577. auto& responses =
  2578. const_cast<nsTArray<ObjectStoreCursorResponse>&>(aResponses);
  2579. // If a new cursor is created, we need to keep a reference to it until the
  2580. // ResultHelper creates a DOM Binding.
  2581. RefPtr<IDBCursor> newCursor;
  2582. for (ObjectStoreCursorResponse& response : responses) {
  2583. StructuredCloneReadInfo cloneReadInfo(Move(response.cloneInfo()));
  2584. cloneReadInfo.mDatabase = mTransaction->Database();
  2585. DeserializeStructuredCloneFiles(mTransaction->Database(),
  2586. response.cloneInfo().files(),
  2587. nullptr,
  2588. cloneReadInfo.mFiles);
  2589. if (mCursor) {
  2590. mCursor->Reset(Move(response.key()), Move(cloneReadInfo));
  2591. } else {
  2592. newCursor = IDBCursor::Create(this,
  2593. Move(response.key()),
  2594. Move(cloneReadInfo));
  2595. mCursor = newCursor;
  2596. }
  2597. }
  2598. ResultHelper helper(mRequest, mTransaction, mCursor);
  2599. DispatchSuccessEvent(&helper);
  2600. }
  2601. void
  2602. BackgroundCursorChild::HandleResponse(
  2603. const ObjectStoreKeyCursorResponse& aResponse)
  2604. {
  2605. AssertIsOnOwningThread();
  2606. MOZ_ASSERT(mRequest);
  2607. MOZ_ASSERT(mTransaction);
  2608. MOZ_ASSERT(mObjectStore);
  2609. MOZ_ASSERT(!mStrongRequest);
  2610. MOZ_ASSERT(!mStrongCursor);
  2611. // XXX Fix this somehow...
  2612. auto& response = const_cast<ObjectStoreKeyCursorResponse&>(aResponse);
  2613. RefPtr<IDBCursor> newCursor;
  2614. if (mCursor) {
  2615. mCursor->Reset(Move(response.key()));
  2616. } else {
  2617. newCursor = IDBCursor::Create(this, Move(response.key()));
  2618. mCursor = newCursor;
  2619. }
  2620. ResultHelper helper(mRequest, mTransaction, mCursor);
  2621. DispatchSuccessEvent(&helper);
  2622. }
  2623. void
  2624. BackgroundCursorChild::HandleResponse(const IndexCursorResponse& aResponse)
  2625. {
  2626. AssertIsOnOwningThread();
  2627. MOZ_ASSERT(mRequest);
  2628. MOZ_ASSERT(mTransaction);
  2629. MOZ_ASSERT(mIndex);
  2630. MOZ_ASSERT(!mStrongRequest);
  2631. MOZ_ASSERT(!mStrongCursor);
  2632. // XXX Fix this somehow...
  2633. auto& response = const_cast<IndexCursorResponse&>(aResponse);
  2634. StructuredCloneReadInfo cloneReadInfo(Move(response.cloneInfo()));
  2635. cloneReadInfo.mDatabase = mTransaction->Database();
  2636. DeserializeStructuredCloneFiles(mTransaction->Database(),
  2637. aResponse.cloneInfo().files(),
  2638. nullptr,
  2639. cloneReadInfo.mFiles);
  2640. RefPtr<IDBCursor> newCursor;
  2641. if (mCursor) {
  2642. mCursor->Reset(Move(response.key()),
  2643. Move(response.sortKey()),
  2644. Move(response.objectKey()),
  2645. Move(cloneReadInfo));
  2646. } else {
  2647. newCursor = IDBCursor::Create(this,
  2648. Move(response.key()),
  2649. Move(response.sortKey()),
  2650. Move(response.objectKey()),
  2651. Move(cloneReadInfo));
  2652. mCursor = newCursor;
  2653. }
  2654. ResultHelper helper(mRequest, mTransaction, mCursor);
  2655. DispatchSuccessEvent(&helper);
  2656. }
  2657. void
  2658. BackgroundCursorChild::HandleResponse(const IndexKeyCursorResponse& aResponse)
  2659. {
  2660. AssertIsOnOwningThread();
  2661. MOZ_ASSERT(mRequest);
  2662. MOZ_ASSERT(mTransaction);
  2663. MOZ_ASSERT(mIndex);
  2664. MOZ_ASSERT(!mStrongRequest);
  2665. MOZ_ASSERT(!mStrongCursor);
  2666. // XXX Fix this somehow...
  2667. auto& response = const_cast<IndexKeyCursorResponse&>(aResponse);
  2668. RefPtr<IDBCursor> newCursor;
  2669. if (mCursor) {
  2670. mCursor->Reset(Move(response.key()),
  2671. Move(response.sortKey()),
  2672. Move(response.objectKey()));
  2673. } else {
  2674. newCursor = IDBCursor::Create(this,
  2675. Move(response.key()),
  2676. Move(response.sortKey()),
  2677. Move(response.objectKey()));
  2678. mCursor = newCursor;
  2679. }
  2680. ResultHelper helper(mRequest, mTransaction, mCursor);
  2681. DispatchSuccessEvent(&helper);
  2682. }
  2683. void
  2684. BackgroundCursorChild::ActorDestroy(ActorDestroyReason aWhy)
  2685. {
  2686. AssertIsOnOwningThread();
  2687. MOZ_ASSERT_IF(aWhy == Deletion, !mStrongRequest);
  2688. MOZ_ASSERT_IF(aWhy == Deletion, !mStrongCursor);
  2689. MaybeCollectGarbageOnIPCMessage();
  2690. if (mStrongRequest && !mStrongCursor && mTransaction) {
  2691. mTransaction->OnRequestFinished(/* aActorDestroyedNormally */
  2692. aWhy == Deletion);
  2693. }
  2694. if (mCursor) {
  2695. mCursor->ClearBackgroundActor();
  2696. #ifdef DEBUG
  2697. mCursor = nullptr;
  2698. #endif
  2699. }
  2700. #ifdef DEBUG
  2701. mRequest = nullptr;
  2702. mTransaction = nullptr;
  2703. mObjectStore = nullptr;
  2704. mIndex = nullptr;
  2705. #endif
  2706. }
  2707. bool
  2708. BackgroundCursorChild::RecvResponse(const CursorResponse& aResponse)
  2709. {
  2710. AssertIsOnOwningThread();
  2711. MOZ_ASSERT(aResponse.type() != CursorResponse::T__None);
  2712. MOZ_ASSERT(mRequest);
  2713. MOZ_ASSERT(mTransaction);
  2714. MOZ_ASSERT_IF(mCursor, mStrongCursor);
  2715. MOZ_ASSERT_IF(!mCursor, mStrongRequest);
  2716. MaybeCollectGarbageOnIPCMessage();
  2717. RefPtr<IDBRequest> request;
  2718. mStrongRequest.swap(request);
  2719. RefPtr<IDBCursor> cursor;
  2720. mStrongCursor.swap(cursor);
  2721. RefPtr<IDBTransaction> transaction = mTransaction;
  2722. switch (aResponse.type()) {
  2723. case CursorResponse::Tnsresult:
  2724. HandleResponse(aResponse.get_nsresult());
  2725. break;
  2726. case CursorResponse::Tvoid_t:
  2727. HandleResponse(aResponse.get_void_t());
  2728. break;
  2729. case CursorResponse::TArrayOfObjectStoreCursorResponse:
  2730. HandleResponse(aResponse.get_ArrayOfObjectStoreCursorResponse());
  2731. break;
  2732. case CursorResponse::TObjectStoreKeyCursorResponse:
  2733. HandleResponse(aResponse.get_ObjectStoreKeyCursorResponse());
  2734. break;
  2735. case CursorResponse::TIndexCursorResponse:
  2736. HandleResponse(aResponse.get_IndexCursorResponse());
  2737. break;
  2738. case CursorResponse::TIndexKeyCursorResponse:
  2739. HandleResponse(aResponse.get_IndexKeyCursorResponse());
  2740. break;
  2741. default:
  2742. MOZ_CRASH("Should never get here!");
  2743. }
  2744. transaction->OnRequestFinished(/* aActorDestroyedNormally */ true);
  2745. return true;
  2746. }
  2747. NS_IMETHODIMP
  2748. BackgroundCursorChild::
  2749. DelayedActionRunnable::Run()
  2750. {
  2751. MOZ_ASSERT(mActor);
  2752. mActor->AssertIsOnOwningThread();
  2753. MOZ_ASSERT(mRequest);
  2754. MOZ_ASSERT(mActionFunc);
  2755. (mActor->*mActionFunc)();
  2756. mActor = nullptr;
  2757. mRequest = nullptr;
  2758. return NS_OK;
  2759. }
  2760. nsresult
  2761. BackgroundCursorChild::
  2762. DelayedActionRunnable::Cancel()
  2763. {
  2764. if (NS_WARN_IF(!mActor)) {
  2765. return NS_ERROR_UNEXPECTED;
  2766. }
  2767. // This must always run to clean up our state.
  2768. Run();
  2769. return NS_OK;
  2770. }
  2771. /*******************************************************************************
  2772. * BackgroundUtilsChild
  2773. ******************************************************************************/
  2774. BackgroundUtilsChild::BackgroundUtilsChild(IndexedDatabaseManager* aManager)
  2775. : mManager(aManager)
  2776. #ifdef DEBUG
  2777. , mOwningThread(NS_GetCurrentThread())
  2778. #endif
  2779. {
  2780. AssertIsOnOwningThread();
  2781. MOZ_ASSERT(aManager);
  2782. MOZ_COUNT_CTOR(indexedDB::BackgroundUtilsChild);
  2783. }
  2784. BackgroundUtilsChild::~BackgroundUtilsChild()
  2785. {
  2786. MOZ_COUNT_DTOR(indexedDB::BackgroundUtilsChild);
  2787. }
  2788. #ifdef DEBUG
  2789. void
  2790. BackgroundUtilsChild::AssertIsOnOwningThread() const
  2791. {
  2792. MOZ_ASSERT(mOwningThread);
  2793. bool current;
  2794. MOZ_ASSERT(NS_SUCCEEDED(mOwningThread->IsOnCurrentThread(&current)));
  2795. MOZ_ASSERT(current);
  2796. }
  2797. #endif // DEBUG
  2798. void
  2799. BackgroundUtilsChild::SendDeleteMeInternal()
  2800. {
  2801. AssertIsOnOwningThread();
  2802. if (mManager) {
  2803. mManager->ClearBackgroundActor();
  2804. mManager = nullptr;
  2805. MOZ_ALWAYS_TRUE(PBackgroundIndexedDBUtilsChild::SendDeleteMe());
  2806. }
  2807. }
  2808. void
  2809. BackgroundUtilsChild::ActorDestroy(ActorDestroyReason aWhy)
  2810. {
  2811. AssertIsOnOwningThread();
  2812. if (mManager) {
  2813. mManager->ClearBackgroundActor();
  2814. #ifdef DEBUG
  2815. mManager = nullptr;
  2816. #endif
  2817. }
  2818. }
  2819. } // namespace indexedDB
  2820. } // namespace dom
  2821. } // namespace mozilla