From c2bcdec5c9ed69dac41be63988eec3c28d0b164d Mon Sep 17 00:00:00 2001 From: roytam1 Date: Wed, 28 Aug 2024 23:55:40 +0800 Subject: [PATCH] import changes from `dev' branch of rmottola/Arctic-Fox: - Bug 1261009 - Remove the Data Store API, r=fabrice (b22e580107) - Bug 1268393 - Some compilation issues in ServiceWorker code, r=ehsan (d9c2f2554b) - Bug 1209095 - Accept opaqueredirection fetch results if the request redirection type is manual. r=bkelly (6fe92d1368) - Bug 1267733 P2 Pass ServiceWorkerRegistrationInfo down to CancelChannelRunnable. r=jdm (0ec51f09ef) - Bug 1267733 P3 Trigger service worker update after failed interception. r=jdm (f89a7998d4) - Bug 1267733 P4 Add a wpt test that verifies a service worker update can recover from a broken navigation interception. r=jdm (9dc0ce97bd) - Bug 1267691: Assert on failed attempts to shutdown a thread from itself r=froyd (0cbd1e458c) - Bug 1180533 - Disable BackgroundHangMonitor on gonk (a2d666e741) - Bug 1121216 - disable BackgroundHangMonitor for TSan builds; r=jchen (ef15d1016f) - Bug 1265621 - Use StaticRefPtr in Omnijar.cpp; r=froydnj (81bc32836e) - Bug 1265621 - Expose outer zip readers in Omnijar::GetReader; r=froydnj (ce3f82929e) - Bug 1267021 - Use fallible allocation and move semantics for Push events. r=wchen (3a1ae23d8d) - Bug 1222899 - Handle geolocation-device-events callback. r=kchen (a33bcf4297) - Bug 1237831 - Update GonkGPSGeolocationProvider.cpp to use B2G-style. r=jst (d389eedf47) - Bug 1245033 - Build break in dom/system/gonk/GonkGPSGeolocationProvider.cpp:541:126: error: format '%d' expects argument of type 'int', but argument 5 has type 'nsresult'. r=fabrice (ecde789edf) - Bug 1264287: Convert Wifi to use |UniquePtr|, r=nfroyd (9bad7792bf) - Bug 1267577 - Move nsRunnable to mozilla::Runnable. r=gsvelto (f58e2161f2) - Bug 1210370 - Close wpa_supplicant before we shutdown nsIWifiProxyService. r=mrbkap (5cd4dce58f) - Bug 1218629 - Save audio volume for each device to setting db r=alwu (2f1847dd6f) - Bug 1249437 - Remove workaround of volume control r=alwu (13cd144a89) - Bug 1268432: Replace |Task| with |Runnable| in B2G code r=fabrice (bcc768e9cb) - Bug 1226483 - Add ASSERT check to AudioManager::SelectDeviceFromDevices() r=alwu (446e8f634e) - Bug 1229234 - Enable audio_is_output_device() on ICS r=alwu (84aae07f23) - Bug 1267369 - Only generate typelib data for scriptable interfaces; r=khuey (e49b44c9ce) - Bug 1155969 - Make runtests.py flake8 compliant. r=ted (1de456b206) - Bug 1266569 - Avoid including the ChromeUtils binding in Base64.h. r=froydnj (7ba39a7687) --- b2g/app/b2g.js | 7 - b2g/chrome/content/shell.js | 38 +- b2g/installer/package-manifest.in | 4 - browser/installer/package-manifest.in | 4 - dom/apps/AppsService.js | 4 - dom/apps/AppsServiceChild.jsm | 4 - dom/apps/Webapps.jsm | 76 -- dom/apps/tests/test_widget_browser.html | 2 +- dom/base/ChromeUtils.cpp | 24 +- dom/base/Navigator.cpp | 102 -- dom/base/Navigator.h | 13 - dom/base/test/unit/test_chromeutils_base64.js | 4 +- dom/bindings/Bindings.conf | 23 - .../bluedroid/BluetoothA2dpManager.cpp | 18 +- .../bluedroid/BluetoothAvrcpManager.cpp | 22 +- .../BluetoothDaemonSocketInterface.cpp | 21 +- .../bluedroid/BluetoothGattManager.cpp | 18 +- .../bluedroid/BluetoothHidManager.cpp | 18 +- .../bluedroid/BluetoothOppManager.cpp | 13 +- dom/bluetooth/bluedroid/BluetoothSocket.cpp | 52 +- .../BluetoothSocketMessageWatcher.cpp | 8 +- .../bluedroid/BluetoothSocketMessageWatcher.h | 8 +- .../bluedroid/hfp/BluetoothHfpManager.cpp | 41 +- dom/bluetooth/bluez/BluetoothDBusService.cpp | 352 ++++--- dom/bluetooth/bluez/BluetoothHfpManager.cpp | 39 +- dom/bluetooth/bluez/BluetoothOppManager.cpp | 11 +- dom/bluetooth/bluez/BluetoothSocket.cpp | 53 +- dom/bluetooth/common/BluetoothReplyRunnable.h | 4 +- dom/bluetooth/common/BluetoothService.cpp | 4 +- dom/bluetooth/common/BluetoothService.h | 2 +- .../common/webapi/BluetoothGattServer.cpp | 6 +- dom/camera/TestGonkCameraHardware.cpp | 4 +- dom/crypto/CryptoBuffer.cpp | 10 +- dom/datastore/DataStore.manifest | 2 - dom/datastore/DataStoreCallbacks.h | 54 - dom/datastore/DataStoreChangeNotifier.jsm | 223 ---- dom/datastore/DataStoreCursor.cpp | 79 -- dom/datastore/DataStoreCursor.h | 59 -- dom/datastore/DataStoreCursorImpl.jsm | 444 -------- dom/datastore/DataStoreDB.h | 80 -- dom/datastore/DataStoreDB.jsm | 118 --- dom/datastore/DataStoreImpl.js | 549 ---------- dom/datastore/DataStoreRevision.cpp | 100 -- dom/datastore/DataStoreRevision.h | 50 - dom/datastore/moz.build | 50 - dom/datastore/tests/file_app.sjs | 55 - dom/datastore/tests/file_app.template.webapp | 10 - dom/datastore/tests/file_app2.template.webapp | 10 - dom/datastore/tests/file_app_install.html | 91 -- dom/datastore/tests/file_arrays.html | 110 -- dom/datastore/tests/file_basic.html | 31 - dom/datastore/tests/file_basic_common.js | 119 --- dom/datastore/tests/file_basic_worker.html | 30 - dom/datastore/tests/file_basic_worker.js | 19 - dom/datastore/tests/file_bug1008044.html | 46 - dom/datastore/tests/file_bug1058108.html | 40 - dom/datastore/tests/file_bug924104.html | 77 -- dom/datastore/tests/file_bug957086.html | 34 - dom/datastore/tests/file_bug976311.html | 88 -- .../tests/file_bug976311.template.webapp | 12 - dom/datastore/tests/file_bug986056.html | 26 - .../tests/file_bug986056.template.webapp | 12 - dom/datastore/tests/file_certifiedApp.html | 25 - dom/datastore/tests/file_changes.html | 148 --- dom/datastore/tests/file_changes2.html | 51 - dom/datastore/tests/file_duplicate.html | 75 -- dom/datastore/tests/file_event_maker.html | 32 - dom/datastore/tests/file_event_receiver.html | 45 - dom/datastore/tests/file_keys.html | 161 --- .../tests/file_notify_system_message.html | 120 --- dom/datastore/tests/file_readonly.html | 72 -- dom/datastore/tests/file_sync.html | 31 - dom/datastore/tests/file_sync_common.js | 461 -------- dom/datastore/tests/file_sync_worker.html | 30 - dom/datastore/tests/file_sync_worker.js | 19 - dom/datastore/tests/file_transactions.html | 129 --- dom/datastore/tests/file_worker_close.html | 29 - dom/datastore/tests/file_worker_close.js | 18 - dom/datastore/tests/mochitest.ini | 64 -- dom/datastore/tests/test_sync.html | 128 --- dom/datastore/tests/test_sync_worker.html | 128 --- .../test/test_all_synthetic_events.html | 4 - dom/fmradio/FMRadioService.h | 2 +- dom/indexedDB/IDBFactory.cpp | 25 - dom/indexedDB/IDBFactory.h | 5 - dom/interfaces/apps/nsIAppsService.idl | 5 - dom/ipc/ContentChild.cpp | 19 - dom/ipc/ContentChild.h | 4 - dom/ipc/ContentParent.cpp | 23 - dom/ipc/ContentParent.h | 12 - dom/ipc/NuwaChild.cpp | 6 +- dom/ipc/PContent.ipdl | 14 - dom/ipc/PreallocatedProcessManager.cpp | 4 +- .../SystemMessagePermissionsChecker.jsm | 37 - dom/moz.build | 1 - dom/nfc/gonk/NfcService.cpp | 12 +- dom/push/PushManager.cpp | 4 +- dom/push/PushSubscription.cpp | 8 +- dom/push/PushUtil.cpp | 22 +- dom/push/PushUtil.h | 8 + dom/system/gonk/AudioManager.cpp | 306 +++--- dom/system/gonk/AudioManager.h | 53 +- dom/system/gonk/AutoMounter.cpp | 14 +- dom/system/gonk/AutoMounterSetting.cpp | 4 +- .../gonk/GonkGPSGeolocationProvider.cpp | 121 ++- dom/system/gonk/MozMtpDatabase.cpp | 2 +- dom/system/gonk/MozMtpServer.cpp | 8 +- dom/system/gonk/NetworkWorker.cpp | 6 +- dom/system/gonk/VolumeManager.cpp | 5 +- dom/system/gonk/VolumeServiceTest.cpp | 2 +- dom/system/gonk/android_audio/AudioSystem.h | 17 + dom/system/gonk/mozstumbler/MozStumbler.cpp | 2 +- .../gonk/mozstumbler/UploadStumbleRunnable.h | 2 +- .../gonk/mozstumbler/WriteStumbleOnThread.cpp | 2 +- .../gonk/mozstumbler/WriteStumbleOnThread.h | 2 +- dom/system/gonk/nsVolume.cpp | 4 - dom/system/gonk/nsVolumeService.cpp | 4 +- .../mochitest/general/test_interfaces.html | 6 - dom/webidl/DataStore.webidl | 112 -- dom/webidl/DataStoreChangeEvent.webidl | 24 - dom/webidl/DataStoreImpl.webidl | 61 -- dom/webidl/Navigator.webidl | 10 - dom/webidl/WorkerNavigator.webidl | 1 - dom/webidl/moz.build | 3 - dom/wifi/WifiProxyService.cpp | 22 +- dom/wifi/WifiUtils.cpp | 8 +- dom/wifi/WifiUtils.h | 8 +- dom/wifi/WifiWorker.js | 20 +- dom/workers/DataStore.cpp | 989 ------------------ dom/workers/DataStore.h | 138 --- dom/workers/DataStoreCursor.cpp | 202 ---- dom/workers/DataStoreCursor.h | 66 -- dom/workers/ServiceWorkerEvents.cpp | 90 +- dom/workers/ServiceWorkerEvents.h | 8 +- dom/workers/ServiceWorkerManager.cpp | 90 -- dom/workers/ServiceWorkerPrivate.cpp | 9 +- dom/workers/ServiceWorkerRegistrationInfo.cpp | 33 + dom/workers/ServiceWorkerUpdateJob.cpp | 66 ++ dom/workers/WorkerNavigator.cpp | 252 +---- dom/workers/WorkerNavigator.h | 9 - dom/workers/moz.build | 4 - dom/workers/test/navigator_worker.js | 11 +- .../test_serviceworker_interfaces.js | 4 - dom/workers/test/test_navigator.html | 6 - dom/workers/test/test_worker_interfaces.js | 4 - hal/gonk/GonkDiskSpaceWatcher.cpp | 6 +- hal/gonk/GonkFMRadio.cpp | 2 +- hal/gonk/GonkHal.cpp | 8 +- hal/gonk/GonkSensor.cpp | 6 +- hal/gonk/GonkSwitch.cpp | 19 +- hal/gonk/UeventPoller.cpp | 15 +- ipc/glue/ProcessUtils_linux.cpp | 16 +- ipc/hal/DaemonRunnables.h | 2 +- ipc/hal/DaemonSocket.cpp | 6 +- ipc/netd/Netd.cpp | 8 +- ipc/netd/Netd.h | 4 +- ipc/ril/RilSocket.cpp | 33 +- ipc/unixsocket/ConnectionOrientedSocket.cpp | 6 +- ipc/unixsocket/DataSocket.cpp | 16 +- ipc/unixsocket/DataSocket.h | 4 +- ipc/unixsocket/ListenSocket.cpp | 11 +- ipc/unixsocket/SocketBase.cpp | 22 +- ipc/unixsocket/SocketBase.h | 17 +- ipc/unixsocket/StreamSocket.cpp | 44 +- layout/build/nsLayoutModule.cpp | 10 - layout/build/nsLayoutStatics.cpp | 3 - modules/libpref/init/all.js | 3 - netwerk/protocol/rtsp/RtspChannelChild.cpp | 4 +- .../rtsp/controller/RtspController.cpp | 6 +- .../rtsp/controller/RtspControllerChild.cpp | 2 +- testing/mochitest/manifest.webapp | 4 - .../fetch-event-redirect.https.html | 25 +- .../fetch-event-redirect-iframe.html | 5 +- .../resources/update-recovery-worker.py | 25 + .../service-worker/update-recovery.https.html | 71 ++ toolkit/identity/IdentityCryptoService.cpp | 12 +- toolkit/xre/EventTracer.cpp | 2 +- widget/gonk/GonkPermission.cpp | 2 +- widget/gonk/HwcComposer2D.cpp | 2 +- widget/gonk/WidgetTraceEvent.cpp | 2 +- .../gonk/nativewindow/FakeSurfaceComposer.cpp | 11 +- .../gonk/nativewindow/GonkBufferQueueJB.cpp | 10 +- .../gonk/nativewindow/GonkBufferQueueKK.cpp | 10 +- .../GonkBufferQueueLL/GonkBufferQueueCore.cpp | 5 +- .../GonkBufferQueueProducer.cpp | 5 +- .../gonk/nativewindow/GonkNativeWindowICS.cpp | 15 +- widget/gonk/nsAppShell.cpp | 2 +- widget/gonk/nsScreenManagerGonk.cpp | 7 +- widget/gonk/nsScreenManagerGonk.h | 6 +- widget/gonk/nsWindow.cpp | 13 +- xpcom/build/Omnijar.cpp | 35 +- xpcom/build/Omnijar.h | 44 +- xpcom/idl-parser/xpidl/typelib.py | 4 +- xpcom/io/Base64.cpp | 19 +- xpcom/io/Base64.h | 17 +- xpcom/threads/StateMirroring.h | 2 + xpcom/threads/moz.build | 7 +- xpcom/threads/nsThread.cpp | 2 +- xpcom/typelib/xpt/tools/runtests.py | 63 +- 199 files changed, 1344 insertions(+), 7774 deletions(-) delete mode 100644 dom/datastore/DataStore.manifest delete mode 100644 dom/datastore/DataStoreCallbacks.h delete mode 100644 dom/datastore/DataStoreChangeNotifier.jsm delete mode 100644 dom/datastore/DataStoreCursor.cpp delete mode 100644 dom/datastore/DataStoreCursor.h delete mode 100644 dom/datastore/DataStoreCursorImpl.jsm delete mode 100644 dom/datastore/DataStoreDB.h delete mode 100644 dom/datastore/DataStoreDB.jsm delete mode 100644 dom/datastore/DataStoreImpl.js delete mode 100644 dom/datastore/DataStoreRevision.cpp delete mode 100644 dom/datastore/DataStoreRevision.h delete mode 100644 dom/datastore/moz.build delete mode 100644 dom/datastore/tests/file_app.sjs delete mode 100644 dom/datastore/tests/file_app.template.webapp delete mode 100644 dom/datastore/tests/file_app2.template.webapp delete mode 100644 dom/datastore/tests/file_app_install.html delete mode 100644 dom/datastore/tests/file_arrays.html delete mode 100644 dom/datastore/tests/file_basic.html delete mode 100644 dom/datastore/tests/file_basic_common.js delete mode 100644 dom/datastore/tests/file_basic_worker.html delete mode 100644 dom/datastore/tests/file_basic_worker.js delete mode 100644 dom/datastore/tests/file_bug1008044.html delete mode 100644 dom/datastore/tests/file_bug1058108.html delete mode 100644 dom/datastore/tests/file_bug924104.html delete mode 100644 dom/datastore/tests/file_bug957086.html delete mode 100644 dom/datastore/tests/file_bug976311.html delete mode 100644 dom/datastore/tests/file_bug976311.template.webapp delete mode 100644 dom/datastore/tests/file_bug986056.html delete mode 100644 dom/datastore/tests/file_bug986056.template.webapp delete mode 100644 dom/datastore/tests/file_certifiedApp.html delete mode 100644 dom/datastore/tests/file_changes.html delete mode 100644 dom/datastore/tests/file_changes2.html delete mode 100644 dom/datastore/tests/file_duplicate.html delete mode 100644 dom/datastore/tests/file_event_maker.html delete mode 100644 dom/datastore/tests/file_event_receiver.html delete mode 100644 dom/datastore/tests/file_keys.html delete mode 100644 dom/datastore/tests/file_notify_system_message.html delete mode 100644 dom/datastore/tests/file_readonly.html delete mode 100644 dom/datastore/tests/file_sync.html delete mode 100644 dom/datastore/tests/file_sync_common.js delete mode 100644 dom/datastore/tests/file_sync_worker.html delete mode 100644 dom/datastore/tests/file_sync_worker.js delete mode 100644 dom/datastore/tests/file_transactions.html delete mode 100644 dom/datastore/tests/file_worker_close.html delete mode 100644 dom/datastore/tests/file_worker_close.js delete mode 100644 dom/datastore/tests/mochitest.ini delete mode 100644 dom/datastore/tests/test_sync.html delete mode 100644 dom/datastore/tests/test_sync_worker.html delete mode 100644 dom/webidl/DataStore.webidl delete mode 100644 dom/webidl/DataStoreChangeEvent.webidl delete mode 100644 dom/webidl/DataStoreImpl.webidl delete mode 100644 dom/workers/DataStore.cpp delete mode 100644 dom/workers/DataStore.h delete mode 100644 dom/workers/DataStoreCursor.cpp delete mode 100644 dom/workers/DataStoreCursor.h create mode 100644 testing/web-platform/tests/service-workers/service-worker/resources/update-recovery-worker.py create mode 100644 testing/web-platform/tests/service-workers/service-worker/update-recovery.https.html diff --git a/b2g/app/b2g.js b/b2g/app/b2g.js index aec584c084..142af0ca93 100644 --- a/b2g/app/b2g.js +++ b/b2g/app/b2g.js @@ -910,13 +910,6 @@ pref("network.sntp.pools", // Servers separated by ';'. pref("network.sntp.port", 123); pref("network.sntp.timeout", 30); // In seconds. -// Enable dataStore -pref("dom.datastore.enabled", true); -// When an entry is changed, use two timers to fire system messages in a more -// moderate pattern. -pref("dom.datastore.sysMsgOnChangeShortTimeoutSec", 10); -pref("dom.datastore.sysMsgOnChangeLongTimeoutSec", 60); - // DOM Inter-App Communication API. pref("dom.inter-app-communication-api.enabled", true); diff --git a/b2g/chrome/content/shell.js b/b2g/chrome/content/shell.js index 58dbdec2bc..4261bffa5f 100644 --- a/b2g/chrome/content/shell.js +++ b/b2g/chrome/content/shell.js @@ -7,7 +7,6 @@ window.performance.mark('gecko-shell-loadstart'); Cu.import('resource://gre/modules/ContactService.jsm'); -Cu.import('resource://gre/modules/DataStoreChangeNotifier.jsm'); Cu.import('resource://gre/modules/AlarmService.jsm'); Cu.import('resource://gre/modules/ActivitiesService.jsm'); Cu.import('resource://gre/modules/NotificationDB.jsm'); @@ -1064,22 +1063,49 @@ window.addEventListener('ContentStart', function update_onContentStart() { updatePrompt.wrappedJSObject.handleContentStart(shell); #endif }); +/* The "GPSChipOn" is to indicate that GPS engine is turned ON by the modem. + During this GPS engine is turned ON by the modem, we make the location tracking icon visible to user. + Once GPS engine is turned OFF, the location icon will disappear. + If GPS engine is not turned ON by the modem or GPS location service is triggered, + we let GPS service take over the control of showing the location tracking icon. + The regular sequence of the geolocation-device-events is: starting-> GPSStarting-> shutdown-> GPSShutdown +*/ (function geolocationStatusTracker() { let gGeolocationActive = false; + let GPSChipOn = false; Services.obs.addObserver(function(aSubject, aTopic, aData) { let oldState = gGeolocationActive; - if (aData == "starting") { - gGeolocationActive = true; - } else if (aData == "shutdown") { - gGeolocationActive = false; + let promptWarning = false; + switch (aData) { + case "GPSStarting": + if (!gGeolocationActive) { + gGeolocationActive = true; + GPSChipOn = true; + promptWarning = true; + } + break; + case "GPSShutdown": + if (GPSChipOn) { + gGeolocationActive = false; + GPSChipOn = false; + } + break; + case "starting": + gGeolocationActive = true; + GPSChipOn = false; + break; + case "shutdown": + gGeolocationActive = false; + break; } if (gGeolocationActive != oldState) { shell.sendChromeEvent({ type: 'geolocation-status', - active: gGeolocationActive + active: gGeolocationActive, + prompt: promptWarning }); } }, "geolocation-device-events", false); diff --git a/b2g/installer/package-manifest.in b/b2g/installer/package-manifest.in index 8d62b81c2c..2195a44454 100644 --- a/b2g/installer/package-manifest.in +++ b/b2g/installer/package-manifest.in @@ -938,10 +938,6 @@ bin/libfreebl_32int64_3.so @RESPATH@/components/FxAccountsUIGlue.js @RESPATH@/components/services_fxaccounts.xpt -@RESPATH@/components/DataStore.manifest -@RESPATH@/components/DataStoreImpl.js -@RESPATH@/components/dom_datastore.xpt - @RESPATH@/components/MobileIdentity.manifest @RESPATH@/components/MobileIdentity.js @RESPATH@/components/dom_mobileidentity.xpt diff --git a/browser/installer/package-manifest.in b/browser/installer/package-manifest.in index 2f179ad973..1c49b568eb 100644 --- a/browser/installer/package-manifest.in +++ b/browser/installer/package-manifest.in @@ -815,10 +815,6 @@ bin/libfreebl_32int64_3.so #endif #endif -@RESPATH@/components/DataStore.manifest -@RESPATH@/components/DataStoreImpl.js -@RESPATH@/components/dom_datastore.xpt - @RESPATH@/components/dom_audiochannel.xpt ; Shutdown Terminator diff --git a/dom/apps/AppsService.js b/dom/apps/AppsService.js index a8fbfe368f..1263e0b193 100644 --- a/dom/apps/AppsService.js +++ b/dom/apps/AppsService.js @@ -170,10 +170,6 @@ AppsService.prototype = { return UserCustomizations.isFromExtension(aURI); }, - updateDataStoreEntriesFromLocalId: function(aLocalId) { - return DOMApplicationRegistry.updateDataStoreEntriesFromLocalId(aLocalId); - }, - classID : APPS_SERVICE_CID, QueryInterface : XPCOMUtils.generateQI([Ci.nsIAppsService]) } diff --git a/dom/apps/AppsServiceChild.jsm b/dom/apps/AppsServiceChild.jsm index fe1243bfbe..c89df36aab 100644 --- a/dom/apps/AppsServiceChild.jsm +++ b/dom/apps/AppsServiceChild.jsm @@ -419,10 +419,6 @@ this.DOMApplicationRegistry = { getAppInfo: function getAppInfo(aAppId) { return AppsUtils.getAppInfo(this.webapps, aAppId); - }, - - updateDataStoreEntriesFromLocalId: function(aLocalId) { - debug("updateDataStoreEntriesFromLocalId() not yet supported on child!"); } } diff --git a/dom/apps/Webapps.jsm b/dom/apps/Webapps.jsm index 6bc82b328f..e2b7f26d25 100755 --- a/dom/apps/Webapps.jsm +++ b/dom/apps/Webapps.jsm @@ -149,10 +149,6 @@ XPCOMUtils.defineLazyGetter(this, "interAppCommService", function() { .getService(Ci.nsIInterAppCommService); }); -XPCOMUtils.defineLazyServiceGetter(this, "dataStoreService", - "@mozilla.org/datastore-service;1", - "nsIDataStoreService"); - XPCOMUtils.defineLazyServiceGetter(this, "appsService", "@mozilla.org/AppsService;1", "nsIAppsService"); @@ -452,18 +448,6 @@ this.DOMApplicationRegistry = { } }), - updateDataStoreForApp: Task.async(function*(aId) { - if (!this.webapps[aId]) { - return; - } - - // Create or Update the DataStore for this app - let results = yield this._readManifests([{ id: aId }]); - let app = this.webapps[aId]; - this.updateDataStore(app.localId, app.origin, app.manifestURL, - results[0].manifest, app.appStatus); - }), - appKind: function(aApp, aManifest) { if (aApp.origin.startsWith("android://")) { return this.kAndroid; @@ -815,52 +799,10 @@ this.DOMApplicationRegistry = { Services.prefs.setBoolPref("dom.apps.reset-permissions", true); } - // DataStores must be initialized at startup. - for (let id in this.webapps) { - yield this.updateDataStoreForApp(id); - } - yield this.registerAppsHandlers(runUpdate); }.bind(this)).then(null, Cu.reportError); }, - updateDataStore: function(aId, aOrigin, aManifestURL, aManifest) { - if (!aManifest) { - debug("updateDataStore: no manifest for " + aOrigin); - return; - } - - let uri = Services.io.newURI(aOrigin, null, null); - let secMan = Cc["@mozilla.org/scriptsecuritymanager;1"] - .getService(Ci.nsIScriptSecurityManager); - let principal = secMan.createCodebasePrincipal(uri, {appId: aId}); - if (!dataStoreService.checkPermission(principal)) { - return; - } - - if ('datastores-owned' in aManifest) { - for (let name in aManifest['datastores-owned']) { - let readonly = "access" in aManifest['datastores-owned'][name] - ? aManifest['datastores-owned'][name].access == 'readonly' - : false; - - dataStoreService.installDataStore(aId, name, aOrigin, aManifestURL, - readonly); - } - } - - if ('datastores-access' in aManifest) { - for (let name in aManifest['datastores-access']) { - let readonly = ("readonly" in aManifest['datastores-access'][name]) && - !aManifest['datastores-access'][name].readonly - ? false : true; - - dataStoreService.installAccessDataStore(aId, name, aOrigin, - aManifestURL, readonly); - } - } - }, - // |aEntryPoint| is either the entry_point name or the null in which case we // use the root of the manifest. // @@ -1927,8 +1869,6 @@ this.DOMApplicationRegistry = { kind: app.kind }, true); } - this.updateDataStore(this.webapps[id].localId, app.origin, - app.manifestURL, newManifest); MessageBroadcaster.broadcastMessage("Webapps:UpdateState", { app: app, manifest: newManifest, @@ -2373,9 +2313,6 @@ this.DOMApplicationRegistry = { }, true); } - this.updateDataStore(this.webapps[aId].localId, aApp.origin, - aApp.manifestURL, aApp.manifest); - aApp.name = aNewManifest.name; aApp.csp = manifest.csp || ""; aApp.updateTime = Date.now(); @@ -3015,9 +2952,6 @@ this.DOMApplicationRegistry = { this.doUninstall.bind(this, aData, aData.mm) ); } - - this.updateDataStore(this.webapps[id].localId, this.webapps[id].origin, - this.webapps[id].manifestURL, jsonManifest); } for (let prop of ["installState", "downloadAvailable", "downloading", @@ -3162,9 +3096,6 @@ this.DOMApplicationRegistry = { }, true); } - this.updateDataStore(this.webapps[aId].localId, aNewApp.origin, - aNewApp.manifestURL, aManifest); - if (aInstallSuccessCallback) { try { yield aInstallSuccessCallback(aNewApp, aManifest, zipFile.path); @@ -4676,13 +4607,6 @@ this.DOMApplicationRegistry = { return AppsUtils.areAnyAppsInstalled(this.webapps); }, - updateDataStoreEntriesFromLocalId: function(aLocalId) { - let app = appsService.getAppByLocalId(aLocalId); - if (app) { - this.updateDataStoreForApp(app.id); - } - }, - _isLaunchable: function(aApp) { return true; }, diff --git a/dom/apps/tests/test_widget_browser.html b/dom/apps/tests/test_widget_browser.html index 366953dff8..4270f278c1 100644 --- a/dom/apps/tests/test_widget_browser.html +++ b/dom/apps/tests/test_widget_browser.html @@ -2,7 +2,7 @@ - Test for DataStore - basic operation on a readonly db + ?!? diff --git a/dom/base/ChromeUtils.cpp b/dom/base/ChromeUtils.cpp index a0ed93b3eb..d9da48242b 100644 --- a/dom/base/ChromeUtils.cpp +++ b/dom/base/ChromeUtils.cpp @@ -74,7 +74,9 @@ ThreadSafeChromeUtils::Base64URLEncode(GlobalObject& aGlobal, MOZ_CRASH("Uninitialized union: expected buffer or view"); } - nsresult rv = mozilla::Base64URLEncode(length, data, aOptions, aResult); + auto paddingPolicy = aOptions.mPad ? Base64URLEncodePaddingPolicy::Include : + Base64URLEncodePaddingPolicy::Omit; + nsresult rv = mozilla::Base64URLEncode(length, data, paddingPolicy, aResult); if (NS_WARN_IF(NS_FAILED(rv))) { aResult.Truncate(); aRv.Throw(rv); @@ -88,8 +90,26 @@ ThreadSafeChromeUtils::Base64URLDecode(GlobalObject& aGlobal, JS::MutableHandle aRetval, ErrorResult& aRv) { + Base64URLDecodePaddingPolicy paddingPolicy; + switch (aOptions.mPadding) { + case Base64URLDecodePadding::Require: + paddingPolicy = Base64URLDecodePaddingPolicy::Require; + break; + + case Base64URLDecodePadding::Ignore: + paddingPolicy = Base64URLDecodePaddingPolicy::Ignore; + break; + + case Base64URLDecodePadding::Reject: + paddingPolicy = Base64URLDecodePaddingPolicy::Reject; + break; + + default: + aRv.Throw(NS_ERROR_INVALID_ARG); + return; + } FallibleTArray data; - nsresult rv = mozilla::Base64URLDecode(aString, aOptions, data); + nsresult rv = mozilla::Base64URLDecode(aString, paddingPolicy, data); if (NS_WARN_IF(NS_FAILED(rv))) { aRv.Throw(rv); return; diff --git a/dom/base/Navigator.cpp b/dom/base/Navigator.cpp index d4e8341b21..d083e18ef2 100644 --- a/dom/base/Navigator.cpp +++ b/dom/base/Navigator.cpp @@ -95,7 +95,6 @@ #endif #include "nsIDOMGlobalPropertyInitializer.h" -#include "mozilla/dom/DataStoreService.h" #include "nsJSUtils.h" #include "nsScriptNameSpaceManager.h" @@ -1503,38 +1502,6 @@ Navigator::GetDeprecatedBattery(ErrorResult& aRv) return mBatteryManager; } -/* static */ already_AddRefed -Navigator::GetDataStores(nsPIDOMWindow* aWindow, - const nsAString& aName, - const nsAString& aOwner, - ErrorResult& aRv) -{ - if (!aWindow || !aWindow->GetDocShell()) { - aRv.Throw(NS_ERROR_UNEXPECTED); - return nullptr; - } - - RefPtr service = DataStoreService::GetOrCreate(); - if (!service) { - aRv.Throw(NS_ERROR_FAILURE); - return nullptr; - } - - nsCOMPtr promise; - aRv = service->GetDataStores(aWindow, aName, aOwner, getter_AddRefs(promise)); - - RefPtr p = static_cast(promise.get()); - return p.forget(); -} - -already_AddRefed -Navigator::GetDataStores(const nsAString& aName, - const nsAString& aOwner, - ErrorResult& aRv) -{ - return GetDataStores(mWindow, aName, aOwner, aRv); -} - already_AddRefed Navigator::GetFeature(const nsAString& aName, ErrorResult& aRv) { @@ -2294,75 +2261,6 @@ Navigator::HasUserMediaSupport(JSContext* /* unused */, Preferences::GetBool("media.peerconnection.enabled", false); } -/* static */ -bool -Navigator::HasDataStoreSupport(nsIPrincipal* aPrincipal) -{ - workers::AssertIsOnMainThread(); - - return DataStoreService::CheckPermission(aPrincipal); -} - -// A WorkerMainThreadRunnable to synchronously dispatch the call of -// HasDataStoreSupport() from the worker thread to the main thread. -class HasDataStoreSupportRunnable final - : public workers::WorkerCheckAPIExposureOnMainThreadRunnable -{ -public: - bool mResult; - - explicit HasDataStoreSupportRunnable(workers::WorkerPrivate* aWorkerPrivate) - : workers::WorkerCheckAPIExposureOnMainThreadRunnable(aWorkerPrivate) - , mResult(false) - { - MOZ_ASSERT(aWorkerPrivate); - aWorkerPrivate->AssertIsOnWorkerThread(); - } - -protected: - virtual bool - MainThreadRun() override - { - workers::AssertIsOnMainThread(); - - mResult = Navigator::HasDataStoreSupport(mWorkerPrivate->GetPrincipal()); - - return true; - } -}; - -/* static */ -bool -Navigator::HasDataStoreSupport(JSContext* aCx, JSObject* aGlobal) -{ - // If the caller is on the worker thread, dispatch this to the main thread. - if (!NS_IsMainThread()) { - workers::WorkerPrivate* workerPrivate = - workers::GetWorkerPrivateFromContext(aCx); - workerPrivate->AssertIsOnWorkerThread(); - - RefPtr runnable = - new HasDataStoreSupportRunnable(workerPrivate); - return runnable->Dispatch() && runnable->mResult; - } - - workers::AssertIsOnMainThread(); - - JS::Rooted global(aCx, aGlobal); - - nsCOMPtr win = GetWindowFromGlobal(global); - if (!win) { - return false; - } - - nsIDocument* doc = win->GetExtantDoc(); - if (!doc || !doc->NodePrincipal()) { - return false; - } - - return HasDataStoreSupport(doc->NodePrincipal()); -} - #ifdef MOZ_B2G /* static */ bool diff --git a/dom/base/Navigator.h b/dom/base/Navigator.h index ad88c90a7c..1f4e29792b 100644 --- a/dom/base/Navigator.h +++ b/dom/base/Navigator.h @@ -164,11 +164,6 @@ public: Promise* GetBattery(ErrorResult& aRv); battery::BatteryManager* GetDeprecatedBattery(ErrorResult& aRv); - static already_AddRefed GetDataStores(nsPIDOMWindow* aWindow, - const nsAString& aName, - const nsAString& aOwner, - ErrorResult& aRv); - static void AppName(nsAString& aAppName, bool aUsePrefOverriddenValue); static nsresult GetPlatform(nsAString& aPlatform, @@ -186,10 +181,6 @@ public: // NavigatorBinding::ClearCachedUserAgentValue(this); void ClearUserAgentCache(); - already_AddRefed GetDataStores(const nsAString& aName, - const nsAString& aOwner, - ErrorResult& aRv); - // Feature Detection API already_AddRefed GetFeature(const nsAString& aName, ErrorResult& aRv); @@ -326,10 +317,6 @@ public: static bool HasUserMediaSupport(JSContext* /* unused */, JSObject* /* unused */); - static bool HasDataStoreSupport(nsIPrincipal* aPrincipal); - - static bool HasDataStoreSupport(JSContext* cx, JSObject* aGlobal); - #ifdef MOZ_B2G static bool HasMobileIdSupport(JSContext* aCx, JSObject* aGlobal); #endif diff --git a/dom/base/test/unit/test_chromeutils_base64.js b/dom/base/test/unit/test_chromeutils_base64.js index cc8f9907ad..361392c44d 100644 --- a/dom/base/test/unit/test_chromeutils_base64.js +++ b/dom/base/test/unit/test_chromeutils_base64.js @@ -88,8 +88,10 @@ function testDecode(input, decoded) { function test_base64URLDecode() { throws(_ => ChromeUtils.base64URLDecode(""), /TypeError/, "Should require decoding options"); - throws(_ => ChromeUtils.base64URLEncode("", {}), /TypeError/, + throws(_ => ChromeUtils.base64URLDecode("", {}), /TypeError/, "Decoding should require the padding option"); + throws(_ => ChromeUtils.base64URLDecode("", { padding: "chocolate" }), + "Decoding should throw for invalid padding policy"); for (let {decoded, encoded} of binaryTests) { testDecode(encoded, decoded); diff --git a/dom/bindings/Bindings.conf b/dom/bindings/Bindings.conf index d3dd985210..e04fdf0fc6 100644 --- a/dom/bindings/Bindings.conf +++ b/dom/bindings/Bindings.conf @@ -362,25 +362,6 @@ DOMInterfaces = { 'nativeType': 'nsDOMDataChannel', }, -'DataStore': [{ - 'workers': False -}, { - 'workers': True, - 'nativeType': 'mozilla::dom::workers::WorkerDataStore', - 'implicitJSContext': ['name', 'owner', 'readOnly', 'get', 'remove', - 'clear', 'revisionId', 'getLength', 'sync'] -}], - -'DataStoreCursor': [{ - 'workers': False, - 'wrapperCache': False -}, { - 'workers': True, - 'nativeType': 'mozilla::dom::workers::WorkerDataStoreCursor', - 'wrapperCache': False, - 'implicitJSContext': ['store', 'next', 'close'] -}], - 'DedicatedWorkerGlobalScope': { 'headerFile': 'mozilla/dom/WorkerScope.h', 'workers': True, @@ -1611,10 +1592,6 @@ DOMInterfaces = { }, }, -'WorkerNavigator': { - 'implicitJSContext': ['getDataStores'], -}, - 'XMLHttpRequest': [ { 'nativeType': 'nsXMLHttpRequest', diff --git a/dom/bluetooth/bluedroid/BluetoothA2dpManager.cpp b/dom/bluetooth/bluedroid/BluetoothA2dpManager.cpp index 48db47da3b..7191841cd7 100644 --- a/dom/bluetooth/bluedroid/BluetoothA2dpManager.cpp +++ b/dom/bluetooth/bluedroid/BluetoothA2dpManager.cpp @@ -129,7 +129,7 @@ private: }; class BluetoothA2dpManager::InitProfileResultHandlerRunnable final - : public nsRunnable + : public Runnable { public: InitProfileResultHandlerRunnable(BluetoothProfileResultHandler* aRes, @@ -171,7 +171,7 @@ BluetoothA2dpManager::InitA2dpInterface(BluetoothProfileResultHandler* aRes) if (sBtA2dpInterface) { BT_LOGR("Bluetooth A2DP interface is already initalized."); - RefPtr r = + RefPtr r = new InitProfileResultHandlerRunnable(aRes, NS_OK); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch A2DP Init runnable"); @@ -184,7 +184,7 @@ BluetoothA2dpManager::InitA2dpInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!btInf)) { // If there's no Bluetooth interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch A2DP OnError runnable"); @@ -197,7 +197,7 @@ BluetoothA2dpManager::InitA2dpInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!setupInterface)) { // If there's no Setup interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch A2DP OnError runnable"); @@ -210,7 +210,7 @@ BluetoothA2dpManager::InitA2dpInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!a2dpInterface)) { // If there's no A2DP interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch A2DP OnError runnable"); @@ -329,7 +329,7 @@ private: }; class BluetoothA2dpManager::DeinitProfileResultHandlerRunnable final - : public nsRunnable + : public Runnable { public: DeinitProfileResultHandlerRunnable(BluetoothProfileResultHandler* aRes, @@ -365,7 +365,7 @@ BluetoothA2dpManager::DeinitA2dpInterface(BluetoothProfileResultHandler* aRes) if (!sBtA2dpInterface) { BT_LOGR("Bluetooth A2DP interface has not been initalized."); - RefPtr r = + RefPtr r = new DeinitProfileResultHandlerRunnable(aRes, NS_OK); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch A2DP Deinit runnable"); @@ -378,7 +378,7 @@ BluetoothA2dpManager::DeinitA2dpInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!btInf)) { // If there's no backend interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new DeinitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch A2DP OnError runnable"); @@ -391,7 +391,7 @@ BluetoothA2dpManager::DeinitA2dpInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!setupInterface)) { // If there's no Setup interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new DeinitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch A2DP OnError runnable"); diff --git a/dom/bluetooth/bluedroid/BluetoothAvrcpManager.cpp b/dom/bluetooth/bluedroid/BluetoothAvrcpManager.cpp index 2c3e03bceb..cca192d743 100644 --- a/dom/bluetooth/bluedroid/BluetoothAvrcpManager.cpp +++ b/dom/bluetooth/bluedroid/BluetoothAvrcpManager.cpp @@ -172,7 +172,7 @@ private: }; class BluetoothAvrcpManager::InitProfileResultHandlerRunnable final - : public nsRunnable + : public Runnable { public: InitProfileResultHandlerRunnable(BluetoothProfileResultHandler* aRes, @@ -211,7 +211,7 @@ BluetoothAvrcpManager::InitAvrcpInterface(BluetoothProfileResultHandler* aRes) if (sBtAvrcpInterface) { BT_LOGR("Bluetooth AVRCP interface is already initalized."); - RefPtr r = + RefPtr r = new InitProfileResultHandlerRunnable(aRes, NS_OK); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch AVRCP Init runnable"); @@ -224,7 +224,7 @@ BluetoothAvrcpManager::InitAvrcpInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!btInf)) { // If there's no Bluetooth interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch AVRCP OnError runnable"); @@ -237,7 +237,7 @@ BluetoothAvrcpManager::InitAvrcpInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!setupInterface)) { // If there's no Setup interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch AVRCP OnError runnable"); @@ -250,7 +250,7 @@ BluetoothAvrcpManager::InitAvrcpInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!avrcpInterface)) { // If there's no AVRCP interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch AVRCP OnError runnable"); @@ -350,7 +350,7 @@ private: }; class BluetoothAvrcpManager::DeinitProfileResultHandlerRunnable final - : public nsRunnable + : public Runnable { public: DeinitProfileResultHandlerRunnable(BluetoothProfileResultHandler* aRes, @@ -386,7 +386,7 @@ BluetoothAvrcpManager::DeinitAvrcpInterface(BluetoothProfileResultHandler* aRes) if (!sBtAvrcpInterface) { BT_LOGR("Bluetooth AVRCP interface has not been initalized."); - RefPtr r = + RefPtr r = new DeinitProfileResultHandlerRunnable(aRes, NS_OK); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch AVRCP Deinit runnable"); @@ -399,7 +399,7 @@ BluetoothAvrcpManager::DeinitAvrcpInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!btInf)) { // If there's no backend interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new DeinitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch AVRCP OnError runnable"); @@ -412,7 +412,7 @@ BluetoothAvrcpManager::DeinitAvrcpInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!setupInterface)) { // If there's no Setup interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new DeinitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch AVRCP OnError runnable"); @@ -434,7 +434,7 @@ BluetoothAvrcpManager::HandleShutdown() sBluetoothAvrcpManager = nullptr; } -class BluetoothAvrcpManager::ConnectRunnable final : public nsRunnable +class BluetoothAvrcpManager::ConnectRunnable final : public Runnable { public: ConnectRunnable(BluetoothAvrcpManager* aManager) @@ -467,7 +467,7 @@ BluetoothAvrcpManager::Connect(const BluetoothAddress& aDeviceAddress, NS_DispatchToMainThread(new ConnectRunnable(this)); } -class BluetoothAvrcpManager::DisconnectRunnable final : public nsRunnable +class BluetoothAvrcpManager::DisconnectRunnable final : public Runnable { public: DisconnectRunnable(BluetoothAvrcpManager* aManager) diff --git a/dom/bluetooth/bluedroid/BluetoothDaemonSocketInterface.cpp b/dom/bluetooth/bluedroid/BluetoothDaemonSocketInterface.cpp index 4bf5ca13eb..01321562d2 100644 --- a/dom/bluetooth/bluedroid/BluetoothDaemonSocketInterface.cpp +++ b/dom/bluetooth/bluedroid/BluetoothDaemonSocketInterface.cpp @@ -88,16 +88,17 @@ BluetoothDaemonSocketModule::ConnectCmd(const BluetoothAddress& aBdAddr, /* |DeleteTask| deletes a class instance on the I/O thread */ template -class DeleteTask final : public Task +class DeleteTask final : public Runnable { public: DeleteTask(T* aPtr) : mPtr(aPtr) { } - void Run() override + NS_IMETHOD Run() override { mPtr = nullptr; + return NS_OK; } private: @@ -134,7 +135,7 @@ public: } MessageLoopForIO::current()->PostTask( - FROM_HERE, new DeleteTask(this)); + MakeAndAddRef>(this)); } }; @@ -145,8 +146,8 @@ BluetoothDaemonSocketModule::AcceptCmd(int aFd, MOZ_ASSERT(NS_IsMainThread()); /* receive Bluedroid's socket-setup messages and client fd */ - Task* t = new SocketMessageWatcherTask(new AcceptWatcher(aFd, aRes)); - XRE_GetIOMessageLoop()->PostTask(FROM_HERE, t); + XRE_GetIOMessageLoop()->PostTask( + MakeAndAddRef(new AcceptWatcher(aFd, aRes))); return NS_OK; } @@ -157,8 +158,8 @@ BluetoothDaemonSocketModule::CloseCmd(BluetoothSocketResultHandler* aRes) MOZ_ASSERT(NS_IsMainThread()); /* stop the watcher corresponding to |aRes| */ - Task* t = new DeleteSocketMessageWatcherTask(aRes); - XRE_GetIOMessageLoop()->PostTask(FROM_HERE, t); + XRE_GetIOMessageLoop()->PostTask( + MakeAndAddRef(aRes)); return NS_OK; } @@ -273,7 +274,7 @@ public: } MessageLoopForIO::current()->PostTask( - FROM_HERE, new DeleteTask(this)); + MakeAndAddRef>(this)); } }; @@ -298,8 +299,8 @@ BluetoothDaemonSocketModule::ConnectRsp(const DaemonSocketPDUHeader& aHeader, } /* receive Bluedroid's socket-setup messages */ - Task* t = new SocketMessageWatcherTask(new ConnectWatcher(fd, aRes)); - XRE_GetIOMessageLoop()->PostTask(FROM_HERE, t); + XRE_GetIOMessageLoop()->PostTask( + MakeAndAddRef(new ConnectWatcher(fd, aRes))); } // diff --git a/dom/bluetooth/bluedroid/BluetoothGattManager.cpp b/dom/bluetooth/bluedroid/BluetoothGattManager.cpp index 5c8eb6b2a6..969b5ed710 100644 --- a/dom/bluetooth/bluedroid/BluetoothGattManager.cpp +++ b/dom/bluetooth/bluedroid/BluetoothGattManager.cpp @@ -465,7 +465,7 @@ private: }; class BluetoothGattManager::InitProfileResultHandlerRunnable final - : public nsRunnable + : public Runnable { public: InitProfileResultHandlerRunnable(BluetoothProfileResultHandler* aRes, @@ -501,7 +501,7 @@ BluetoothGattManager::InitGattInterface(BluetoothProfileResultHandler* aRes) if (sBluetoothGattInterface) { BT_LOGR("Bluetooth GATT interface is already initalized."); - RefPtr r = + RefPtr r = new InitProfileResultHandlerRunnable(aRes, NS_OK); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch GATT Init runnable"); @@ -514,7 +514,7 @@ BluetoothGattManager::InitGattInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!btInf)) { // If there's no Bluetooth interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch GATT OnError runnable"); @@ -527,7 +527,7 @@ BluetoothGattManager::InitGattInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!setupInterface)) { // If there's no Setup interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch GATT OnError runnable"); @@ -540,7 +540,7 @@ BluetoothGattManager::InitGattInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!gattInterface)) { // If there's no GATT interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch GATT OnError runnable"); @@ -615,7 +615,7 @@ private: }; class BluetoothGattManager::DeinitProfileResultHandlerRunnable final - : public nsRunnable + : public Runnable { public: DeinitProfileResultHandlerRunnable(BluetoothProfileResultHandler* aRes, @@ -651,7 +651,7 @@ BluetoothGattManager::DeinitGattInterface(BluetoothProfileResultHandler* aRes) if (!sBluetoothGattInterface) { BT_LOGR("Bluetooth GATT interface has not been initalized."); - RefPtr r = + RefPtr r = new DeinitProfileResultHandlerRunnable(aRes, NS_OK); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch GATT Deinit runnable"); @@ -664,7 +664,7 @@ BluetoothGattManager::DeinitGattInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!btInf)) { // If there's no backend interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new DeinitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch GATT OnError runnable"); @@ -677,7 +677,7 @@ BluetoothGattManager::DeinitGattInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!setupInterface)) { // If there's no Setup interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new DeinitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch GATT OnError runnable"); diff --git a/dom/bluetooth/bluedroid/BluetoothHidManager.cpp b/dom/bluetooth/bluedroid/BluetoothHidManager.cpp index 954bf5b263..6981b37de2 100644 --- a/dom/bluetooth/bluedroid/BluetoothHidManager.cpp +++ b/dom/bluetooth/bluedroid/BluetoothHidManager.cpp @@ -78,7 +78,7 @@ private: }; class BluetoothHidManager::InitProfileResultHandlerRunnable final - : public nsRunnable + : public Runnable { public: InitProfileResultHandlerRunnable(BluetoothProfileResultHandler* aRes, @@ -114,7 +114,7 @@ BluetoothHidManager::InitHidInterface(BluetoothProfileResultHandler* aRes) if (sBluetoothHidInterface) { BT_LOGR("Bluetooth HID interface is already initialized."); - RefPtr r = + RefPtr r = new InitProfileResultHandlerRunnable(aRes, NS_OK); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch HID Init runnable"); @@ -127,7 +127,7 @@ BluetoothHidManager::InitHidInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!btInf)) { // If there's no backend interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch HID OnError runnable"); @@ -140,7 +140,7 @@ BluetoothHidManager::InitHidInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!setupInterface)) { // If there's no Setup interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch HID OnError runnable"); @@ -153,7 +153,7 @@ BluetoothHidManager::InitHidInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!hidinterface)) { // If there's no HID interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch HID OnError runnable"); @@ -230,7 +230,7 @@ private: }; class BluetoothHidManager::DeinitProfileResultHandlerRunnable final - : public nsRunnable + : public Runnable { public: DeinitProfileResultHandlerRunnable(BluetoothProfileResultHandler* aRes, @@ -266,7 +266,7 @@ BluetoothHidManager::DeinitHidInterface(BluetoothProfileResultHandler* aRes) if (!sBluetoothHidInterface) { BT_LOGR("Bluetooth Hid interface has not been initialized."); - RefPtr r = + RefPtr r = new DeinitProfileResultHandlerRunnable(aRes, NS_OK); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch HID Deinit runnable"); @@ -279,7 +279,7 @@ BluetoothHidManager::DeinitHidInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!btInf)) { // If there's no backend interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new DeinitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch HID OnError runnable"); @@ -292,7 +292,7 @@ BluetoothHidManager::DeinitHidInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!setupInterface)) { // If there's no Setup interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new DeinitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch HID OnError runnable"); diff --git a/dom/bluetooth/bluedroid/BluetoothOppManager.cpp b/dom/bluetooth/bluedroid/BluetoothOppManager.cpp index 2ea8e2eb11..b31beaf29e 100644 --- a/dom/bluetooth/bluedroid/BluetoothOppManager.cpp +++ b/dom/bluetooth/bluedroid/BluetoothOppManager.cpp @@ -102,7 +102,7 @@ BluetoothOppManager::Observe(nsISupports* aSubject, return NS_ERROR_UNEXPECTED; } -class BluetoothOppManager::SendSocketDataTask final : public nsRunnable +class BluetoothOppManager::SendSocketDataTask final : public Runnable { public: SendSocketDataTask(UniquePtr aStream, uint32_t aSize) @@ -126,7 +126,7 @@ private: uint32_t mSize; }; -class BluetoothOppManager::ReadFileTask final : public nsRunnable +class BluetoothOppManager::ReadFileTask final : public Runnable { public: ReadFileTask(nsIInputStream* aInputStream, @@ -172,7 +172,7 @@ private: uint32_t mAvailablePacketSize; }; -class BluetoothOppManager::CloseSocketTask final : public Task +class BluetoothOppManager::CloseSocketTask final : public Runnable { public: CloseSocketTask(BluetoothSocket* aSocket) : mSocket(aSocket) @@ -180,10 +180,11 @@ public: MOZ_ASSERT(aSocket); } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(NS_IsMainThread()); mSocket->Close(); + return NS_OK; } private: @@ -1138,8 +1139,8 @@ BluetoothOppManager::ClientDataHandler(UnixSocketBuffer* aMessage) // Disconnect request, so we make a delay here. If the socket hasn't been // disconnected, we will close it. if (mSocket) { - MessageLoop::current()-> - PostDelayedTask(FROM_HERE, new CloseSocketTask(mSocket), 1000); + MessageLoop::current()->PostDelayedTask( + MakeAndAddRef(mSocket), 1000); } } else if (mLastCommand == ObexRequestCode::Connect) { MOZ_ASSERT(!mFileName.IsEmpty()); diff --git a/dom/bluetooth/bluedroid/BluetoothSocket.cpp b/dom/bluetooth/bluedroid/BluetoothSocket.cpp index 3aa040ebaa..2e868f9e8f 100644 --- a/dom/bluetooth/bluedroid/BluetoothSocket.cpp +++ b/dom/bluetooth/bluedroid/BluetoothSocket.cpp @@ -200,12 +200,14 @@ public: , mFd(aFd) { } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(!GetIO()->IsConsumerThread()); MOZ_ASSERT(!IsCanceled()); GetIO()->Connect(mFd); + + return NS_OK; } private: @@ -220,13 +222,14 @@ public: , mFd(aFd) { } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(!GetIO()->IsConsumerThread()); if (!IsCanceled()) { GetIO()->Listen(mFd); } + return NS_OK; } private: @@ -240,11 +243,13 @@ class SocketConnectClientFdTask final : SocketIOTask(aImpl) { } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(!GetIO()->IsConsumerThread()); GetIO()->ConnectClientFd(); + + return NS_OK; } }; @@ -303,7 +308,7 @@ DroidSocketImpl::Accept(int aFd) mConnectionStatus = SOCKET_IS_CONNECTED; GetConsumerThread()->PostTask( - FROM_HERE, new SocketEventTask(this, SocketEventTask::CONNECT_SUCCESS)); + MakeAndAddRef(this, SocketEventTask::CONNECT_SUCCESS)); AddWatchers(READ_WATCHER, true); if (HasPendingData()) { @@ -347,12 +352,14 @@ public: , mFd(aFd) { } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(!GetIO()->IsConsumerThread()); MOZ_ASSERT(!IsCanceled()); GetIO()->Accept(mFd); + + return NS_OK; } private: @@ -386,8 +393,8 @@ public: } mImpl->mConsumer->SetAddress(aBdAddress); - mImpl->GetIOLoop()->PostTask(FROM_HERE, - new AcceptTask(mImpl, fd.forget())); + mImpl->GetIOLoop()->PostTask( + mozilla::MakeAndAddRef(mImpl, fd.forget())); } void OnError(BluetoothStatus aStatus) override @@ -416,11 +423,13 @@ public: , mListenFd(aListenFd) { } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(GetIO()->IsConsumerThread()); GetIO()->mConsumer->Accept(mListenFd, new AcceptResultHandler(GetIO())); + + return NS_OK; } private: @@ -438,7 +447,7 @@ DroidSocketImpl::OnSocketCanAcceptWithoutBlocking(int aFd) */ RemoveWatchers(READ_WATCHER); - GetConsumerThread()->PostTask(FROM_HERE, new InvokeAcceptTask(this, aFd)); + GetConsumerThread()->PostTask(MakeAndAddRef(this, aFd)); } void @@ -483,7 +492,7 @@ DroidSocketImpl::OnSocketCanConnectWithoutBlocking(int aFd) mConnectionStatus = SOCKET_IS_CONNECTED; GetConsumerThread()->PostTask( - FROM_HERE, new SocketEventTask(this, SocketEventTask::CONNECT_SUCCESS)); + MakeAndAddRef(this, SocketEventTask::CONNECT_SUCCESS)); AddWatchers(READ_WATCHER, true); if (HasPendingData()) { @@ -519,7 +528,7 @@ public: , mBuffer(aBuffer) { } - void Run() override + NS_IMETHOD Run() override { DroidSocketImpl* io = SocketTask::GetIO(); @@ -528,13 +537,15 @@ public: if (NS_WARN_IF(io->IsShutdownOnConsumerThread())) { // Since we've already explicitly closed and the close // happened before this, this isn't really an error. - return; + return NS_OK; } BluetoothSocket* bluetoothSocket = io->GetBluetoothSocket(); MOZ_ASSERT(bluetoothSocket); bluetoothSocket->ReceiveSocketData(mBuffer); + + return NS_OK; } private: @@ -544,8 +555,8 @@ private: void DroidSocketImpl::ConsumeBuffer() { - GetConsumerThread()->PostTask(FROM_HERE, - new ReceiveTask(this, mBuffer.release())); + GetConsumerThread()->PostTask( + MakeAndAddRef(this, mBuffer.release())); } void @@ -605,8 +616,8 @@ public: } mImpl->mConsumer->SetAddress(aBdAddress); - mImpl->GetIOLoop()->PostTask(FROM_HERE, - new SocketConnectTask(mImpl, aFd)); + mImpl->GetIOLoop()->PostTask( + mozilla::MakeAndAddRef(mImpl, aFd)); } void OnError(BluetoothStatus aStatus) override @@ -682,7 +693,8 @@ public: { MOZ_ASSERT(mImpl->IsConsumerThread()); - mImpl->GetIOLoop()->PostTask(FROM_HERE, new SocketListenTask(mImpl, aFd)); + mImpl->GetIOLoop()->PostTask( + mozilla::MakeAndAddRef(mImpl, aFd)); } void OnError(BluetoothStatus aStatus) override @@ -776,8 +788,8 @@ BluetoothSocket::SendSocketData(UnixSocketIOBuffer* aBuffer) MOZ_ASSERT(!mImpl->IsShutdownOnConsumerThread()); mImpl->GetIOLoop()->PostTask( - FROM_HERE, - new SocketIOSendTask(mImpl, aBuffer)); + MakeAndAddRef>( + mImpl, aBuffer)); } // |SocketBase| @@ -860,7 +872,7 @@ BluetoothSocket::Cleanup() // sever the relationship here so any future calls to listen // or connect will create a new implementation. mImpl->ShutdownOnConsumerThread(); - mImpl->GetIOLoop()->PostTask(FROM_HERE, new SocketIOShutdownTask(mImpl)); + mImpl->GetIOLoop()->PostTask(MakeAndAddRef(mImpl)); mImpl = nullptr; mSocketInterface = nullptr; diff --git a/dom/bluetooth/bluedroid/BluetoothSocketMessageWatcher.cpp b/dom/bluetooth/bluedroid/BluetoothSocketMessageWatcher.cpp index d4a4b3a07a..22a8f19e3d 100644 --- a/dom/bluetooth/bluedroid/BluetoothSocketMessageWatcher.cpp +++ b/dom/bluetooth/bluedroid/BluetoothSocketMessageWatcher.cpp @@ -277,10 +277,11 @@ SocketMessageWatcherTask::SocketMessageWatcherTask( MOZ_ASSERT(mWatcher); } -void +NS_IMETHODIMP SocketMessageWatcherTask::Run() { mWatcher->Watch(); + return NS_OK; } // @@ -294,19 +295,20 @@ DeleteSocketMessageWatcherTask::DeleteSocketMessageWatcherTask( MOZ_ASSERT(mRes); } -void +NS_IMETHODIMP DeleteSocketMessageWatcherTask::Run() { // look up hash table for the watcher corresponding to |mRes| SocketMessageWatcherWrapper* wrapper = sWatcherHashtable.Get(mRes); if (!wrapper) { - return; + return NS_OK; } // stop the watcher if it exists SocketMessageWatcher* watcher = wrapper->GetSocketMessageWatcher(); watcher->StopWatching(); watcher->Proceed(STATUS_DONE); + return NS_OK; } END_BLUETOOTH_NAMESPACE diff --git a/dom/bluetooth/bluedroid/BluetoothSocketMessageWatcher.h b/dom/bluetooth/bluedroid/BluetoothSocketMessageWatcher.h index 81cc8cb210..e21ccd90a5 100644 --- a/dom/bluetooth/bluedroid/BluetoothSocketMessageWatcher.h +++ b/dom/bluetooth/bluedroid/BluetoothSocketMessageWatcher.h @@ -84,12 +84,12 @@ private: /* |SocketMessageWatcherTask| starts a SocketMessageWatcher * on the I/O task */ -class SocketMessageWatcherTask final : public Task +class SocketMessageWatcherTask final : public Runnable { public: SocketMessageWatcherTask(SocketMessageWatcher* aWatcher); - void Run() override; + NS_IMETHOD Run() override; private: SocketMessageWatcher* mWatcher; @@ -98,12 +98,12 @@ private: /* |DeleteSocketMessageWatcherTask| deletes a watching SocketMessageWatcher * on the I/O task */ -class DeleteSocketMessageWatcherTask final : public Task +class DeleteSocketMessageWatcherTask final : public Runnable { public: DeleteSocketMessageWatcherTask(BluetoothSocketResultHandler* aRes); - void Run() override; + NS_IMETHOD Run() override; private: BluetoothSocketResultHandler* mRes; diff --git a/dom/bluetooth/bluedroid/hfp/BluetoothHfpManager.cpp b/dom/bluetooth/bluedroid/hfp/BluetoothHfpManager.cpp index 427a5e7724..718260edbb 100644 --- a/dom/bluetooth/bluedroid/hfp/BluetoothHfpManager.cpp +++ b/dom/bluetooth/bluedroid/hfp/BluetoothHfpManager.cpp @@ -108,17 +108,18 @@ protected: ~GetVolumeTask() { } }; -class BluetoothHfpManager::CloseScoTask : public Task +class BluetoothHfpManager::CloseScoTask : public Runnable { private: - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(sBluetoothHfpManager); sBluetoothHfpManager->DisconnectSco(); + return NS_OK; } }; -class BluetoothHfpManager::CloseScoRunnable : public nsRunnable +class BluetoothHfpManager::CloseScoRunnable : public Runnable { public: NS_IMETHOD Run() override @@ -126,16 +127,16 @@ public: MOZ_ASSERT(NS_IsMainThread()); MessageLoop::current()->PostDelayedTask( - FROM_HERE, new CloseScoTask(), sBusyToneInterval); + MakeAndAddRef(), sBusyToneInterval); return NS_OK; } }; -class BluetoothHfpManager::RespondToBLDNTask : public Task +class BluetoothHfpManager::RespondToBLDNTask : public Runnable { private: - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(sBluetoothHfpManager); @@ -143,6 +144,7 @@ private: sBluetoothHfpManager->mDialingRequestProcessed = true; sBluetoothHfpManager->SendResponse(HFP_AT_RESPONSE_ERROR); } + return NS_OK; } }; @@ -319,7 +321,7 @@ private: }; class BluetoothHfpManager::InitProfileResultHandlerRunnable final - : public nsRunnable + : public Runnable { public: InitProfileResultHandlerRunnable(BluetoothProfileResultHandler* aRes, @@ -355,7 +357,7 @@ BluetoothHfpManager::InitHfpInterface(BluetoothProfileResultHandler* aRes) if (sBluetoothHfpInterface) { BT_LOGR("Bluetooth Handsfree interface is already initalized."); - RefPtr r = + RefPtr r = new InitProfileResultHandlerRunnable(aRes, NS_OK); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch HFP Init runnable"); @@ -368,7 +370,7 @@ BluetoothHfpManager::InitHfpInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!btInf)) { // If there's no backend interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch HFP OnError runnable"); @@ -381,7 +383,7 @@ BluetoothHfpManager::InitHfpInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!setupInterface)) { // If there's no Setup interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch HFP OnError runnable"); @@ -394,7 +396,7 @@ BluetoothHfpManager::InitHfpInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!interface)) { // If there's no HFP interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new InitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch HFP OnError runnable"); @@ -471,7 +473,7 @@ private: }; class BluetoothHfpManager::DeinitProfileResultHandlerRunnable final - : public nsRunnable + : public Runnable { public: DeinitProfileResultHandlerRunnable(BluetoothProfileResultHandler* aRes, @@ -507,7 +509,7 @@ BluetoothHfpManager::DeinitHfpInterface(BluetoothProfileResultHandler* aRes) if (!sBluetoothHfpInterface) { BT_LOGR("Bluetooth Handsfree interface has not been initialized."); - RefPtr r = + RefPtr r = new DeinitProfileResultHandlerRunnable(aRes, NS_OK); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch HFP Deinit runnable"); @@ -520,7 +522,7 @@ BluetoothHfpManager::DeinitHfpInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!btInf)) { // If there's no backend interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new DeinitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch HFP OnError runnable"); @@ -533,7 +535,7 @@ BluetoothHfpManager::DeinitHfpInterface(BluetoothProfileResultHandler* aRes) if (NS_WARN_IF(!setupInterface)) { // If there's no Setup interface, we dispatch a runnable // that calls the profile result handler. - RefPtr r = + RefPtr r = new DeinitProfileResultHandlerRunnable(aRes, NS_ERROR_FAILURE); if (NS_FAILED(NS_DispatchToMainThread(r))) { BT_LOGR("Failed to dispatch HFP OnError runnable"); @@ -1597,8 +1599,7 @@ void BluetoothHfpManager::DialCallNotification(const nsAString& aNumber, mDialingRequestProcessed = false; NotifyDialer(NS_LITERAL_STRING("BLDN")); - MessageLoop::current()->PostDelayedTask(FROM_HERE, - new RespondToBLDNTask(), + MessageLoop::current()->PostDelayedTask(MakeAndAddRef(), sWaitingForDialingInterval); } else if (message[0] == '>') { mDialingRequestProcessed = false; @@ -1607,8 +1608,7 @@ void BluetoothHfpManager::DialCallNotification(const nsAString& aNumber, newMsg += StringHead(message, message.Length() - 1); NotifyDialer(NS_ConvertUTF8toUTF16(newMsg)); - MessageLoop::current()->PostDelayedTask(FROM_HERE, - new RespondToBLDNTask(), + MessageLoop::current()->PostDelayedTask(MakeAndAddRef(), sWaitingForDialingInterval); } else { SendResponse(HFP_AT_RESPONSE_OK); @@ -1766,8 +1766,7 @@ BluetoothHfpManager::KeyPressedNotification(const BluetoothAddress& aBdAddress) NotifyDialer(NS_LITERAL_STRING("BLDN")); - MessageLoop::current()->PostDelayedTask(FROM_HERE, - new RespondToBLDNTask(), + MessageLoop::current()->PostDelayedTask(MakeAndAddRef(), sWaitingForDialingInterval); } } diff --git a/dom/bluetooth/bluez/BluetoothDBusService.cpp b/dom/bluetooth/bluez/BluetoothDBusService.cpp index d0df1ecf23..0a617486c5 100644 --- a/dom/bluetooth/bluez/BluetoothDBusService.cpp +++ b/dom/bluetooth/bluez/BluetoothDBusService.cpp @@ -384,9 +384,9 @@ typedef void (*UnpackFunc)(DBusMessage*, DBusError*, typedef bool (*FilterFunc)(const BluetoothValue&); static void -DispatchToDBusThread(Task* task) +DispatchToDBusThread(already_AddRefed task) { - XRE_GetIOMessageLoop()->PostTask(FROM_HERE, task); + XRE_GetIOMessageLoop()->PostTask(Move(task)); } static nsresult @@ -513,7 +513,7 @@ GetPairedDevicesFilter(const BluetoothValue& aValue) return false; } -class DistributeBluetoothSignalTask : public nsRunnable +class DistributeBluetoothSignalTask : public Runnable { public: DistributeBluetoothSignalTask(const BluetoothSignal& aSignal) @@ -536,7 +536,7 @@ private: BluetoothSignal mSignal; }; -class ControlPropertyChangedHandler : public nsRunnable +class ControlPropertyChangedHandler : public Runnable { public: ControlPropertyChangedHandler(const BluetoothSignal& aSignal) @@ -568,7 +568,7 @@ private: BluetoothSignal mSignal; }; -class SinkPropertyChangedHandler : public nsRunnable +class SinkPropertyChangedHandler : public Runnable { public: SinkPropertyChangedHandler(const BluetoothSignal& aSignal) @@ -598,7 +598,7 @@ private: BluetoothSignal mSignal; }; -class InputPropertyChangedHandler : public nsRunnable +class InputPropertyChangedHandler : public Runnable { public: InputPropertyChangedHandler(const BluetoothSignal& aSignal) @@ -628,16 +628,17 @@ private: BluetoothSignal mSignal; }; -class TryFiringAdapterAddedTask : public Task +class TryFiringAdapterAddedTask : public Runnable { public: - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(NS_IsMainThread()); + return NS_OK; } }; -class TryFiringAdapterAddedRunnable : public nsRunnable +class TryFiringAdapterAddedRunnable : public Runnable { public: TryFiringAdapterAddedRunnable(bool aDelay) @@ -650,11 +651,11 @@ public: if (mDelay) { MessageLoop::current()-> - PostDelayedTask(FROM_HERE, new TryFiringAdapterAddedTask(), + PostDelayedTask(MakeAndAddRef(), sWaitingForAdapterNameInterval); } else { MessageLoop::current()-> - PostTask(FROM_HERE, new TryFiringAdapterAddedTask()); + PostTask(MakeAndAddRef()); } return NS_OK; @@ -719,7 +720,7 @@ UnpackObjectPathMessage(DBusMessage* aMsg, DBusError* aErr, } } -class PrepareProfileManagersRunnable : public nsRunnable +class PrepareProfileManagersRunnable : public Runnable { public: nsresult Run() @@ -808,7 +809,7 @@ GetVoidCallback(DBusMessage* aMsg, void* aBluetoothReplyRunnable) UnpackVoidMessage); } -class ReplyErrorToProfileManager : public nsRunnable +class ReplyErrorToProfileManager : public Runnable { public: ReplyErrorToProfileManager(BluetoothServiceClass aServiceClass, @@ -1256,7 +1257,7 @@ AppendDeviceName(BluetoothSignal& aSignal) Unused << handler.forget(); // picked up by callback handler } -class SetPairingConfirmationTask : public Task +class SetPairingConfirmationTask : public Runnable { public: SetPairingConfirmationTask(const BluetoothAddress& aDeviceAddress, @@ -1269,7 +1270,7 @@ public: MOZ_ASSERT(!mDeviceAddress.IsCleared()); } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(!NS_IsMainThread()); // I/O thread MOZ_ASSERT(sDBusConnection); @@ -1283,7 +1284,7 @@ public: errorStr.AssignLiteral("Couldn't get original request message."); DispatchBluetoothReply(mRunnable, v, errorStr); - return; + return NS_OK; } DBusMessage *reply; @@ -1302,7 +1303,7 @@ public: if (mRunnable) { DispatchBluetoothReply(mRunnable, v, errorStr); } - return; + return NS_OK; } bool result = sDBusConnection->Send(reply); @@ -1316,6 +1317,7 @@ public: if (mRunnable) { DispatchBluetoothReply(mRunnable, v, errorStr); } + return NS_OK; } private: @@ -1509,8 +1511,8 @@ AgentEventFilter(DBusConnection *conn, DBusMessage *msg, void *data) GetAddressFromObjectPath(NS_ConvertUTF8toUTF16(objectPath), address); sPairingReqTable->Put(address, msg); - Task* task = new SetPairingConfirmationTask(address, true, nullptr); - DispatchToDBusThread(task); + DispatchToDBusThread( + MakeAndAddRef(address, true, nullptr)); // Increase dbus message reference counts, it will be decreased in // SetPairingConfirmationTask dbus_message_ref(msg); @@ -1689,13 +1691,13 @@ private: } }; -class AddReservedServiceRecordsTask : public Task +class AddReservedServiceRecordsTask : public Runnable { public: AddReservedServiceRecordsTask() { } - void Run() + NS_IMETHOD Run() override { static const dbus_uint32_t sServices[] = { BluetoothServiceClass::HANDSFREE_AG, @@ -1720,13 +1722,15 @@ public: DBUS_TYPE_ARRAY, DBUS_TYPE_UINT32, &services, ArrayLength(sServices), DBUS_TYPE_INVALID); - NS_ENSURE_TRUE_VOID(success); + NS_ENSURE_TRUE(success, NS_OK); Unused << handler.forget(); /* picked up by callback handler */ + + return NS_OK; } }; -class PrepareAdapterRunnable : public nsRunnable +class PrepareAdapterRunnable : public Runnable { public: PrepareAdapterRunnable() @@ -1736,14 +1740,13 @@ public: { MOZ_ASSERT(NS_IsMainThread()); - Task* task = new AddReservedServiceRecordsTask(); - DispatchToDBusThread(task); + DispatchToDBusThread(MakeAndAddRef()); return NS_OK; } }; -class RequestPlayStatusTask : public nsRunnable +class RequestPlayStatusTask : public Runnable { public: RequestPlayStatusTask() @@ -2016,7 +2019,7 @@ EventFilter(DBusConnection* aConn, DBusMessage* aMsg, void* aData) } BluetoothSignal signal(signalName, signalPath, v); - RefPtr task; + RefPtr task; if (signalInterface.EqualsLiteral(DBUS_SINK_IFACE)) { task = new SinkPropertyChangedHandler(signal); } else if (signalInterface.EqualsLiteral(DBUS_CTL_IFACE)) { @@ -2071,7 +2074,7 @@ BluetoothDBusService::IsReady() return true; } -class StartDBusConnectionTask : public Task +class StartDBusConnectionTask : public Runnable { public: StartDBusConnectionTask(RawDBusConnection* aConnection) @@ -2080,28 +2083,28 @@ public: MOZ_ASSERT(mConnection); } - void Run() + NS_IMETHOD Run() override { MOZ_ASSERT(!NS_IsMainThread()); // I/O thread if (sDBusConnection) { BT_WARNING("DBus connection has already been established."); - RefPtr runnable = new BluetoothService::ToggleBtAck(true); + RefPtr runnable = new BluetoothService::ToggleBtAck(true); if (NS_FAILED(NS_DispatchToMainThread(runnable))) { BT_WARNING("Failed to dispatch to main thread!"); } - return; + return NS_OK; } // Add a filter for all incoming messages_base if (!dbus_connection_add_filter(mConnection->GetConnection(), EventFilter, nullptr, nullptr)) { BT_WARNING("Cannot create DBus Event Filter for DBus Thread!"); - RefPtr runnable = new BluetoothService::ToggleBtAck(false); + RefPtr runnable = new BluetoothService::ToggleBtAck(false); if (NS_FAILED(NS_DispatchToMainThread(runnable))) { BT_WARNING("Failed to dispatch to main thread!"); } - return; + return NS_OK; } mConnection->Watch(); @@ -2112,11 +2115,11 @@ public: sDBusConnection = mConnection.release(); - RefPtr runnable = + RefPtr runnable = new BluetoothService::ToggleBtAck(true); - if (NS_FAILED(NS_DispatchToMainThread(runnable))) { + if (NS_FAILED(NS_DispatchToMainThread(runnable.forget()))) { BT_WARNING("Failed to dispatch to main thread!"); - return; + return NS_OK; } /* Normally we'll receive the signal 'AdapterAdded' with the adapter object @@ -2136,13 +2139,14 @@ public: BT_WARNING("Failed to query default adapter!"); } } + return NS_OK; } private: UniquePtr mConnection; }; -class StartBluetoothRunnable final : public nsRunnable +class StartBluetoothRunnable final : public Runnable { public: NS_IMETHOD Run() @@ -2153,7 +2157,7 @@ public: #ifdef MOZ_WIDGET_GONK if (!sBluedroid.Enable()) { BT_WARNING("Bluetooth not available."); - RefPtr runnable = new BluetoothService::ToggleBtAck(false); + RefPtr runnable = new BluetoothService::ToggleBtAck(false); if (NS_FAILED(NS_DispatchToMainThread(runnable))) { BT_WARNING("Failed to dispatch to main thread!"); } @@ -2165,7 +2169,7 @@ public: nsresult rv = connection->EstablishDBusConnection(); if (NS_FAILED(rv)) { BT_WARNING("Failed to establish connection to BlueZ daemon"); - RefPtr runnable = new BluetoothService::ToggleBtAck(false); + RefPtr runnable = new BluetoothService::ToggleBtAck(false); if (NS_FAILED(NS_DispatchToMainThread(runnable))) { BT_WARNING("Failed to dispatch to main thread!"); } @@ -2190,8 +2194,7 @@ public: } } - Task* task = new StartDBusConnectionTask(connection); - DispatchToDBusThread(task); + DispatchToDBusThread(MakeAndAddRef(connection)); return NS_OK; } @@ -2202,7 +2205,7 @@ BluetoothDBusService::StartInternal(BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(!aRunnable); - RefPtr runnable = new StartBluetoothRunnable(); + RefPtr runnable = new StartBluetoothRunnable(); nsresult rv = DispatchToBtThread(runnable); if (NS_FAILED(rv)) { BT_WARNING("Failed to dispatch to BT thread!"); @@ -2210,7 +2213,7 @@ BluetoothDBusService::StartInternal(BluetoothReplyRunnable* aRunnable) return rv; } -class DisableBluetoothRunnable final : public nsRunnable +class DisableBluetoothRunnable final : public Runnable { public: NS_IMETHOD Run() @@ -2230,7 +2233,7 @@ public: bool isEnabled = false; #endif - RefPtr runnable = + RefPtr runnable = new BluetoothService::ToggleBtAck(isEnabled); nsresult rv = NS_DispatchToMainThread(runnable); if (NS_FAILED(rv)) { @@ -2240,23 +2243,23 @@ public: } }; -class DeleteDBusConnectionTask final : public Task +class DeleteDBusConnectionTask final : public Runnable { public: DeleteDBusConnectionTask() { } - void Run() + NS_IMETHOD Run() override { MOZ_ASSERT(!NS_IsMainThread()); // I/O thread if (!sDBusConnection) { BT_WARNING("DBus connection has not been established."); - RefPtr runnable = new BluetoothService::ToggleBtAck(false); + RefPtr runnable = new BluetoothService::ToggleBtAck(false); if (NS_FAILED(NS_DispatchToMainThread(runnable))) { BT_WARNING("Failed to dispatch to main thread!"); } - return; + return NS_OK; } for (uint32_t i = 0; i < ArrayLength(sBluetoothDBusSignals); ++i) { @@ -2295,14 +2298,15 @@ public: // We can only dispatch to the BT thread if we're on the main // thread. Thus we dispatch our runnable to the main thread // from where it will forward itself to the BT thread. - RefPtr runnable = new DisableBluetoothRunnable(); + RefPtr runnable = new DisableBluetoothRunnable(); if (NS_FAILED(NS_DispatchToMainThread(runnable))) { BT_WARNING("Failed to dispatch to BT thread!"); } + return NS_OK; } }; -class StopBluetoothRunnable final : public nsRunnable +class StopBluetoothRunnable final : public Runnable { public: NS_IMETHOD Run() @@ -2315,7 +2319,7 @@ public: lock.Wait(PR_SecondsToInterval(TIMEOUT_FORCE_TO_DISABLE_BT)); } - DispatchToDBusThread(new DeleteDBusConnectionTask()); + DispatchToDBusThread(MakeAndAddRef()); return NS_OK; } @@ -2326,7 +2330,7 @@ BluetoothDBusService::StopInternal(BluetoothReplyRunnable* aRunnable) { MOZ_ASSERT(!aRunnable); - RefPtr runnable = new StopBluetoothRunnable(); + RefPtr runnable = new StopBluetoothRunnable(); nsresult rv = DispatchToBtThread(runnable); if (NS_FAILED(rv)) { BT_WARNING("Failed to dispatch to BT thread!"); @@ -2443,7 +2447,7 @@ private: nsString mAdapterPath; }; -class DefaultAdapterTask : public Task +class DefaultAdapterTask : public Runnable { public: DefaultAdapterTask(BluetoothReplyRunnable* aRunnable) @@ -2452,7 +2456,7 @@ public: MOZ_ASSERT(mRunnable); } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(!NS_IsMainThread()); // I/O thread MOZ_ASSERT(sDBusConnection); @@ -2465,9 +2469,11 @@ public: handler.get(), 1000, BLUEZ_DBUS_BASE_IFC, "/", DBUS_MANAGER_IFACE, "DefaultAdapter", DBUS_TYPE_INVALID); - NS_ENSURE_TRUE_VOID(success); + NS_ENSURE_TRUE(success, NS_OK); Unused << handler.forget(); // picked up by callback handler + + return NS_OK; } private: @@ -2489,8 +2495,7 @@ BluetoothDBusService::GetAdaptersInternal(BluetoothReplyRunnable* aRunnable) return NS_OK; } - Task* task = new DefaultAdapterTask(aRunnable); - DispatchToDBusThread(task); + DispatchToDBusThread(MakeAndAddRef(aRunnable)); return NS_OK; } @@ -2513,7 +2518,7 @@ OnSendDiscoveryMessageReply(DBusMessage *aReply, void *aData) DispatchBluetoothReply(runnable.get(), BluetoothValue(true), errorStr); } -class SendDiscoveryMessageTask : public Task +class SendDiscoveryMessageTask : public Runnable { public: SendDiscoveryMessageTask(const char* aMessageName, @@ -2525,7 +2530,7 @@ public: MOZ_ASSERT(mRunnable); } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(!NS_IsMainThread()); // I/O thread MOZ_ASSERT(sDBusConnection); @@ -2538,9 +2543,11 @@ public: NS_ConvertUTF16toUTF8(sAdapterPath).get(), DBUS_ADAPTER_IFACE, mMessageName.get(), DBUS_TYPE_INVALID); - NS_ENSURE_TRUE_VOID(success); + NS_ENSURE_TRUE(success, NS_OK); Unused << mRunnable.forget(); // picked up by callback handler + + return NS_OK; } private: @@ -2562,8 +2569,8 @@ BluetoothDBusService::SendDiscoveryMessage(const char* aMessageName, return NS_OK; } - Task* task = new SendDiscoveryMessageTask(aMessageName, aRunnable); - DispatchToDBusThread(task); + DispatchToDBusThread( + MakeAndAddRef(aMessageName, aRunnable)); return NS_OK; } @@ -2587,7 +2594,7 @@ BluetoothDBusService::SendInputMessage(const nsAString& aDeviceAddress, return SendAsyncDBusMessage(objectPath, DBUS_INPUT_IFACE, aMessage, callback); } -class SendAsyncDBusMessageTask : public Task +class SendAsyncDBusMessageTask : public Runnable { public: SendAsyncDBusMessageTask(DBusReplyCallback aCallback, @@ -2606,7 +2613,7 @@ public: MOZ_ASSERT(!mMessage.IsEmpty()); } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(!NS_IsMainThread()); // I/O thread MOZ_ASSERT(sDBusConnection); @@ -2617,7 +2624,9 @@ public: mCallback, NS_INT32_TO_PTR(mServiceClass), -1, BLUEZ_DBUS_BASE_IFC, mObjectPath.get(), mInterface.get(), mMessage.get(), DBUS_TYPE_INVALID); - NS_ENSURE_TRUE_VOID(success); + NS_ENSURE_TRUE(success, NS_OK); + + return NS_OK; } private: @@ -2650,12 +2659,12 @@ BluetoothDBusService::SendAsyncDBusMessage(const nsAString& aObjectPath, return NS_ERROR_FAILURE; } - Task* task = new SendAsyncDBusMessageTask(aCallback, + DispatchToDBusThread( + MakeAndAddRef(aCallback, serviceClass, NS_ConvertUTF16toUTF8(aObjectPath), aInterface, - NS_ConvertUTF16toUTF8(aMessage)); - DispatchToDBusThread(task); + NS_ConvertUTF16toUTF8(aMessage))); return NS_OK; } @@ -2824,7 +2833,7 @@ private: BluetoothValue mValues; }; -class ProcessRemainingDeviceAddressesTask : public Task +class ProcessRemainingDeviceAddressesTask : public Runnable { public: ProcessRemainingDeviceAddressesTask( @@ -2837,11 +2846,13 @@ public: MOZ_ASSERT(mRunnable); } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(!NS_IsMainThread()); // I/O thread mHandler->ProcessRemainingDeviceAddresses(); + + return NS_OK; } private: @@ -2883,8 +2894,8 @@ BluetoothDBusService::GetConnectedDevicePropertiesInternal( new BluetoothArrayOfDevicePropertiesReplyHandler(deviceAddresses, GetConnectedDevicesFilter, aRunnable); - Task* task = new ProcessRemainingDeviceAddressesTask(handler, aRunnable); - DispatchToDBusThread(task); + DispatchToDBusThread( + MakeAndAddRef(handler, aRunnable)); return NS_OK; } @@ -2906,8 +2917,8 @@ BluetoothDBusService::GetPairedDevicePropertiesInternal( new BluetoothArrayOfDevicePropertiesReplyHandler(aDeviceAddresses, GetPairedDevicesFilter, aRunnable); - Task* task = new ProcessRemainingDeviceAddressesTask(handler, aRunnable); - DispatchToDBusThread(task); + DispatchToDBusThread( + MakeAndAddRef(handler, aRunnable)); return NS_OK; } @@ -2919,7 +2930,7 @@ BluetoothDBusService::FetchUuidsInternal(const BluetoothAddress& aDeviceAddress, return NS_OK; } -class SetPropertyTask : public Task +class SetPropertyTask : public Runnable { public: SetPropertyTask(BluetoothObjectType aType, @@ -2994,9 +3005,11 @@ public: , mValue(aValue) { } - void Run() override + NS_IMETHOD Run() override { Send(DBUS_TYPE_UINT32, &mValue); + + return NS_OK; } private: @@ -3014,10 +3027,12 @@ public: , mValue(aValue) { } - void Run() override + NS_IMETHOD Run() override { const char* value = mValue.get(); Send(DBUS_TYPE_STRING, &value); + + return NS_OK; } private: @@ -3036,9 +3051,11 @@ public: { } - void Run() override + NS_IMETHOD Run() override { Send(DBUS_TYPE_BOOLEAN, &mValue); + + return NS_OK; } private: @@ -3058,30 +3075,30 @@ BluetoothDBusService::SetProperty(BluetoothObjectType aType, return NS_OK; } - Task* task; + RefPtr task; if (aValue.value().type() == BluetoothValue::Tuint32_t) { - task = new SetUInt32PropertyTask(aType, + task = MakeAndAddRef(aType, NS_ConvertUTF16toUTF8(aValue.name()), aValue.value().get_uint32_t(), aRunnable); } else if (aValue.value().type() == BluetoothValue::TnsString) { - task = new SetStringPropertyTask(aType, + task = MakeAndAddRef(aType, NS_ConvertUTF16toUTF8(aValue.name()), NS_ConvertUTF16toUTF8(aValue.value().get_nsString()), aRunnable); } else if (aValue.value().type() == BluetoothValue::Tbool) { - task = new SetBooleanPropertyTask(aType, + task = MakeAndAddRef(aType, NS_ConvertUTF16toUTF8(aValue.name()), aValue.value().get_bool(), aRunnable); } else { BT_WARNING("Property type not handled!"); return NS_ERROR_FAILURE; } - DispatchToDBusThread(task); + DispatchToDBusThread(task.forget()); return NS_OK; } -class CreatePairedDeviceInternalTask : public Task +class CreatePairedDeviceInternalTask : public Runnable { public: CreatePairedDeviceInternalTask(const BluetoothAddress& aDeviceAddress, @@ -3095,7 +3112,7 @@ public: MOZ_ASSERT(mRunnable); } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(!NS_IsMainThread()); // I/O thread MOZ_ASSERT(sDBusConnection); @@ -3121,7 +3138,7 @@ public: DBUS_TYPE_OBJECT_PATH, &deviceAgentPath, DBUS_TYPE_STRING, &capabilities, DBUS_TYPE_INVALID); - NS_ENSURE_TRUE_VOID(success); + NS_ENSURE_TRUE(success, NS_OK); Unused << mRunnable.forget(); // picked up by callback handler @@ -3138,6 +3155,8 @@ public: * Please see Bug 818696 for more information. */ sIsPairing++; + + return NS_OK; } private: @@ -3152,15 +3171,15 @@ BluetoothDBusService::CreatePairedDeviceInternal( int aTimeout, BluetoothReplyRunnable* aRunnable) { - Task* task = new CreatePairedDeviceInternalTask(aDeviceAddress, + DispatchToDBusThread( + MakeAndAddRef(aDeviceAddress, aTimeout, - aRunnable); - DispatchToDBusThread(task); + aRunnable)); return NS_OK; } -class RemoveDeviceTask : public Task +class RemoveDeviceTask : public Runnable { public: RemoveDeviceTask(const BluetoothAddress& aDeviceAddress, @@ -3172,7 +3191,7 @@ public: MOZ_ASSERT(mRunnable); } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(!NS_IsMainThread()); // I/O thread MOZ_ASSERT(sDBusConnection); @@ -3190,9 +3209,11 @@ public: DBUS_ADAPTER_IFACE, "RemoveDevice", DBUS_TYPE_OBJECT_PATH, &cstrDeviceObjectPath, DBUS_TYPE_INVALID); - NS_ENSURE_TRUE_VOID(success); + NS_ENSURE_TRUE(success, NS_OK); Unused << mRunnable.forget(); // picked up by callback handler + + return NS_OK; } protected: @@ -3229,13 +3250,13 @@ BluetoothDBusService::RemoveDeviceInternal( return NS_OK; } - Task* task = new RemoveDeviceTask(aDeviceAddress, aRunnable); - DispatchToDBusThread(task); + DispatchToDBusThread( + MakeAndAddRef(aDeviceAddress, aRunnable)); return NS_OK; } -class SetPinCodeTask : public Task +class SetPinCodeTask : public Runnable { public: SetPinCodeTask(const BluetoothAddress& aDeviceAddress, @@ -3249,7 +3270,7 @@ public: MOZ_ASSERT(mRunnable); } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(!NS_IsMainThread()); // I/O thread @@ -3260,7 +3281,7 @@ public: BT_WARNING("%s: Couldn't get original request message.", __FUNCTION__); errorStr.AssignLiteral("Couldn't get original request message."); DispatchBluetoothReply(mRunnable, v, errorStr); - return; + return NS_OK; } DBusMessage *reply = dbus_message_new_method_return(msg); @@ -3270,7 +3291,7 @@ public: dbus_message_unref(msg); errorStr.AssignLiteral("Memory can't be allocated for the message."); DispatchBluetoothReply(mRunnable, v, errorStr); - return; + return NS_OK; } nsAutoString pinCodeStr; @@ -3280,7 +3301,7 @@ public: dbus_message_unref(reply); errorStr.AssignLiteral("Cannot convert pin code to string."); DispatchBluetoothReply(mRunnable, v, errorStr); - return; + return NS_OK; } auto utf8PinCodeStr = NS_ConvertUTF16toUTF8(pinCodeStr); @@ -3302,6 +3323,8 @@ public: sPairingReqTable->Remove(mDeviceAddress); DispatchBluetoothReply(mRunnable, v, errorStr); + + return NS_OK; } private: @@ -3331,11 +3354,11 @@ BluetoothDBusService::SetPinCodeInternal(const BluetoothAddress& aDeviceAddress, const BluetoothPinCode& aPinCode, BluetoothReplyRunnable* aRunnable) { - Task* task = new SetPinCodeTask(aDeviceAddress, aPinCode, aRunnable); - DispatchToDBusThread(task); + DispatchToDBusThread( + MakeAndAddRef(aDeviceAddress, aPinCode, aRunnable)); } -class SetPasskeyTask : public Task +class SetPasskeyTask : public Runnable { public: SetPasskeyTask(const BluetoothAddress& aDeviceAddress, @@ -3349,7 +3372,7 @@ public: MOZ_ASSERT(mRunnable); } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(!NS_IsMainThread()); // I/O thread @@ -3360,7 +3383,7 @@ public: BT_WARNING("%s: Couldn't get original request message.", __FUNCTION__); errorStr.AssignLiteral("Couldn't get original request message."); DispatchBluetoothReply(mRunnable, v, errorStr); - return; + return NS_OK; } DBusMessage *reply = dbus_message_new_method_return(msg); @@ -3370,7 +3393,7 @@ public: dbus_message_unref(msg); errorStr.AssignLiteral("Memory can't be allocated for the message."); DispatchBluetoothReply(mRunnable, v, errorStr); - return; + return NS_OK; } uint32_t passkey = mPasskey; @@ -3390,6 +3413,8 @@ public: sPairingReqTable->Remove(mDeviceAddress); DispatchBluetoothReply(mRunnable, v, errorStr); + + return NS_OK; } private: @@ -3404,10 +3429,10 @@ BluetoothDBusService::SetPasskeyInternal( uint32_t aPasskey, BluetoothReplyRunnable* aRunnable) { - Task* task = new SetPasskeyTask(aDeviceAddress, + DispatchToDBusThread( + MakeAndAddRef(aDeviceAddress, aPasskey, - aRunnable); - DispatchToDBusThread(task); + aRunnable)); } void @@ -3418,10 +3443,10 @@ BluetoothDBusService::SetPairingConfirmationInternal( { MOZ_ASSERT(NS_IsMainThread()); - Task* task = new SetPairingConfirmationTask(aDeviceAddress, + DispatchToDBusThread( + MakeAndAddRef(aDeviceAddress, aConfirm, - aRunnable); - DispatchToDBusThread(task); + aRunnable)); } static void @@ -3514,7 +3539,7 @@ BluetoothDBusService::ToggleCalls(BluetoothReplyRunnable* aRunnable) } #endif // MOZ_B2G_RIL -class OnUpdateSdpRecordsRunnable : public nsRunnable +class OnUpdateSdpRecordsRunnable : public Runnable { public: OnUpdateSdpRecordsRunnable(const BluetoothAddress& aDeviceAddress, @@ -3541,7 +3566,7 @@ private: BluetoothProfileManagerBase* mManager; }; -class OnGetServiceChannelRunnable : public nsRunnable +class OnGetServiceChannelRunnable : public Runnable { public: OnGetServiceChannelRunnable(const BluetoothAddress& aDeviceAddress, @@ -3603,7 +3628,7 @@ public: channel = dbus_returns_int32(aReply); } - RefPtr r = + RefPtr r = new OnGetServiceChannelRunnable(mDeviceAddress, mServiceUUID, channel, mBluetoothProfileManager); nsresult rv = NS_DispatchToMainThread(r); @@ -3616,7 +3641,7 @@ private: BluetoothProfileManagerBase* mBluetoothProfileManager; }; -class GetServiceChannelTask : public Task +class GetServiceChannelTask : public Runnable { public: GetServiceChannelTask(const BluetoothAddress& aDeviceAddress, @@ -3630,7 +3655,7 @@ public: MOZ_ASSERT(mBluetoothProfileManager); } - void Run() override + NS_IMETHOD Run() override { static const int sProtocolDescriptorList = 0x0004; @@ -3659,9 +3684,11 @@ public: DBUS_TYPE_STRING, &cstrServiceUUID, DBUS_TYPE_UINT16, &sProtocolDescriptorList, DBUS_TYPE_INVALID); - NS_ENSURE_TRUE_VOID(success); + NS_ENSURE_TRUE(success, NS_OK); Unused << handler.forget(); // picked up by callback handler + + return NS_OK; } private: @@ -3685,10 +3712,10 @@ BluetoothDBusService::GetServiceChannel(const BluetoothAddress& aDeviceAddress, #ifdef MOZ_WIDGET_GONK // GetServiceAttributeValue only exists in android's bluez dbus binding // implementation - Task* task = new GetServiceChannelTask(aDeviceAddress, + DispatchToDBusThread( + MakeAndAddRef(aDeviceAddress, aServiceUUID, - aManager); - DispatchToDBusThread(task); + aManager)); #else // FIXME/Bug 793977 qdot: Just set something for desktop, until we have a // parser for the GetServiceAttributes xml block @@ -3696,17 +3723,17 @@ BluetoothDBusService::GetServiceChannel(const BluetoothAddress& aDeviceAddress, // Even though we are on the main thread already, we need to dispatch a // runnable here. OnGetServiceChannel needs mRunnable to be set, which // happens after GetServiceChannel returns. - RefPtr r = new OnGetServiceChannelRunnable(aDeviceAddress, - aServiceUUID, - 1, - aManager); + RefPtr r = new OnGetServiceChannelRunnable(aDeviceAddress, + aServiceUUID, + 1, + aManager); NS_DispatchToMainThread(r); #endif return NS_OK; } -class UpdateSdpRecordsTask : public Task +class UpdateSdpRecordsTask : public Runnable { public: UpdateSdpRecordsTask(const BluetoothAddress& aDeviceAddress, @@ -3718,7 +3745,7 @@ public: MOZ_ASSERT(mBluetoothProfileManager); } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(!NS_IsMainThread()); // I/O thread MOZ_ASSERT(sDBusConnection); @@ -3740,6 +3767,7 @@ public: "DiscoverServices", DBUS_TYPE_STRING, &EmptyCString(), DBUS_TYPE_INVALID); + return NS_OK; } protected: @@ -3763,8 +3791,8 @@ BluetoothDBusService::UpdateSdpRecords(const BluetoothAddress& aDeviceAddress, { MOZ_ASSERT(NS_IsMainThread()); - Task* task = new UpdateSdpRecordsTask(aDeviceAddress, aManager); - DispatchToDBusThread(task); + DispatchToDBusThread( + MakeAndAddRef(aDeviceAddress, aManager)); return true; } @@ -3892,7 +3920,7 @@ BluetoothDBusService::IsScoConnected(BluetoothReplyRunnable* aRunnable) DispatchBluetoothReply(aRunnable, hfp->IsScoConnected(), EmptyString()); } -class SendMetadataTask : public Task +class SendMetadataTask : public Runnable { public: SendMetadataTask(const BluetoothAddress& aDeviceAddress, @@ -3916,7 +3944,7 @@ public: MOZ_ASSERT(mRunnable); } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(!NS_IsMainThread()); // I/O thread MOZ_ASSERT(sDBusConnection); @@ -3965,9 +3993,11 @@ public: DBUS_TYPE_STRING, &duration, DBUS_TYPE_STRING, &genre, DBUS_TYPE_INVALID); - NS_ENSURE_TRUE_VOID(success); + NS_ENSURE_TRUE(success, NS_OK); Unused << mRunnable.forget(); // picked up by callback handler + + return NS_OK; } private: @@ -4021,22 +4051,22 @@ BluetoothDBusService::SendMetaData(const nsAString& aTitle, BluetoothAddress deviceAddress; avrcp->GetAddress(deviceAddress); - Task* task = new SendMetadataTask( - deviceAddress, - NS_ConvertUTF16toUTF8(aTitle), - NS_ConvertUTF16toUTF8(aArtist), - NS_ConvertUTF16toUTF8(aAlbum), - aMediaNumber, - aTotalMediaCount, - aDuration, - aRunnable); - DispatchToDBusThread(task); + DispatchToDBusThread( + MakeAndAddRef( + deviceAddress, + NS_ConvertUTF16toUTF8(aTitle), + NS_ConvertUTF16toUTF8(aArtist), + NS_ConvertUTF16toUTF8(aAlbum), + aMediaNumber, + aTotalMediaCount, + aDuration, + aRunnable)); avrcp->UpdateMetaData(aTitle, aArtist, aAlbum, aMediaNumber, aTotalMediaCount, aDuration); } -class SendPlayStatusTask : public Task +class SendPlayStatusTask : public Runnable { public: SendPlayStatusTask(const BluetoothAddress& aDeviceAddress, @@ -4054,7 +4084,7 @@ public: MOZ_ASSERT(mRunnable); } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(!NS_IsMainThread()); // I/O thread MOZ_ASSERT(sDBusConnection); @@ -4074,9 +4104,11 @@ public: DBUS_TYPE_UINT32, &mPosition, DBUS_TYPE_UINT32, &tempPlayStatus, DBUS_TYPE_INVALID); - NS_ENSURE_TRUE_VOID(success); + NS_ENSURE_TRUE(success, NS_OK); Unused << mRunnable.forget(); // picked up by callback handler + + return NS_OK; } private: @@ -4134,12 +4166,12 @@ BluetoothDBusService::SendPlayStatus(int64_t aDuration, BluetoothAddress deviceAddress; avrcp->GetAddress(deviceAddress); - Task* task = new SendPlayStatusTask(deviceAddress, + DispatchToDBusThread( + MakeAndAddRef(deviceAddress, aDuration, aPosition, aPlayStatus, - aRunnable); - DispatchToDBusThread(task); + aRunnable)); avrcp->UpdatePlayStatus(aDuration, aPosition, aPlayStatus); } @@ -4157,7 +4189,7 @@ ControlCallback(DBusMessage* aMsg, void* aParam) } } -class UpdatePlayStatusTask : public Task +class UpdatePlayStatusTask : public Runnable { public: UpdatePlayStatusTask(const BluetoothAddress& aDeviceAddress, @@ -4172,7 +4204,7 @@ public: MOZ_ASSERT(!mDeviceAddress.IsCleared()); } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(!NS_IsMainThread()); // I/O thread MOZ_ASSERT(sDBusConnection); @@ -4192,7 +4224,9 @@ public: DBUS_TYPE_UINT32, &mPosition, DBUS_TYPE_UINT32, &tempPlayStatus, DBUS_TYPE_INVALID); - NS_ENSURE_TRUE_VOID(success); + NS_ENSURE_TRUE(success, NS_OK); + + return NS_OK; } private: @@ -4218,14 +4252,14 @@ BluetoothDBusService::UpdatePlayStatus(uint32_t aDuration, BluetoothAddress deviceAddress; avrcp->GetAddress(deviceAddress); - Task* task = new UpdatePlayStatusTask(deviceAddress, + DispatchToDBusThread( + MakeAndAddRef(deviceAddress, aDuration, aPosition, - aPlayStatus); - DispatchToDBusThread(task); + aPlayStatus)); } -class UpdateNotificationTask : public Task +class UpdateNotificationTask : public Runnable { public: UpdateNotificationTask(const BluetoothAddress& aDeviceAddress, @@ -4238,7 +4272,7 @@ public: MOZ_ASSERT(!mDeviceAddress.IsCleared()); } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(!NS_IsMainThread()); // I/O thread MOZ_ASSERT(sDBusConnection); @@ -4257,7 +4291,9 @@ public: DBUS_TYPE_UINT16, &eventId, DBUS_TYPE_UINT64, &mData, DBUS_TYPE_INVALID); - NS_ENSURE_TRUE_VOID(success); + NS_ENSURE_TRUE(success, NS_OK); + + return NS_OK; } private: @@ -4281,8 +4317,8 @@ BluetoothDBusService::UpdateNotification(ControlEventId aEventId, BluetoothAddress deviceAddress; avrcp->GetAddress(deviceAddress); - Task* task = new UpdateNotificationTask(deviceAddress, aEventId, aData); - DispatchToDBusThread(task); + DispatchToDBusThread( + MakeAndAddRef(deviceAddress, aEventId, aData)); } void diff --git a/dom/bluetooth/bluez/BluetoothHfpManager.cpp b/dom/bluetooth/bluez/BluetoothHfpManager.cpp index 3ad8b11dc2..09131993db 100644 --- a/dom/bluetooth/bluez/BluetoothHfpManager.cpp +++ b/dom/bluetooth/bluez/BluetoothHfpManager.cpp @@ -242,10 +242,10 @@ BluetoothHfpManager::Notify(const hal::BatteryInformation& aBatteryInfo) } #ifdef MOZ_B2G_RIL -class BluetoothHfpManager::RespondToBLDNTask : public Task +class BluetoothHfpManager::RespondToBLDNTask : public Runnable { private: - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(sBluetoothHfpManager); @@ -253,10 +253,11 @@ private: sBluetoothHfpManager->mDialingRequestProcessed = true; sBluetoothHfpManager->SendLine("ERROR"); } + return NS_OK; } }; -class BluetoothHfpManager::SendRingIndicatorTask : public Task +class BluetoothHfpManager::SendRingIndicatorTask : public Runnable { public: SendRingIndicatorTask(const nsAString& aNumber, int aType) @@ -266,18 +267,18 @@ public: MOZ_ASSERT(NS_IsMainThread()); } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(NS_IsMainThread()); // Stop sending RING indicator if (sStopSendingRingFlag) { - return; + return NS_OK; } if (!sBluetoothHfpManager) { BT_WARNING("BluetoothHfpManager no longer exists, cannot send ring!"); - return; + return NS_OK; } nsAutoCString ringMsg("RING"); @@ -291,10 +292,10 @@ public: sBluetoothHfpManager->SendLine(clipMsg.get()); } - MessageLoop::current()-> - PostDelayedTask(FROM_HERE, - new SendRingIndicatorTask(mNumber, mType), - sRingInterval); + MessageLoop::current()->PostDelayedTask( + MakeAndAddRef(mNumber, mType), sRingInterval); + + return NS_OK; } private: @@ -303,14 +304,16 @@ private: }; #endif // MOZ_B2G_RIL -class BluetoothHfpManager::CloseScoTask : public Task +class BluetoothHfpManager::CloseScoTask : public Runnable { private: - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(sBluetoothHfpManager); sBluetoothHfpManager->DisconnectSco(); + + return NS_OK; } }; @@ -985,7 +988,7 @@ BluetoothHfpManager::ReceiveSocketData(BluetoothSocket* aSocket, } MessageLoop::current()-> - PostDelayedTask(FROM_HERE, new RespondToBLDNTask(), + PostDelayedTask(MakeAndAddRef(), sWaitingForDialingInterval); // Don't send response 'OK' here because we'll respond later in either @@ -1490,7 +1493,7 @@ BluetoothHfpManager::HandleCallStateChanged(uint32_t aCallIndex, } mCurrentCallArray[aCallIndex].mNumber = aNumber; - RefPtr sendRingTask; + RefPtr sendRingTask; nsString address; switch (aCallState) { @@ -1576,9 +1579,8 @@ BluetoothHfpManager::HandleCallStateChanged(uint32_t aCallIndex, } MessageLoop::current()->PostDelayedTask( - FROM_HERE, - new SendRingIndicatorTask(number, - mCurrentCallArray[aCallIndex].mType), + MakeAndAddRef( + number, mCurrentCallArray[aCallIndex].mType), sRingInterval); } break; @@ -1686,8 +1688,7 @@ BluetoothHfpManager::HandleCallStateChanged(uint32_t aCallIndex, DisconnectSco(); } else { // Close Sco later since Dialer is still playing busy tone via HF. - MessageLoop::current()->PostDelayedTask(FROM_HERE, - new CloseScoTask(), + MessageLoop::current()->PostDelayedTask(MakeAndAddRef(), sBusyToneInterval); } diff --git a/dom/bluetooth/bluez/BluetoothOppManager.cpp b/dom/bluetooth/bluez/BluetoothOppManager.cpp index 0ae7c0d316..7c69085600 100644 --- a/dom/bluetooth/bluez/BluetoothOppManager.cpp +++ b/dom/bluetooth/bluez/BluetoothOppManager.cpp @@ -97,7 +97,7 @@ BluetoothOppManager::Observe(nsISupports* aSubject, return NS_ERROR_UNEXPECTED; } -class SendSocketDataTask : public nsRunnable +class SendSocketDataTask : public Runnable { public: SendSocketDataTask(UniquePtr aStream, uint32_t aSize) @@ -121,7 +121,7 @@ private: uint32_t mSize; }; -class ReadFileTask : public nsRunnable +class ReadFileTask : public Runnable { public: ReadFileTask(nsIInputStream* aInputStream, @@ -167,7 +167,7 @@ private: uint32_t mAvailablePacketSize; }; -class CloseSocketTask : public Task +class CloseSocketTask : public Runnable { public: CloseSocketTask(BluetoothSocket* aSocket) : mSocket(aSocket) @@ -175,7 +175,7 @@ public: MOZ_ASSERT(aSocket); } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(NS_IsMainThread()); @@ -183,6 +183,7 @@ public: SocketConnectionStatus::SOCKET_CONNECTED) { mSocket->Close(); } + return NS_OK; } private: @@ -1076,7 +1077,7 @@ BluetoothOppManager::ClientDataHandler(UnixSocketBuffer* aMessage) // disconnected, we will close it. if (mSocket) { MessageLoop::current()-> - PostDelayedTask(FROM_HERE, new CloseSocketTask(mSocket), 1000); + PostDelayedTask(MakeAndAddRef(mSocket), 1000); } } else if (mLastCommand == ObexRequestCode::Connect) { MOZ_ASSERT(!mFileName.IsEmpty()); diff --git a/dom/bluetooth/bluez/BluetoothSocket.cpp b/dom/bluetooth/bluez/BluetoothSocket.cpp index d8164de01b..f174ff4283 100644 --- a/dom/bluetooth/bluez/BluetoothSocket.cpp +++ b/dom/bluetooth/bluez/BluetoothSocket.cpp @@ -43,7 +43,7 @@ public: // Delayed-task handling // - void SetDelayedConnectTask(CancelableTask* aTask); + void SetDelayedConnectTask(CancelableRunnable* aTask); void ClearDelayedConnectTask(); void CancelDelayedConnectTask(); @@ -126,7 +126,7 @@ private: * Task member for delayed connect task. Should only be access on consumer * thread. */ - CancelableTask* mDelayedConnectTask; + CancelableRunnable* mDelayedConnectTask; /** * I/O buffer for received data @@ -193,7 +193,7 @@ BluetoothSocket::BluetoothSocketIO::GetDataSocket() } void -BluetoothSocket::BluetoothSocketIO::SetDelayedConnectTask(CancelableTask* aTask) +BluetoothSocket::BluetoothSocketIO::SetDelayedConnectTask(CancelableRunnable* aTask) { MOZ_ASSERT(IsConsumerThread()); @@ -285,7 +285,7 @@ BluetoothSocket::BluetoothSocketIO::OnConnected() MOZ_ASSERT(GetConnectionStatus() == SOCKET_IS_CONNECTED); GetConsumerThread()->PostTask( - FROM_HERE, new SocketEventTask(this, SocketEventTask::CONNECT_SUCCESS)); + MakeAndAddRef(this, SocketEventTask::CONNECT_SUCCESS)); AddWatchers(READ_WATCHER, true); if (HasPendingData()) { @@ -334,7 +334,7 @@ BluetoothSocket::BluetoothSocketIO::OnSocketCanAcceptWithoutBlocking() SetSocket(fd, SOCKET_IS_CONNECTED); GetConsumerThread()->PostTask( - FROM_HERE, new SocketEventTask(this, SocketEventTask::CONNECT_SUCCESS)); + MakeAndAddRef(this, SocketEventTask::CONNECT_SUCCESS)); AddWatchers(READ_WATCHER, true); if (HasPendingData()) { @@ -384,7 +384,7 @@ BluetoothSocket::BluetoothSocketIO::FireSocketError() // Tell the consumer thread we've errored GetConsumerThread()->PostTask( - FROM_HERE, new SocketEventTask(this, SocketEventTask::CONNECT_ERROR)); + MakeAndAddRef(this, SocketEventTask::CONNECT_ERROR)); } // |DataSocketIO| @@ -416,7 +416,7 @@ public: , mBuffer(aBuffer) { } - void Run() override + NS_IMETHOD Run() override { BluetoothSocketIO* io = SocketTask::GetIO(); @@ -425,13 +425,15 @@ public: if (NS_WARN_IF(io->IsShutdownOnConsumerThread())) { // Since we've already explicitly closed and the close // happened before this, this isn't really an error. - return; + return NS_OK; } BluetoothSocket* bluetoothSocket = io->GetBluetoothSocket(); MOZ_ASSERT(bluetoothSocket); bluetoothSocket->ReceiveSocketData(mBuffer); + + return NS_OK; } private: @@ -441,8 +443,8 @@ private: void BluetoothSocket::BluetoothSocketIO::ConsumeBuffer() { - GetConsumerThread()->PostTask(FROM_HERE, - new ReceiveTask(this, mBuffer.release())); + GetConsumerThread()->PostTask( + MakeAndAddRef(this, mBuffer.release())); } void @@ -505,13 +507,14 @@ public: : SocketIOTask(aIO) { } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(!GetIO()->IsConsumerThread()); if (!IsCanceled()) { GetIO()->Listen(); } + return NS_OK; } }; @@ -523,12 +526,14 @@ public: : SocketIOTask(aIO) { } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(!GetIO()->IsConsumerThread()); MOZ_ASSERT(!IsCanceled()); GetIO()->Connect(); + + return NS_OK; } }; @@ -540,21 +545,23 @@ public: : SocketIOTask(aIO) { } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(GetIO()->IsConsumerThread()); if (IsCanceled()) { - return; + return NS_OK; } BluetoothSocketIO* io = GetIO(); if (io->IsShutdownOnConsumerThread()) { - return; + return NS_OK; } io->ClearDelayedConnectTask(); - io->GetIOLoop()->PostTask(FROM_HERE, new ConnectTask(io)); + io->GetIOLoop()->PostTask(MakeAndAddRef(io)); + + return NS_OK; } }; @@ -670,11 +677,12 @@ BluetoothSocket::Connect(BluetoothUnixSocketConnector* aConnector, SetConnectionStatus(SOCKET_CONNECTING); if (aDelayMs > 0) { - DelayedConnectTask* connectTask = new DelayedConnectTask(mIO); + RefPtr connectTask = + MakeAndAddRef(mIO); mIO->SetDelayedConnectTask(connectTask); - MessageLoop::current()->PostDelayedTask(FROM_HERE, connectTask, aDelayMs); + MessageLoop::current()->PostDelayedTask(connectTask.forget(), aDelayMs); } else { - aIOLoop->PostTask(FROM_HERE, new ConnectTask(mIO)); + aIOLoop->PostTask(MakeAndAddRef(mIO)); } return NS_OK; @@ -700,7 +708,7 @@ BluetoothSocket::Listen(BluetoothUnixSocketConnector* aConnector, mIO = new BluetoothSocketIO(aConsumerLoop, aIOLoop, this, aConnector); SetConnectionStatus(SOCKET_LISTENING); - aIOLoop->PostTask(FROM_HERE, new ListenTask(mIO)); + aIOLoop->PostTask(MakeAndAddRef(mIO)); return NS_OK; } @@ -733,8 +741,7 @@ BluetoothSocket::SendSocketData(UnixSocketIOBuffer* aBuffer) MOZ_ASSERT(!mIO->IsShutdownOnConsumerThread()); mIO->GetIOLoop()->PostTask( - FROM_HERE, - new SocketIOSendTask(mIO, aBuffer)); + MakeAndAddRef>(mIO, aBuffer)); } // |SocketBase| @@ -754,7 +761,7 @@ BluetoothSocket::Close() // We sever the relationship here so any future calls to listen or connect // will create a new implementation. mIO->ShutdownOnConsumerThread(); - mIO->GetIOLoop()->PostTask(FROM_HERE, new SocketIOShutdownTask(mIO)); + mIO->GetIOLoop()->PostTask(MakeAndAddRef(mIO)); mIO = nullptr; NotifyDisconnect(); diff --git a/dom/bluetooth/common/BluetoothReplyRunnable.h b/dom/bluetooth/common/BluetoothReplyRunnable.h index 9ffc4cf1e1..158f9724f5 100644 --- a/dom/bluetooth/common/BluetoothReplyRunnable.h +++ b/dom/bluetooth/common/BluetoothReplyRunnable.h @@ -25,7 +25,7 @@ BEGIN_BLUETOOTH_NAMESPACE class BluetoothReply; -class BluetoothReplyRunnable : public nsRunnable +class BluetoothReplyRunnable : public Runnable { public: NS_DECL_NSIRUNNABLE @@ -96,7 +96,7 @@ protected: } }; -class BluetoothReplyTaskQueue : public nsRunnable +class BluetoothReplyTaskQueue : public Runnable { public: NS_DECL_NSIRUNNABLE diff --git a/dom/bluetooth/common/BluetoothService.cpp b/dom/bluetooth/common/BluetoothService.cpp index 0c050e5f14..d16ad7adac 100644 --- a/dom/bluetooth/common/BluetoothService.cpp +++ b/dom/bluetooth/common/BluetoothService.cpp @@ -434,7 +434,7 @@ BluetoothService::StartBluetooth(bool aIsStartup, } } else { BT_WARNING("Bluetooth has already been enabled before."); - RefPtr runnable = new BluetoothService::ToggleBtAck(true); + RefPtr runnable = new BluetoothService::ToggleBtAck(true); if (NS_FAILED(NS_DispatchToMainThread(runnable))) { BT_WARNING("Failed to dispatch to main thread!"); } @@ -465,7 +465,7 @@ BluetoothService::StopBluetooth(bool aIsStartup, } } else { BT_WARNING("Bluetooth has already been enabled/disabled before."); - RefPtr runnable = new BluetoothService::ToggleBtAck(false); + RefPtr runnable = new BluetoothService::ToggleBtAck(false); if (NS_FAILED(NS_DispatchToMainThread(runnable))) { BT_WARNING("Failed to dispatch to main thread!"); } diff --git a/dom/bluetooth/common/BluetoothService.h b/dom/bluetooth/common/BluetoothService.h index fb124bae55..c042792323 100644 --- a/dom/bluetooth/common/BluetoothService.h +++ b/dom/bluetooth/common/BluetoothService.h @@ -41,7 +41,7 @@ class BluetoothService : public nsIObserver friend class StartupTask; public: - class ToggleBtAck : public nsRunnable + class ToggleBtAck : public Runnable { public: ToggleBtAck(bool aEnabled); diff --git a/dom/bluetooth/common/webapi/BluetoothGattServer.cpp b/dom/bluetooth/common/webapi/BluetoothGattServer.cpp index 5d2bfc56d6..7a35be3abd 100644 --- a/dom/bluetooth/common/webapi/BluetoothGattServer.cpp +++ b/dom/bluetooth/common/webapi/BluetoothGattServer.cpp @@ -897,9 +897,9 @@ private: { mService->AssignAppUuid(mServer->mAppUuid); - RefPtr runnable = new AddServiceTaskQueue(mServer, - mService, - mPromise); + RefPtr runnable = new AddServiceTaskQueue(mServer, + mService, + mPromise); nsresult rv = NS_DispatchToMainThread(runnable.forget()); if (NS_WARN_IF(NS_FAILED(rv))) { diff --git a/dom/camera/TestGonkCameraHardware.cpp b/dom/camera/TestGonkCameraHardware.cpp index 3b1c7feeda..ce5549b4b7 100644 --- a/dom/camera/TestGonkCameraHardware.cpp +++ b/dom/camera/TestGonkCameraHardware.cpp @@ -153,7 +153,7 @@ TestGonkCameraHardwareListener::HandleEvent(nsIDOMEvent* aEvent) OnTakePictureError(mTarget); } else if (errorType.EqualsLiteral("system")) { if (!NS_WARN_IF(!mCameraThread)) { - class DeferredSystemFailure : public nsRunnable + class DeferredSystemFailure : public Runnable { public: DeferredSystemFailure(nsGonkCameraControl* aTarget) @@ -228,7 +228,7 @@ TestGonkCameraHardwareListener::HandleEvent(nsIDOMEvent* aEvent) NS_IMPL_ISUPPORTS(TestGonkCameraHardwareListener, nsIDOMEventListener) -class TestGonkCameraHardware::ControlMessage : public nsRunnable +class TestGonkCameraHardware::ControlMessage : public Runnable { public: ControlMessage(TestGonkCameraHardware* aTestHw) diff --git a/dom/crypto/CryptoBuffer.cpp b/dom/crypto/CryptoBuffer.cpp index 3beaa36b22..cefdd4287a 100644 --- a/dom/crypto/CryptoBuffer.cpp +++ b/dom/crypto/CryptoBuffer.cpp @@ -115,10 +115,9 @@ CryptoBuffer::FromJwkBase64(const nsString& aBase64) NS_ConvertUTF16toUTF8 temp(aBase64); temp.StripWhitespace(); - Base64URLDecodeOptions options; // JWK prohibits padding per RFC 7515, section 2. - options.mPadding = Base64URLDecodePadding::Reject; - nsresult rv = Base64URLDecode(temp, options, *this); + nsresult rv = Base64URLDecode(temp, Base64URLDecodePaddingPolicy::Reject, + *this); NS_ENSURE_SUCCESS(rv, rv); return NS_OK; @@ -134,9 +133,8 @@ CryptoBuffer::ToJwkBase64(nsString& aBase64) } nsAutoCString base64; - Base64URLEncodeOptions options; - options.mPad = false; - nsresult rv = Base64URLEncode(Length(), Elements(), options, base64); + nsresult rv = Base64URLEncode(Length(), Elements(), + Base64URLEncodePaddingPolicy::Omit, base64); NS_ENSURE_SUCCESS(rv, rv); CopyASCIItoUTF16(base64, aBase64); diff --git a/dom/datastore/DataStore.manifest b/dom/datastore/DataStore.manifest deleted file mode 100644 index 409bcdc958..0000000000 --- a/dom/datastore/DataStore.manifest +++ /dev/null @@ -1,2 +0,0 @@ -component {db5c9602-030f-4bff-a3de-881a8de370f2} DataStoreImpl.js -contract @mozilla.org/dom/datastore;1 {db5c9602-030f-4bff-a3de-881a8de370f2} diff --git a/dom/datastore/DataStoreCallbacks.h b/dom/datastore/DataStoreCallbacks.h deleted file mode 100644 index a59fce738a..0000000000 --- a/dom/datastore/DataStoreCallbacks.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_dom_DataStoreCallbacks_h -#define mozilla_dom_DataStoreCallbacks_h - -#include "nsISupports.h" - -namespace mozilla { -namespace dom { - -class DataStoreDB; - -class DataStoreDBCallback -{ -public: - NS_IMETHOD_(MozExternalRefCountType) AddRef(void) = 0; - NS_IMETHOD_(MozExternalRefCountType) Release(void) = 0; - - enum RunStatus { - Success, - CreatedSchema, - Error - }; - - virtual void Run(DataStoreDB* aDb, RunStatus aStatus) = 0; - -protected: - virtual ~DataStoreDBCallback() - { - } -}; - -class DataStoreRevisionCallback -{ -public: - NS_IMETHOD_(MozExternalRefCountType) AddRef(void) = 0; - NS_IMETHOD_(MozExternalRefCountType) Release(void) = 0; - - virtual void Run(const nsAString& aRevisionID) = 0; - -protected: - virtual ~DataStoreRevisionCallback() - { - } -}; - -} // namespace dom -} // namespace mozilla - -#endif // mozilla_dom_DataStoreCallbacks_h diff --git a/dom/datastore/DataStoreChangeNotifier.jsm b/dom/datastore/DataStoreChangeNotifier.jsm deleted file mode 100644 index 072c099887..0000000000 --- a/dom/datastore/DataStoreChangeNotifier.jsm +++ /dev/null @@ -1,223 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -"use strict" - -const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; - -this.EXPORTED_SYMBOLS = ["DataStoreChangeNotifier"]; - -function debug(s) { - //dump('DEBUG DataStoreChangeNotifier: ' + s + '\n'); -} - -Cu.import("resource://gre/modules/XPCOMUtils.jsm"); -Cu.import("resource://gre/modules/Services.jsm"); - -XPCOMUtils.defineLazyServiceGetter(this, "ppmm", - "@mozilla.org/parentprocessmessagemanager;1", - "nsIMessageBroadcaster"); - -XPCOMUtils.defineLazyServiceGetter(this, "dataStoreService", - "@mozilla.org/datastore-service;1", - "nsIDataStoreService"); - -XPCOMUtils.defineLazyServiceGetter(this, "systemMessenger", - "@mozilla.org/system-message-internal;1", - "nsISystemMessagesInternal"); - -var kSysMsgOnChangeShortTimeoutSec = - Services.prefs.getIntPref("dom.datastore.sysMsgOnChangeShortTimeoutSec"); -var kSysMsgOnChangeLongTimeoutSec = - Services.prefs.getIntPref("dom.datastore.sysMsgOnChangeLongTimeoutSec"); - -this.DataStoreChangeNotifier = { - children: [], - messages: [ "DataStore:Changed", "DataStore:RegisterForMessages", - "DataStore:UnregisterForMessages", - "child-process-shutdown" ], - - // These hashes are used for storing the mapping between the datastore - // identifiers (name | owner manifest URL) and their correspondent timers. - // The object literal is defined as below: - // - // { - // "datastore name 1|owner manifest URL 1": timer1, - // "datastore name 2|owner manifest URL 2": timer2, - // ... - // } - sysMsgOnChangeShortTimers: {}, - sysMsgOnChangeLongTimers: {}, - - init: function() { - debug("init"); - - this.messages.forEach((function(msgName) { - ppmm.addMessageListener(msgName, this); - }).bind(this)); - - Services.obs.addObserver(this, 'xpcom-shutdown', false); - }, - - observe: function(aSubject, aTopic, aData) { - debug("observe"); - - switch (aTopic) { - case 'xpcom-shutdown': - this.messages.forEach((function(msgName) { - ppmm.removeMessageListener(msgName, this); - }).bind(this)); - - Services.obs.removeObserver(this, 'xpcom-shutdown'); - ppmm = null; - break; - - default: - debug("Wrong observer topic: " + aTopic); - break; - } - }, - - broadcastMessage: function broadcastMessage(aData) { - debug("broadcast"); - - this.children.forEach(function(obj) { - if (obj.store == aData.store && obj.owner == aData.owner) { - obj.mm.sendAsyncMessage("DataStore:Changed:Return:OK", aData); - } - }); - }, - - broadcastSystemMessage: function(aStore, aOwner) { - debug("broadcastSystemMessage"); - - // Clear relevant timers. - var storeKey = aStore + "|" + aOwner; - var shortTimer = this.sysMsgOnChangeShortTimers[storeKey]; - if (shortTimer) { - shortTimer.cancel(); - delete this.sysMsgOnChangeShortTimers[storeKey]; - } - var longTimer = this.sysMsgOnChangeLongTimers[storeKey]; - if (longTimer) { - longTimer.cancel(); - delete this.sysMsgOnChangeLongTimers[storeKey]; - } - - systemMessenger.broadcastMessage("datastore-update-" + aStore, - { owner: aOwner }); - }, - - // Use the following logic to broadcast system messages in a moderate pattern. - // 1. When an entry is changed, start a short timer and a long timer. - // 2. If an entry is changed while the short timer is running, reset it. - // Do not reset the long timer. - // 3. Once either fires, broadcast the system message and cancel both timers. - setSystemMessageTimeout: function(aStore, aOwner) { - debug("setSystemMessageTimeout"); - - var storeKey = aStore + "|" + aOwner; - - // Reset the short timer. - var shortTimer = this.sysMsgOnChangeShortTimers[storeKey]; - if (!shortTimer) { - shortTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); - this.sysMsgOnChangeShortTimers[storeKey] = shortTimer; - } else { - shortTimer.cancel(); - } - shortTimer.initWithCallback({ notify: this.broadcastSystemMessage.bind(this, aStore, aOwner) }, - kSysMsgOnChangeShortTimeoutSec * 1000, - Ci.nsITimer.TYPE_ONE_SHOT); - - // Set the long timer if necessary. - if (!this.sysMsgOnChangeLongTimers[storeKey]) { - var longTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); - this.sysMsgOnChangeLongTimers[storeKey] = longTimer; - longTimer.initWithCallback({ notify: this.broadcastSystemMessage.bind(this, aStore, aOwner) }, - kSysMsgOnChangeLongTimeoutSec * 1000, - Ci.nsITimer.TYPE_ONE_SHOT); - } - }, - - receiveMessage: function(aMessage) { - debug("receiveMessage "); - - // No check has to be done when the message is 'child-process-shutdown'. - if (aMessage.name != "child-process-shutdown") { - let principal = aMessage.principal; - if (!principal || !dataStoreService.checkPermission(principal)) { - return; - } - } - - switch (aMessage.name) { - case "DataStore:Changed": - this.broadcastMessage(aMessage.data); - if (Services.prefs.getBoolPref("dom.sysmsg.enabled")) { - this.setSystemMessageTimeout(aMessage.data.store, aMessage.data.owner); - } - break; - - case "DataStore:RegisterForMessages": - debug("Register!"); - - for (let i = 0; i < this.children.length; ++i) { - if (this.children[i].mm == aMessage.target && - this.children[i].store == aMessage.data.store && - this.children[i].owner == aMessage.data.owner) { - debug("Register on existing index: " + i); - this.children[i].windows.push(aMessage.data.innerWindowID); - return; - } - } - - this.children.push({ mm: aMessage.target, - store: aMessage.data.store, - owner: aMessage.data.owner, - windows: [ aMessage.data.innerWindowID ]}); - break; - - case "DataStore:UnregisterForMessages": - debug("Unregister"); - - for (let i = 0; i < this.children.length; ++i) { - if (this.children[i].mm == aMessage.target) { - debug("Unregister index: " + i); - - var pos = this.children[i].windows.indexOf(aMessage.data.innerWindowID); - if (pos != -1) { - this.children[i].windows.splice(pos, 1); - } - - if (this.children[i].windows.length) { - continue; - } - - debug("Unregister delete index: " + i); - this.children.splice(i, 1); - --i; - } - } - break; - - case "child-process-shutdown": - debug("Child process shutdown"); - - for (let i = 0; i < this.children.length; ++i) { - if (this.children[i].mm == aMessage.target) { - debug("Unregister index: " + i); - this.children.splice(i, 1); - --i; - } - } - break; - - default: - debug("Wrong message: " + aMessage.name); - } - } -} - -DataStoreChangeNotifier.init(); diff --git a/dom/datastore/DataStoreCursor.cpp b/dom/datastore/DataStoreCursor.cpp deleted file mode 100644 index ea111ea2b7..0000000000 --- a/dom/datastore/DataStoreCursor.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "mozilla/dom/DataStore.h" -#include "mozilla/dom/DataStoreCursor.h" -#include "mozilla/dom/DataStoreBinding.h" -#include "mozilla/dom/DataStoreImplBinding.h" -#include "mozilla/dom/Promise.h" -#include "mozilla/ErrorResult.h" -#include "nsPIDOMWindow.h" - -namespace mozilla { -namespace dom { - -NS_IMPL_CYCLE_COLLECTING_ADDREF(DataStoreCursor) -NS_IMPL_CYCLE_COLLECTING_RELEASE(DataStoreCursor) - -NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(DataStoreCursor) - NS_INTERFACE_MAP_ENTRY(nsISupports) -NS_INTERFACE_MAP_END - -NS_IMPL_CYCLE_COLLECTION(DataStoreCursor, mCursor) - -already_AddRefed -DataStoreCursor::Constructor(GlobalObject& aGlobal, ErrorResult& aRv) -{ - RefPtr cursor = new DataStoreCursor(); - return cursor.forget(); -} - -bool -DataStoreCursor::WrapObject(JSContext* aCx, - JS::Handle aGivenProto, - JS::MutableHandle aReflector) -{ - return DataStoreCursorBinding::Wrap(aCx, this, aGivenProto, aReflector); -} - -already_AddRefed -DataStoreCursor::GetStore(ErrorResult& aRv) -{ - MOZ_ASSERT(NS_IsMainThread()); - MOZ_ASSERT(mCursor); - - return mCursor->GetStore(aRv); -} - -already_AddRefed -DataStoreCursor::Next(ErrorResult& aRv) -{ - MOZ_ASSERT(NS_IsMainThread()); - MOZ_ASSERT(mCursor); - - return mCursor->Next(aRv); -} - -void -DataStoreCursor::Close(ErrorResult& aRv) -{ - MOZ_ASSERT(NS_IsMainThread()); - MOZ_ASSERT(mCursor); - - mCursor->Close(aRv); -} - -void -DataStoreCursor::SetDataStoreCursorImpl(DataStoreCursorImpl& aCursor) -{ - MOZ_ASSERT(NS_IsMainThread()); - MOZ_ASSERT(!mCursor); - - mCursor = &aCursor; -} - -} //namespace dom -} //namespace mozilla diff --git a/dom/datastore/DataStoreCursor.h b/dom/datastore/DataStoreCursor.h deleted file mode 100644 index eca92e22f5..0000000000 --- a/dom/datastore/DataStoreCursor.h +++ /dev/null @@ -1,59 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_dom_DataStoreCursor_h -#define mozilla_dom_DataStoreCursor_h - -#include "nsAutoPtr.h" -#include "nsCOMPtr.h" -#include "nsCycleCollectionParticipant.h" - -namespace mozilla { - -class ErrorResult; - -namespace dom { - -class Promise; -class DataStore; -class GlobalObject; -class DataStoreCursorImpl; - -class DataStoreCursor final : public nsISupports -{ -public: - NS_DECL_CYCLE_COLLECTING_ISUPPORTS - NS_DECL_CYCLE_COLLECTION_CLASS(DataStoreCursor) - - // WebIDL (internal functions) - - static already_AddRefed Constructor(GlobalObject& aGlobal, - ErrorResult& aRv); - - bool WrapObject(JSContext *aCx, JS::Handle aGivenProto, JS::MutableHandle aReflector); - - // WebIDL (public APIs) - - already_AddRefed GetStore(ErrorResult& aRv); - - already_AddRefed Next(ErrorResult& aRv); - - void Close(ErrorResult& aRv); - - // This internal function (ChromeOnly) is aimed to make the DataStoreCursor - // keep a reference to the DataStoreCursorImpl which really implements the - // API's logic in JS. - void SetDataStoreCursorImpl(DataStoreCursorImpl& aCursor); - -private: - ~DataStoreCursor() {} - RefPtr mCursor; -}; - -} //namespace dom -} //namespace mozilla - -#endif diff --git a/dom/datastore/DataStoreCursorImpl.jsm b/dom/datastore/DataStoreCursorImpl.jsm deleted file mode 100644 index 0efa74f44d..0000000000 --- a/dom/datastore/DataStoreCursorImpl.jsm +++ /dev/null @@ -1,444 +0,0 @@ -/* -*- js-indent-level: 2; indent-tabs-mode: nil -*- */ -/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -'use strict' - -this.EXPORTED_SYMBOLS = ['DataStoreCursor']; - -function debug(s) { - //dump('DEBUG DataStoreCursor: ' + s + '\n'); -} - -const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; - -const STATE_INIT = 0; -const STATE_REVISION_INIT = 1; -const STATE_REVISION_CHECK = 2; -const STATE_SEND_ALL = 3; -const STATE_REVISION_SEND = 4; -const STATE_DONE = 5; - -const REVISION_ADDED = 'added'; -const REVISION_UPDATED = 'updated'; -const REVISION_REMOVED = 'removed'; -const REVISION_VOID = 'void'; -const REVISION_SKIP = 'skip' - -Cu.import('resource://gre/modules/Services.jsm'); -Cu.import('resource://gre/modules/XPCOMUtils.jsm'); - -/** - * legend: - * - RID = revision ID - * - R = revision object (with the internalRevisionId that is a number) - * - X = current object ID. - * - L = the list of revisions that we have to send - * - * State: init: do you have RID ? - * YES: state->initRevision; loop - * NO: get R; X=0; state->sendAll; send a 'clear' - * - * State: initRevision. Get R from RID. Done? - * YES: state->revisionCheck; loop - * NO: RID = null; state->init; loop - * - * State: revisionCheck: get all the revisions between R and NOW. Done? - * YES and R == NOW: state->done; loop - * YES and R != NOW: Store this revisions in L; state->revisionSend; loop - * NO: R = NOW; X=0; state->sendAll; send a 'clear' - * - * State: sendAll: is R still the last revision? - * YES get the first object with id > X. Done? - * YES: X = object.id; send 'add' - * NO: state->revisionCheck; loop - * NO: R = NOW; X=0; send a 'clear' - * - * State: revisionSend: do you have something from L to send? - * YES and L[0] == 'removed': R=L[0]; send 'remove' with ID - * YES and L[0] == 'added': R=L[0]; get the object; found? - * NO: loop - * YES: send 'add' with ID and object - * YES and L[0] == 'updated': R=L[0]; get the object; found? - * NO: loop - * YES and object.R > R: continue - * YES and object.R <= R: send 'update' with ID and object - * YES L[0] == 'void': R=L[0]; state->init; loop - * NO: state->revisionCheck; loop - * - * State: done: send a 'done' with R - */ - -/* Helper functions */ -function createDOMError(aWindow, aEvent) { - return new aWindow.DOMError(aEvent); -} - -/* DataStoreCursor object */ -this.DataStoreCursor = function(aWindow, aDataStore, aRevisionId) { - debug("DataStoreCursor created"); - this.init(aWindow, aDataStore, aRevisionId); -} - -this.DataStoreCursor.prototype = { - classDescription: 'DataStoreCursor XPCOM Component', - classID: Components.ID('{b6d14349-1eab-46b8-8513-584a7328a26b}'), - contractID: '@mozilla.org/dom/datastore-cursor-impl;1', - QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsISupports]), - - _shuttingdown: false, - - _window: null, - _dataStore: null, - _revisionId: null, - _revision: null, - _revisionsList: null, - _objectId: 0, - - _state: STATE_INIT, - - init: function(aWindow, aDataStore, aRevisionId) { - debug('DataStoreCursor init'); - - this._window = aWindow; - this._dataStore = aDataStore; - this._revisionId = aRevisionId; - - Services.obs.addObserver(this, "inner-window-destroyed", false); - - let util = aWindow.QueryInterface(Ci.nsIInterfaceRequestor) - .getInterface(Ci.nsIDOMWindowUtils); - this._innerWindowID = util.currentInnerWindowID; - }, - - observe: function(aSubject, aTopic, aData) { - let wId = aSubject.QueryInterface(Ci.nsISupportsPRUint64).data; - if (wId == this._innerWindowID) { - Services.obs.removeObserver(this, "inner-window-destroyed"); - this._shuttingdown = true; - } - }, - - // This is the implementation of the state machine. - // Read the comments at the top of this file in order to follow what it does. - stateMachine: function(aStore, aRevisionStore, aResolve, aReject) { - debug('StateMachine: ' + this._state); - - // If the window has been destroyed we cannot create the Promise object. - if (this._shuttingdown) { - return; - } - - switch (this._state) { - case STATE_INIT: - this.stateMachineInit(aStore, aRevisionStore, aResolve, aReject); - break; - - case STATE_REVISION_INIT: - this.stateMachineRevisionInit(aStore, aRevisionStore, aResolve, aReject); - break; - - case STATE_REVISION_CHECK: - this.stateMachineRevisionCheck(aStore, aRevisionStore, aResolve, aReject); - break; - - case STATE_SEND_ALL: - this.stateMachineSendAll(aStore, aRevisionStore, aResolve, aReject); - break; - - case STATE_REVISION_SEND: - this.stateMachineRevisionSend(aStore, aRevisionStore, aResolve, aReject); - break; - - case STATE_DONE: - this.stateMachineDone(aStore, aRevisionStore, aResolve, aReject); - break; - } - }, - - stateMachineInit: function(aStore, aRevisionStore, aResolve, aReject) { - debug('StateMachineInit'); - - if (this._revisionId) { - this._state = STATE_REVISION_INIT; - this.stateMachine(aStore, aRevisionStore, aResolve, aReject); - return; - } - - let self = this; - let request = aRevisionStore.openCursor(null, 'prev'); - request.onsuccess = function(aEvent) { - if (aEvent.target.result === undefined) { - aReject(self._window.DOMError("InvalidRevision", - "The DataStore is corrupted")); - return; - } - - self._revision = aEvent.target.result.value; - self._objectId = 0; - self._state = STATE_SEND_ALL; - aResolve(self.createTask('clear', null, '', null)); - } - }, - - stateMachineRevisionInit: function(aStore, aRevisionStore, aResolve, aReject) { - debug('StateMachineRevisionInit'); - - let self = this; - let request = this._dataStore._db.getInternalRevisionId( - self._revisionId, - aRevisionStore, - function(aInternalRevisionId) { - // This revision doesn't exist. - if (aInternalRevisionId == undefined) { - self._revisionId = null; - self._objectId = 0; - self._state = STATE_INIT; - self.stateMachine(aStore, aRevisionStore, aResolve, aReject); - return; - } - - self._revision = { revisionId: self._revisionId, - internalRevisionId: aInternalRevisionId }; - self._state = STATE_REVISION_CHECK; - self.stateMachine(aStore, aRevisionStore, aResolve, aReject); - } - ); - }, - - stateMachineRevisionCheck: function(aStore, aRevisionStore, aResolve, aReject) { - debug('StateMachineRevisionCheck'); - - let changes = { - addedIds: {}, - updatedIds: {}, - removedIds: {} - }; - - let self = this; - let request = aRevisionStore.mozGetAll( - self._window.IDBKeyRange.lowerBound(this._revision.internalRevisionId, true)); - request.onsuccess = function(aEvent) { - - // Optimize the operations. - for (let i = 0; i < aEvent.target.result.length; ++i) { - let data = aEvent.target.result[i]; - - switch (data.operation) { - case REVISION_ADDED: - changes.addedIds[data.objectId] = data.internalRevisionId; - break; - - case REVISION_UPDATED: - // We don't consider an update if this object has been added - // or if it has been already modified by a previous - // operation. - if (!(data.objectId in changes.addedIds) && - !(data.objectId in changes.updatedIds)) { - changes.updatedIds[data.objectId] = data.internalRevisionId; - } - break; - - case REVISION_REMOVED: - let id = data.objectId; - - // If the object has been added in this range of revisions - // we can ignore it and remove it from the list. - if (id in changes.addedIds) { - delete changes.addedIds[id]; - } else { - changes.removedIds[id] = data.internalRevisionId; - } - - if (id in changes.updatedIds) { - delete changes.updatedIds[id]; - } - break; - - case REVISION_VOID: - if (i != 0) { - dump('Internal error: Revision "' + REVISION_VOID + '" should not be found!!!\n'); - return; - } - - self._revisionId = null; - self._objectId = 0; - self._state = STATE_INIT; - self.stateMachine(aStore, aRevisionStore, aResolve, aReject); - return; - } - } - - // From changes to a map of internalRevisionId. - let revisions = {}; - function addRevisions(obj) { - for (let key in obj) { - revisions[obj[key]] = true; - } - } - - addRevisions(changes.addedIds); - addRevisions(changes.updatedIds); - addRevisions(changes.removedIds); - - // Create the list of revisions. - let list = []; - for (let i = 0; i < aEvent.target.result.length; ++i) { - let data = aEvent.target.result[i]; - - // If this revision doesn't contain useful data, we still need to keep - // it in the list because we need to update the internal revision ID. - if (!(data.internalRevisionId in revisions)) { - data.operation = REVISION_SKIP; - } - - list.push(data); - } - - if (list.length == 0) { - self._state = STATE_DONE; - self.stateMachine(aStore, aRevisionStore, aResolve, aReject); - return; - } - - // Some revision has to be sent. - self._revisionsList = list; - self._state = STATE_REVISION_SEND; - self.stateMachine(aStore, aRevisionStore, aResolve, aReject); - }; - }, - - stateMachineSendAll: function(aStore, aRevisionStore, aResolve, aReject) { - debug('StateMachineSendAll'); - - let self = this; - let request = aRevisionStore.openCursor(null, 'prev'); - request.onsuccess = function(aEvent) { - if (self._revision.revisionId != aEvent.target.result.value.revisionId) { - self._revision = aEvent.target.result.value; - self._objectId = 0; - aResolve(self.createTask('clear', null, '', null)); - return; - } - - let request = aStore.openCursor(self._window.IDBKeyRange.lowerBound(self._objectId, true)); - request.onsuccess = function(aEvent) { - let cursor = aEvent.target.result; - if (!cursor) { - self._state = STATE_REVISION_CHECK; - self.stateMachine(aStore, aRevisionStore, aResolve, aReject); - return; - } - - self._objectId = cursor.key; - aResolve(self.createTask('add', self._objectId, '', cursor.value)); - }; - }; - }, - - stateMachineRevisionSend: function(aStore, aRevisionStore, aResolve, aReject) { - debug('StateMachineRevisionSend'); - - if (!this._revisionsList.length) { - this._state = STATE_REVISION_CHECK; - this.stateMachine(aStore, aRevisionStore, aResolve, aReject); - return; - } - - this._revision = this._revisionsList.shift(); - - switch (this._revision.operation) { - case REVISION_REMOVED: - aResolve(this.createTask('remove', this._revision.objectId, '', null)); - break; - - case REVISION_ADDED: { - let request = aStore.get(this._revision.objectId); - let self = this; - request.onsuccess = function(aEvent) { - if (aEvent.target.result == undefined) { - self.stateMachine(aStore, aRevisionStore, aResolve, aReject); - return; - } - - aResolve(self.createTask('add', self._revision.objectId, '', - aEvent.target.result)); - } - break; - } - - case REVISION_UPDATED: { - let request = aStore.get(this._revision.objectId); - let self = this; - request.onsuccess = function(aEvent) { - if (aEvent.target.result == undefined) { - self.stateMachine(aStore, aRevisionStore, aResolve, aReject); - return; - } - - if (aEvent.target.result.revisionId > self._revision.internalRevisionId) { - self.stateMachine(aStore, aRevisionStore, aResolve, aReject); - return; - } - - aResolve(self.createTask('update', self._revision.objectId, '', - aEvent.target.result)); - } - break; - } - - case REVISION_VOID: - // Internal error! - dump('Internal error: Revision "' + REVISION_VOID + '" should not be found!!!\n'); - break; - - case REVISION_SKIP: - // This revision contains data that has already been sent by another one. - this.stateMachine(aStore, aRevisionStore, aResolve, aReject); - break; - } - }, - - stateMachineDone: function(aStore, aRevisionStore, aResolve, aReject) { - this.close(); - aResolve(this.createTask('done', null, this._revision.revisionId, null)); - }, - - // public interface - - get store() { - return this._dataStore.exposedObject; - }, - - next: function() { - debug('Next'); - - // If the window has been destroyed we cannot create the Promise object. - if (this._shuttingdown) { - throw Cr.NS_ERROR_FAILURE; - } - - let self = this; - return new this._window.Promise(function(aResolve, aReject) { - self._dataStore._db.cursorTxn( - function(aTxn, aStore, aRevisionStore) { - self.stateMachine(aStore, aRevisionStore, aResolve, aReject); - }, - function(aEvent) { - aReject(createDOMError(self._window, aEvent)); - } - ); - }); - }, - - close: function() { - this._dataStore.syncTerminated(this); - }, - - createTask: function(aOperation, aId, aRevisionId, aData) { - return Cu.cloneInto({ operation: aOperation, id: aId, - revisionId: aRevisionId, data: aData }, this._window); - } -}; diff --git a/dom/datastore/DataStoreDB.h b/dom/datastore/DataStoreDB.h deleted file mode 100644 index fb9380bcf8..0000000000 --- a/dom/datastore/DataStoreDB.h +++ /dev/null @@ -1,80 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_dom_DataStoreDB_h -#define mozilla_dom_DataStoreDB_h - -#include "mozilla/dom/IDBTransactionBinding.h" -#include "nsAutoPtr.h" -#include "nsIDOMEventListener.h" -#include "nsISupportsImpl.h" -#include "nsString.h" - -#define DATASTOREDB_REVISION "revision" - -namespace mozilla { -namespace dom { - -class DataStoreDBCallback; -class IDBDatabase; -class IDBFactory; -class IDBOpenDBRequest; -class IDBTransaction; - -class DataStoreDB final : public nsIDOMEventListener -{ -public: - NS_DECL_ISUPPORTS - - DataStoreDB(const nsAString& aManifestURL, const nsAString& aName); - - nsresult Open(IDBTransactionMode aMode, const Sequence& aDb, - DataStoreDBCallback* aCallback); - - nsresult Delete(); - - IDBTransaction* Transaction() const; - - // nsIDOMEventListener - NS_IMETHOD HandleEvent(nsIDOMEvent* aEvent) override; - -private: - ~DataStoreDB(); - - nsresult CreateFactoryIfNeeded(); - - nsresult UpgradeSchema(nsIDOMEvent* aEvent); - - nsresult DatabaseOpened(); - - nsresult AddEventListeners(); - - nsresult RemoveEventListeners(); - - nsString mDatabaseName; - - RefPtr mFactory; - RefPtr mRequest; - RefPtr mDatabase; - RefPtr mTransaction; - - RefPtr mCallback; - - // Internal state to avoid strange use of this class. - enum StateType { - Inactive, - Active - } mState; - - IDBTransactionMode mTransactionMode; - Sequence mObjectStores; - bool mCreatedSchema; -}; - -} // namespace dom -} // namespace mozilla - -#endif // mozilla_dom_DataStoreDB_h diff --git a/dom/datastore/DataStoreDB.jsm b/dom/datastore/DataStoreDB.jsm deleted file mode 100644 index ec563875e5..0000000000 --- a/dom/datastore/DataStoreDB.jsm +++ /dev/null @@ -1,118 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -'use strict'; - -const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; - -this.EXPORTED_SYMBOLS = ['DataStoreDB']; - -function debug(s) { - //dump('DEBUG DataStoreDB: ' + s + '\n'); -} - -const DATASTOREDB_VERSION = 1; -const DATASTOREDB_OBJECTSTORE_NAME = 'DataStoreDB'; -const DATASTOREDB_REVISION = 'revision'; -const DATASTOREDB_REVISION_INDEX = 'revisionIndex'; - -Cu.import('resource://gre/modules/IndexedDBHelper.jsm'); -Cu.import("resource://gre/modules/XPCOMUtils.jsm"); -Cu.importGlobalProperties(["indexedDB"]); - -XPCOMUtils.defineLazyServiceGetter(this, "uuidgen", - "@mozilla.org/uuid-generator;1", - "nsIUUIDGenerator"); - -this.DataStoreDB = function DataStoreDB() {} - -DataStoreDB.prototype = { - - __proto__: IndexedDBHelper.prototype, - - upgradeSchema: function(aTransaction, aDb, aOldVersion, aNewVersion) { - debug('updateSchema'); - aDb.createObjectStore(DATASTOREDB_OBJECTSTORE_NAME, { autoIncrement: true }); - let store = aDb.createObjectStore(DATASTOREDB_REVISION, - { autoIncrement: true, - keyPath: 'internalRevisionId' }); - store.createIndex(DATASTOREDB_REVISION_INDEX, 'revisionId', { unique: true }); - }, - - init: function(aOwner, aName) { - let dbName = aName + '|' + aOwner; - this.initDBHelper(dbName, DATASTOREDB_VERSION, - [DATASTOREDB_OBJECTSTORE_NAME, DATASTOREDB_REVISION]); - }, - - txn: function(aType, aCallback, aErrorCb) { - debug('Transaction request'); - this.newTxn( - aType, - aType == 'readonly' - ? [ DATASTOREDB_OBJECTSTORE_NAME ] : [ DATASTOREDB_OBJECTSTORE_NAME, DATASTOREDB_REVISION ], - function(aTxn, aStores) { - aType == 'readonly' ? aCallback(aTxn, aStores[0], null) : aCallback(aTxn, aStores[0], aStores[1]); - }, - function() {}, - aErrorCb - ); - }, - - cursorTxn: function(aCallback, aErrorCb) { - debug('Cursor transaction request'); - this.newTxn( - 'readonly', - [ DATASTOREDB_OBJECTSTORE_NAME, DATASTOREDB_REVISION ], - function(aTxn, aStores) { - aCallback(aTxn, aStores[0], aStores[1]); - }, - function() {}, - aErrorCb - ); - }, - - revisionTxn: function(aType, aCallback, aErrorCb) { - debug("Transaction request"); - this.newTxn( - aType, - DATASTOREDB_REVISION, - aCallback, - function() {}, - aErrorCb - ); - }, - - addRevision: function(aStore, aKey, aType, aSuccessCb) { - debug("AddRevision: " + aKey + " - " + aType); - let revisionId = uuidgen.generateUUID().toString(); - let request = aStore.put({ revisionId: revisionId, objectId: aKey, operation: aType }); - request.onsuccess = function() { - aSuccessCb(revisionId); - } - }, - - getInternalRevisionId: function(aRevisionId, aStore, aSuccessCb) { - debug('GetInternalRevisionId'); - let request = aStore.index(DATASTOREDB_REVISION_INDEX).getKey(aRevisionId); - request.onsuccess = function(aEvent) { - aSuccessCb(aEvent.target.result); - } - }, - - clearRevisions: function(aStore, aSuccessCb) { - debug("ClearRevisions"); - let request = aStore.clear(); - request.onsuccess = function() { - aSuccessCb(); - } - }, - - delete: function() { - debug('delete'); - this.close(); - indexedDB.deleteDatabase(this.dbName); - debug('database deleted'); - } -} diff --git a/dom/datastore/DataStoreImpl.js b/dom/datastore/DataStoreImpl.js deleted file mode 100644 index 6c47605c32..0000000000 --- a/dom/datastore/DataStoreImpl.js +++ /dev/null @@ -1,549 +0,0 @@ -/* -*- js-indent-level: 2; indent-tabs-mode: nil -*- */ -/* vim: set ft=javascript ts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -'use strict' - -function debug(s) { - //dump('DEBUG DataStore: ' + s + '\n'); -} - -const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; - -const REVISION_ADDED = "added"; -const REVISION_UPDATED = "updated"; -const REVISION_REMOVED = "removed"; -const REVISION_VOID = "void"; - -// This value has to be tuned a bit. Currently it's just a guess -// and yet we don't know if it's too low or too high. -const MAX_REQUESTS = 25; - -Cu.import("resource://gre/modules/DataStoreCursorImpl.jsm"); -Cu.import("resource://gre/modules/DataStoreDB.jsm"); -Cu.import('resource://gre/modules/Services.jsm'); -Cu.import('resource://gre/modules/XPCOMUtils.jsm'); -Cu.importGlobalProperties(["indexedDB"]); - -XPCOMUtils.defineLazyServiceGetter(this, "cpmm", - "@mozilla.org/childprocessmessagemanager;1", - "nsIMessageSender"); - -/* Helper functions */ -function createDOMError(aWindow, aEvent) { - return new aWindow.DOMError(aEvent); -} - -function throwInvalidArg(aWindow) { - return aWindow.Promise.reject( - new aWindow.DOMError("SyntaxError", "Non-numeric or invalid id")); -} - -function throwReadOnly(aWindow) { - return aWindow.Promise.reject( - new aWindow.DOMError("ReadOnlyError", "DataStore in readonly mode")); -} - -function validateId(aId) { - // If string, it cannot be empty. - if (typeof(aId) == 'string') { - return aId.length; - } - - aId = parseInt(aId); - return (!isNaN(aId) && aId > 0); -} - -/* DataStore object */ -function DataStore() { - debug("DataStore created"); -} - -DataStore.prototype = { - classDescription: "DataStore XPCOM Component", - classID: Components.ID("{db5c9602-030f-4bff-a3de-881a8de370f2}"), - contractID: "@mozilla.org/dom/datastore-impl;1", - QueryInterface: XPCOMUtils.generateQI([Ci.nsIDataStore, Ci.nsISupports, - Ci.nsIObserver]), - - callbacks: [], - - _window: null, - _name: null, - _owner: null, - _readOnly: null, - _revisionId: null, - _exposedObject: null, - _cursor: null, - _shuttingdown: false, - _eventTarget: null, - - init: function(aWindow, aName, aOwner, aReadOnly) { - debug("DataStore init"); - - this._window = aWindow; - this._name = aName; - this._owner = aOwner; - this._readOnly = aReadOnly; - - this._db = new DataStoreDB(); - this._db.init(aOwner, aName); - - Services.obs.addObserver(this, "inner-window-destroyed", false); - - let util = aWindow.QueryInterface(Ci.nsIInterfaceRequestor) - .getInterface(Ci.nsIDOMWindowUtils); - this._innerWindowID = util.currentInnerWindowID; - - cpmm.addMessageListener("DataStore:Changed:Return:OK", this); - cpmm.sendAsyncMessage("DataStore:RegisterForMessages", - { store: this._name, owner: this._owner, - innerWindowID: this._innerWindowID }, - null, - this._window.document.nodePrincipal); - }, - - observe: function(aSubject, aTopic, aData) { - let wId = aSubject.QueryInterface(Ci.nsISupportsPRUint64).data; - if (wId == this._innerWindowID) { - Services.obs.removeObserver(this, "inner-window-destroyed"); - - cpmm.removeMessageListener("DataStore:Changed:Return:OK", this); - cpmm.sendAsyncMessage("DataStore:UnregisterForMessages", - { innerWindowID: this._innerWindowID }, - null, - this._window.document.nodePrincipal); - this._shuttingdown = true; - this._db.close(); - } - }, - - setEventTarget: function(aEventTarget) { - this._eventTarget = aEventTarget; - }, - - newDBPromise: function(aTxnType, aFunction) { - let self = this; - return new this._window.Promise(function(aResolve, aReject) { - debug("DBPromise started"); - self._db.txn( - aTxnType, - function(aTxn, aStore, aRevisionStore) { - debug("DBPromise success"); - aFunction(aResolve, aReject, aTxn, aStore, aRevisionStore); - }, - function(aEvent) { - debug("DBPromise error"); - aReject(createDOMError(self._window, aEvent)); - } - ); - }); - }, - - checkRevision: function(aReject, aRevisionStore, aRevisionId, aCallback) { - if (!aRevisionId) { - aCallback(); - return; - } - - let self = this; - - let request = aRevisionStore.openCursor(null, 'prev'); - request.onsuccess = function(aEvent) { - let cursor = aEvent.target.result; - if (!cursor) { - dump("This cannot really happen."); - return; - } - - if (cursor.value.revisionId != aRevisionId) { - aReject(new self._window.DOMError("ConstraintError", - "RevisionId is not up-to-date")); - return; - } - - aCallback(); - } - }, - - getInternal: function(aStore, aIds, aCallback) { - debug("GetInternal: " + aIds.toSource()); - - // Creation of the results array. - let results = new this._window.Array(aIds.length); - - // We're going to create this amount of requests. - let pendingIds = aIds.length; - let indexPos = 0; - - let self = this; - - function getInternalSuccess(aEvent, aPos) { - debug("GetInternal success. Record: " + aEvent.target.result); - results[aPos] = Cu.cloneInto(aEvent.target.result, self._window); - if (!--pendingIds) { - aCallback(results); - return; - } - - if (indexPos < aIds.length) { - // Just MAX_REQUESTS requests at the same time. - let count = 0; - while (indexPos < aIds.length && ++count < MAX_REQUESTS) { - getInternalRequest(); - } - } - } - - function getInternalRequest() { - let currentPos = indexPos++; - let request = aStore.get(aIds[currentPos]); - request.onsuccess = function(aEvent) { - getInternalSuccess(aEvent, currentPos); - } - } - - getInternalRequest(); - }, - - putInternal: function(aResolve, aStore, aRevisionStore, aObj, aId) { - debug("putInternal " + aId); - - let self = this; - let request = aStore.put(aObj, aId); - request.onsuccess = function(aEvent) { - debug("putInternal success"); - - self.addRevision(aRevisionStore, aId, REVISION_UPDATED, - function() { - debug("putInternal - revisionId increased"); - // No wrap here because the result is always a int. - aResolve(aEvent.target.result); - } - ); - }; - }, - - addInternal: function(aResolve, aStore, aRevisionStore, aObj, aId) { - debug("AddInternal"); - - let self = this; - let request = aStore.add(aObj, aId); - request.onsuccess = function(aEvent) { - debug("Request successful. Id: " + aEvent.target.result); - self.addRevision(aRevisionStore, aEvent.target.result, REVISION_ADDED, - function() { - debug("AddInternal - revisionId increased"); - // No wrap here because the result is always a int. - aResolve(aEvent.target.result); - } - ); - }; - }, - - removeInternal: function(aResolve, aStore, aRevisionStore, aId) { - debug("RemoveInternal"); - - let self = this; - let request = aStore.get(aId); - request.onsuccess = function(aEvent) { - debug("RemoveInternal success. Record: " + aEvent.target.result); - if (aEvent.target.result === undefined) { - aResolve(false); - return; - } - - let deleteRequest = aStore.delete(aId); - deleteRequest.onsuccess = function() { - debug("RemoveInternal success"); - self.addRevision(aRevisionStore, aId, REVISION_REMOVED, - function() { - aResolve(true); - } - ); - }; - }; - }, - - clearInternal: function(aResolve, aStore, aRevisionStore) { - debug("ClearInternal"); - - let self = this; - let request = aStore.clear(); - request.onsuccess = function() { - debug("ClearInternal success"); - self._db.clearRevisions(aRevisionStore, - function() { - debug("Revisions cleared"); - - self.addRevision(aRevisionStore, null, REVISION_VOID, - function() { - debug("ClearInternal - revisionId increased"); - aResolve(); - } - ); - } - ); - }; - }, - - getLengthInternal: function(aResolve, aStore) { - debug("GetLengthInternal"); - - let request = aStore.count(); - request.onsuccess = function(aEvent) { - debug("GetLengthInternal success: " + aEvent.target.result); - // No wrap here because the result is always a int. - aResolve(aEvent.target.result); - }; - }, - - addRevision: function(aRevisionStore, aId, aType, aSuccessCb) { - let self = this; - this._db.addRevision(aRevisionStore, aId, aType, - function(aRevisionId) { - self._revisionId = aRevisionId; - self.sendNotification(aId, aType, aRevisionId); - aSuccessCb(); - } - ); - }, - - retrieveRevisionId: function(aSuccessCb) { - let self = this; - this._db.revisionTxn( - 'readonly', - function(aTxn, aRevisionStore) { - debug("RetrieveRevisionId transaction success"); - - let request = aRevisionStore.openCursor(null, 'prev'); - request.onsuccess = function(aEvent) { - let cursor = aEvent.target.result; - if (cursor) { - self._revisionId = cursor.value.revisionId; - } - - aSuccessCb(self._revisionId); - }; - } - ); - }, - - sendNotification: function(aId, aOperation, aRevisionId) { - debug("SendNotification"); - if (aOperation == REVISION_VOID) { - aOperation = "cleared"; - } - - cpmm.sendAsyncMessage("DataStore:Changed", - { store: this.name, owner: this._owner, - message: { revisionId: aRevisionId, id: aId, - operation: aOperation, owner: this._owner } }, - null, - this._window.document.nodePrincipal); - }, - - receiveMessage: function(aMessage) { - debug("receiveMessage"); - - if (aMessage.name != "DataStore:Changed:Return:OK") { - debug("Wrong message: " + aMessage.name); - return; - } - - // If this message is not for this DataStore, let's ignore it. - if (aMessage.data.owner != this._owner || - aMessage.data.store != this._name) { - return; - } - - let self = this; - - this.retrieveRevisionId( - function() { - // If the window has been destroyed we don't emit the events. - if (self._shuttingdown) { - return; - } - - // If we have an active cursor we don't emit events. - if (self._cursor) { - return; - } - - let event = new self._window.DataStoreChangeEvent('change', - aMessage.data.message); - self._eventTarget.dispatchEvent(event); - } - ); - }, - - get exposedObject() { - debug("get exposedObject"); - return this._exposedObject; - }, - - set exposedObject(aObject) { - debug("set exposedObject"); - this._exposedObject = aObject; - }, - - syncTerminated: function(aCursor) { - // This checks is to avoid that an invalid cursor stops a sync. - if (this._cursor == aCursor) { - this._cursor = null; - } - }, - - // Public interface : - - get name() { - return this._name; - }, - - get owner() { - return this._owner; - }, - - get readOnly() { - return this._readOnly; - }, - - get: function() { - let ids = Array.prototype.slice.call(arguments); - for (let i = 0; i < ids.length; ++i) { - if (!validateId(ids[i])) { - return throwInvalidArg(this._window); - } - } - - if (ids.length == 0) { - return this._window.Promise.resolve(new this._window.Array()); - } - - let self = this; - - // Promise - return this.newDBPromise("readonly", - function(aResolve, aReject, aTxn, aStore, aRevisionStore) { - self.getInternal(aStore, ids, - function(aResults) { - aResolve(ids.length > 1 ? aResults : aResults[0]); - }); - } - ); - }, - - put: function(aObj, aId, aRevisionId) { - if (!validateId(aId)) { - return throwInvalidArg(this._window); - } - - if (this._readOnly) { - return throwReadOnly(this._window); - } - - let self = this; - - // Promise - return this.newDBPromise("readwrite", - function(aResolve, aReject, aTxn, aStore, aRevisionStore) { - self.checkRevision(aReject, aRevisionStore, aRevisionId, function() { - self.putInternal(aResolve, aStore, aRevisionStore, aObj, aId); - }); - } - ); - }, - - add: function(aObj, aId, aRevisionId) { - if (aId) { - if (!validateId(aId)) { - return throwInvalidArg(this._window); - } - } - - if (this._readOnly) { - return throwReadOnly(this._window); - } - - let self = this; - - // Promise - return this.newDBPromise("readwrite", - function(aResolve, aReject, aTxn, aStore, aRevisionStore) { - self.checkRevision(aReject, aRevisionStore, aRevisionId, function() { - self.addInternal(aResolve, aStore, aRevisionStore, aObj, aId); - }); - } - ); - }, - - remove: function(aId, aRevisionId) { - if (!validateId(aId)) { - return throwInvalidArg(this._window); - } - - if (this._readOnly) { - return throwReadOnly(this._window); - } - - let self = this; - - // Promise - return this.newDBPromise("readwrite", - function(aResolve, aReject, aTxn, aStore, aRevisionStore) { - self.checkRevision(aReject, aRevisionStore, aRevisionId, function() { - self.removeInternal(aResolve, aStore, aRevisionStore, aId); - }); - } - ); - }, - - clear: function(aRevisionId) { - if (this._readOnly) { - return throwReadOnly(this._window); - } - - let self = this; - - // Promise - return this.newDBPromise("readwrite", - function(aResolve, aReject, aTxn, aStore, aRevisionStore) { - self.checkRevision(aReject, aRevisionStore, aRevisionId, function() { - self.clearInternal(aResolve, aStore, aRevisionStore); - }); - } - ); - }, - - get revisionId() { - return this._revisionId; - }, - - getLength: function() { - let self = this; - - // Promise - return this.newDBPromise("readonly", - function(aResolve, aReject, aTxn, aStore, aRevisionStore) { - self.getLengthInternal(aResolve, aStore); - } - ); - }, - - sync: function(aRevisionId) { - debug("Sync"); - this._cursor = new DataStoreCursor(this._window, this, aRevisionId); - - let cursorImpl = this._window.DataStoreCursorImpl. - _create(this._window, this._cursor); - - let exposedCursor = new this._window.DataStoreCursor(); - exposedCursor.setDataStoreCursorImpl(cursorImpl); - return exposedCursor; - } -}; - -this.NSGetFactory = XPCOMUtils.generateNSGetFactory([DataStore]); diff --git a/dom/datastore/DataStoreRevision.cpp b/dom/datastore/DataStoreRevision.cpp deleted file mode 100644 index 6612eb392a..0000000000 --- a/dom/datastore/DataStoreRevision.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "DataStoreRevision.h" - -#include "DataStoreCallbacks.h" -#include "DataStoreService.h" -#include "mozilla/dom/DataStoreBinding.h" -#include "mozilla/dom/IDBObjectStore.h" -#include "mozilla/dom/IDBRequest.h" -#include "mozilla/dom/ToJSValue.h" -#include "nsIDOMEvent.h" - -namespace mozilla { -namespace dom { - -NS_IMPL_ISUPPORTS(DataStoreRevision, nsIDOMEventListener) - -// Note: this code in it must not assume anything about the compartment cx is -// in. -nsresult -DataStoreRevision::AddRevision(JSContext* aCx, - IDBObjectStore* aStore, - uint32_t aObjectId, - RevisionType aRevisionType, - DataStoreRevisionCallback* aCallback) -{ - MOZ_ASSERT(aStore); - MOZ_ASSERT(aCallback); - - RefPtr service = DataStoreService::Get(); - if (!service) { - return NS_ERROR_FAILURE; - } - - nsString id; - nsresult rv = service->GenerateUUID(mRevisionID); - if (NS_WARN_IF(NS_FAILED(rv))) { - return rv; - } - - DataStoreRevisionData data; - data.mRevisionId = mRevisionID; - data.mObjectId = aObjectId; - - switch (aRevisionType) { - case RevisionVoid: - data.mOperation = NS_LITERAL_STRING("void"); - break; - - default: - MOZ_CRASH("This should not happen"); - } - - JS::Rooted value(aCx); - if (!ToJSValue(aCx, data, &value)) { - return NS_ERROR_FAILURE; - } - - ErrorResult error; - mRequest = aStore->Put(aCx, value, JS::UndefinedHandleValue, error); - if (NS_WARN_IF(error.Failed())) { - return error.StealNSResult(); - } - - rv = mRequest->EventTarget::AddEventListener(NS_LITERAL_STRING("success"), - this, false); - if (NS_WARN_IF(NS_FAILED(rv))) { - return rv; - } - - mCallback = aCallback; - return NS_OK; -} - -NS_IMETHODIMP -DataStoreRevision::HandleEvent(nsIDOMEvent* aEvent) -{ - nsString type; - nsresult rv = aEvent->GetType(type); - if (NS_WARN_IF(NS_FAILED(rv))) { - return rv; - } - - if (!type.EqualsASCII("success")) { - MOZ_CRASH("This should not happen"); - } - - mRequest->RemoveEventListener(NS_LITERAL_STRING("success"), this, false); - mRequest = nullptr; - - mCallback->Run(mRevisionID); - return NS_OK; -} - -} // namespace dom -} // namespace mozilla diff --git a/dom/datastore/DataStoreRevision.h b/dom/datastore/DataStoreRevision.h deleted file mode 100644 index bf12d213cb..0000000000 --- a/dom/datastore/DataStoreRevision.h +++ /dev/null @@ -1,50 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_dom_DataStoreRevision_h -#define mozilla_dom_DataStoreRevision_h - -#include "jsapi.h" -#include "nsAutoPtr.h" -#include "nsIDOMEventListener.h" -#include "nsString.h" - -namespace mozilla { -namespace dom { - -class DataStoreRevisionCallback; -class IDBObjectStore; -class IDBRequest; - -class DataStoreRevision final : public nsIDOMEventListener -{ -public: - NS_DECL_ISUPPORTS - - enum RevisionType { - RevisionVoid - }; - - nsresult AddRevision(JSContext* aCx, - IDBObjectStore* aStore, - uint32_t aObjectId, - RevisionType aRevisionType, - DataStoreRevisionCallback* aCallback); - - // nsIDOMEventListener - NS_IMETHOD HandleEvent(nsIDOMEvent* aEvent) override; - -private: - ~DataStoreRevision() {} - RefPtr mCallback; - RefPtr mRequest; - nsString mRevisionID; -}; - -} // namespace dom -} // namespace mozilla - -#endif // mozilla_dom_DataStoreRevision_h diff --git a/dom/datastore/moz.build b/dom/datastore/moz.build deleted file mode 100644 index 4e883e3105..0000000000 --- a/dom/datastore/moz.build +++ /dev/null @@ -1,50 +0,0 @@ -# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*- -# vim: set filetype=python: -# This Source Code Form is subject to the terms of the Mozilla Public -# License, v. 2.0. If a copy of the MPL was not distributed with this -# file, You can obtain one at http://mozilla.org/MPL/2.0/. - -XPIDL_SOURCES += [ - 'nsIDataStore.idl', - 'nsIDataStoreService.idl', -] - -XPIDL_MODULE = 'dom_datastore' - -EXPORTS.mozilla.dom += [ - 'DataStore.h', - 'DataStoreCursor.h', - 'DataStoreService.h', -] - -UNIFIED_SOURCES += [ - 'DataStore.cpp', - 'DataStoreCursor.cpp', - 'DataStoreDB.cpp', - 'DataStoreRevision.cpp', - 'DataStoreService.cpp', -] - -LOCAL_INCLUDES += [ - '/js/xpconnect/wrappers', -] - -EXTRA_COMPONENTS += [ - 'DataStore.manifest', - 'DataStoreImpl.js', -] - -EXTRA_JS_MODULES += [ - 'DataStoreChangeNotifier.jsm', - 'DataStoreCursorImpl.jsm', - 'DataStoreDB.jsm', -] - -MOCHITEST_MANIFESTS += ['tests/mochitest.ini'] - -include('/ipc/chromium/chromium-config.mozbuild') - -FINAL_LIBRARY = 'xul' - -if CONFIG['GNU_CXX']: - CXXFLAGS += ['-Wshadow'] diff --git a/dom/datastore/tests/file_app.sjs b/dom/datastore/tests/file_app.sjs deleted file mode 100644 index fe161d3660..0000000000 --- a/dom/datastore/tests/file_app.sjs +++ /dev/null @@ -1,55 +0,0 @@ -var gBasePath = "tests/dom/datastore/tests/"; - -function handleRequest(request, response) { - var query = getQuery(request); - - var testToken = ''; - if ('testToken' in query) { - testToken = query.testToken; - } - - var template = 'file_app.template.webapp'; - if ('template' in query) { - template = query.template; - } - var template = gBasePath + template; - response.setHeader("Content-Type", "application/x-web-app-manifest+json", false); - response.write(readTemplate(template).replace(/TESTTOKEN/g, testToken)); -} - -// Copy-pasted incantations. There ought to be a better way to synchronously read -// a file into a string, but I guess we're trying to discourage that. -function readTemplate(path) { - var file = Components.classes["@mozilla.org/file/directory_service;1"]. - getService(Components.interfaces.nsIProperties). - get("CurWorkD", Components.interfaces.nsILocalFile); - var fis = Components.classes['@mozilla.org/network/file-input-stream;1']. - createInstance(Components.interfaces.nsIFileInputStream); - var cis = Components.classes["@mozilla.org/intl/converter-input-stream;1"]. - createInstance(Components.interfaces.nsIConverterInputStream); - var split = path.split("/"); - for(var i = 0; i < split.length; ++i) { - file.append(split[i]); - } - fis.init(file, -1, -1, false); - cis.init(fis, "UTF-8", 0, 0); - - var data = ""; - let str = {}; - let read = 0; - do { - read = cis.readString(0xffffffff, str); // read as much as we can and put it in str.value - data += str.value; - } while (read != 0); - cis.close(); - return data; -} - -function getQuery(request) { - var query = {}; - request.queryString.split('&').forEach(function (val) { - var [name, value] = val.split('='); - query[name] = unescape(value); - }); - return query; -} diff --git a/dom/datastore/tests/file_app.template.webapp b/dom/datastore/tests/file_app.template.webapp deleted file mode 100644 index 69ee31cfce..0000000000 --- a/dom/datastore/tests/file_app.template.webapp +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "Really Rapid Release (hosted)", - "description": "Updated even faster than Firefox, just to annoy slashdotters.", - "launch_path": "/tests/dom/datastore/tests/TESTTOKEN", - "icons": { "128": "default_icon" }, - "datastores-owned" : { - "foo" : { "access": "readwrite", "description" : "This store is called foo" }, - "bar" : { "access": "readonly", "description" : "This store is called bar" } - } -} diff --git a/dom/datastore/tests/file_app2.template.webapp b/dom/datastore/tests/file_app2.template.webapp deleted file mode 100644 index 25752e208c..0000000000 --- a/dom/datastore/tests/file_app2.template.webapp +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "Really Rapid Release (hosted) - app 2", - "description": "Updated even faster than Firefox, just to annoy slashdotters.", - "launch_path": "/tests/dom/datastore/tests/TESTTOKEN", - "icons": { "128": "default_icon" }, - "datastores-access" : { - "foo" : { "readonly": false, "description" : "This store is called foo" }, - "bar" : { "readonly": true, "description" : "This store is called bar" } - } -} diff --git a/dom/datastore/tests/file_app_install.html b/dom/datastore/tests/file_app_install.html deleted file mode 100644 index a19b1ae46e..0000000000 --- a/dom/datastore/tests/file_app_install.html +++ /dev/null @@ -1,91 +0,0 @@ - - - - - Test for DataStore - install/uninstall apps - - - diff --git a/dom/datastore/tests/file_arrays.html b/dom/datastore/tests/file_arrays.html deleted file mode 100644 index 673c6c6c6b..0000000000 --- a/dom/datastore/tests/file_arrays.html +++ /dev/null @@ -1,110 +0,0 @@ - - - - - Test for DataStore - add([array]) remove([array]) - - -
- - - diff --git a/dom/datastore/tests/file_basic.html b/dom/datastore/tests/file_basic.html deleted file mode 100644 index d8b1d40d73..0000000000 --- a/dom/datastore/tests/file_basic.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - Test for DataStore - basic operation on a readonly db - - - -
- - - diff --git a/dom/datastore/tests/file_basic_common.js b/dom/datastore/tests/file_basic_common.js deleted file mode 100644 index f73c3bee84..0000000000 --- a/dom/datastore/tests/file_basic_common.js +++ /dev/null @@ -1,119 +0,0 @@ -var gStore; - -function testGetDataStores() { - navigator.getDataStores('foo').then(function(stores) { - is(stores.length, 1, "getDataStores('foo') returns 1 element"); - is(stores[0].name, 'foo', 'The dataStore.name is foo'); - is(stores[0].readOnly, false, 'The dataStore foo is not in readonly'); - - var store = stores[0]; - ok("get" in store, "store.get exists"); - ok("put" in store, "store.put exists"); - ok("add" in store, "store.add exists"); - ok("remove" in store, "store.remove exists"); - ok("clear" in store, "store.clear exists"); - ok("revisionId" in store, "store.revisionId exists"); - ok("getLength" in store, "store.getLength exists"); - ok("sync" in store, "store.sync exists"); - - gStore = stores[0]; - - runTest(); - }, cbError); -} - -function testStoreGet(id, value) { - gStore.get(id).then(function(what) { - ok(true, "store.get() retrieves data"); - is(what, value, "store.get(" + id + ") returns " + value); - }, function() { - ok(false, "store.get(" + id + ") retrieves data"); - }).then(runTest, cbError); -} - -function testStoreAdd(value) { - return gStore.add(value).then(function(what) { - ok(true, "store.add() is called"); - ok(what > 0, "store.add() returns something"); - return what; - }, cbError); -} - -function testStorePut(value, id) { - return gStore.put(value, id).then(function() { - ok(true, "store.put() is called"); - }, cbError); -} - -function testStoreGetLength(number) { - return gStore.getLength().then(function(n) { - is(number, n, "store.getLength() returns the right number"); - }, cbError); -} - -function testStoreRemove(id) { - return gStore.remove(id).then(function() { - ok(true, "store.remove() is called"); - }, cbError); -} - -function testStoreClear() { - return gStore.clear().then(function() { - ok(true, "store.clear() is called"); - }, cbError); -} - -var tests = [ - // Test for GetDataStore - testGetDataStores, - - // Unknown ID - function() { testStoreGet(42, undefined); }, - function() { testStoreGet(42, undefined); }, // twice - - // Add + Get - number - function() { testStoreAdd(42).then(function(id) { - gId = id; runTest(); }, cbError); }, - function() { testStoreGet(gId, 42); }, - - // Add + Get - boolean - function() { testStoreAdd(true).then(function(id) { - gId = id; runTest(); }, cbError); }, - function() { testStoreGet(gId, true); }, - - // Add + Get - string - function() { testStoreAdd("hello world").then(function(id) { - gId = id; runTest(); }, cbError); }, - function() { testStoreGet(gId, "hello world"); }, - - // Put + Get - string - function() { testStorePut("hello world 2", gId).then(function() { - runTest(); }, cbError); }, - function() { testStoreGet(gId, "hello world 2"); }, - - // getLength - function() { testStoreGetLength(3).then(function() { runTest(); }, cbError); }, - - // Remove - function() { testStoreRemove(gId).then(function(what) { - runTest(); }, cbError); }, - function() { testStoreGet(gId, undefined); }, - - // Remove - wrong ID - function() { testStoreRemove(gId).then(function(what) { - runTest(); }, cbError); }, - - // Clear - function() { testStoreClear().then(function(what) { - runTest(); }, cbError); }, -]; - -function runTest() { - if (!tests.length) { - finish(); - return; - } - - var test = tests.shift(); - test(); -} diff --git a/dom/datastore/tests/file_basic_worker.html b/dom/datastore/tests/file_basic_worker.html deleted file mode 100644 index 1bd15e9b43..0000000000 --- a/dom/datastore/tests/file_basic_worker.html +++ /dev/null @@ -1,30 +0,0 @@ - - - - - Test for DataStore - basic operation on a readonly db - - -
- - - diff --git a/dom/datastore/tests/file_basic_worker.js b/dom/datastore/tests/file_basic_worker.js deleted file mode 100644 index 8238eee44a..0000000000 --- a/dom/datastore/tests/file_basic_worker.js +++ /dev/null @@ -1,19 +0,0 @@ -function is(a, b, msg) { - postMessage((a === b ? 'OK' : 'KO') + ' ' + msg) -} - -function ok(a, msg) { - postMessage((a ? 'OK' : 'KO')+ ' ' + msg) -} - -function cbError() { - postMessage('KO error'); -} - -function finish() { - postMessage('DONE'); -} - -importScripts("file_basic_common.js"); - -runTest(); diff --git a/dom/datastore/tests/file_bug1008044.html b/dom/datastore/tests/file_bug1008044.html deleted file mode 100644 index 35d1441bcb..0000000000 --- a/dom/datastore/tests/file_bug1008044.html +++ /dev/null @@ -1,46 +0,0 @@ - - - - - Test for DataStore - bug 1008044 - - -
- - - diff --git a/dom/datastore/tests/file_bug1058108.html b/dom/datastore/tests/file_bug1058108.html deleted file mode 100644 index 1859fb8493..0000000000 --- a/dom/datastore/tests/file_bug1058108.html +++ /dev/null @@ -1,40 +0,0 @@ - - - - - Test for DataStore - basic operation on a readonly db - - - -
- - - - diff --git a/dom/datastore/tests/file_bug924104.html b/dom/datastore/tests/file_bug924104.html deleted file mode 100644 index 7593c51721..0000000000 --- a/dom/datastore/tests/file_bug924104.html +++ /dev/null @@ -1,77 +0,0 @@ - - - - - Test for bug 924104 - - -
- - - diff --git a/dom/datastore/tests/file_bug957086.html b/dom/datastore/tests/file_bug957086.html deleted file mode 100644 index ef63e62b73..0000000000 --- a/dom/datastore/tests/file_bug957086.html +++ /dev/null @@ -1,34 +0,0 @@ - - - - - Test for DataStore - bug 1008044 - - -
- - - diff --git a/dom/datastore/tests/file_bug976311.html b/dom/datastore/tests/file_bug976311.html deleted file mode 100644 index 43b7f625c2..0000000000 --- a/dom/datastore/tests/file_bug976311.html +++ /dev/null @@ -1,88 +0,0 @@ - - - - - Test for DataStore - bug 976311 app1 - - -

- -
-  
-
- - - diff --git a/dom/datastore/tests/file_bug976311.template.webapp b/dom/datastore/tests/file_bug976311.template.webapp deleted file mode 100644 index 6a35fd0d26..0000000000 --- a/dom/datastore/tests/file_bug976311.template.webapp +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "Really Rapid Release (hosted)", - "description": "Updated even faster than Firefox, just to annoy slashdotters.", - "launch_path": "/tests/dom/datastore/tests/TESTTOKEN", - "icons": { "128": "default_icon" }, - "datastores-owned" : { - "foo" : { "access": "readwrite", "description" : "This store is called foo" } - }, - "datastores-access" : { - "foo" : { "readonly": false, "description" : "This store is called foo" } - } -} diff --git a/dom/datastore/tests/file_bug986056.html b/dom/datastore/tests/file_bug986056.html deleted file mode 100644 index f1fd7f94e9..0000000000 --- a/dom/datastore/tests/file_bug986056.html +++ /dev/null @@ -1,26 +0,0 @@ - - - - - Test for DataStore - bug 986056 app - - -

- -
-  
-
- - - diff --git a/dom/datastore/tests/file_bug986056.template.webapp b/dom/datastore/tests/file_bug986056.template.webapp deleted file mode 100644 index 6a35fd0d26..0000000000 --- a/dom/datastore/tests/file_bug986056.template.webapp +++ /dev/null @@ -1,12 +0,0 @@ -{ - "name": "Really Rapid Release (hosted)", - "description": "Updated even faster than Firefox, just to annoy slashdotters.", - "launch_path": "/tests/dom/datastore/tests/TESTTOKEN", - "icons": { "128": "default_icon" }, - "datastores-owned" : { - "foo" : { "access": "readwrite", "description" : "This store is called foo" } - }, - "datastores-access" : { - "foo" : { "readonly": false, "description" : "This store is called foo" } - } -} diff --git a/dom/datastore/tests/file_certifiedApp.html b/dom/datastore/tests/file_certifiedApp.html deleted file mode 100644 index c4d7d8211b..0000000000 --- a/dom/datastore/tests/file_certifiedApp.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - Test for DataStore just for certified Apps - - -
- - - diff --git a/dom/datastore/tests/file_changes.html b/dom/datastore/tests/file_changes.html deleted file mode 100644 index 366cb45070..0000000000 --- a/dom/datastore/tests/file_changes.html +++ /dev/null @@ -1,148 +0,0 @@ - - - - - Test for DataStore - basic operation on a readonly db - - -

- -
-  
-
- - diff --git a/dom/datastore/tests/file_changes2.html b/dom/datastore/tests/file_changes2.html deleted file mode 100644 index 96f7727b67..0000000000 --- a/dom/datastore/tests/file_changes2.html +++ /dev/null @@ -1,51 +0,0 @@ - - - - - Test for DataStore - basic operation on a readonly db - - -

- -
-  
-
- - diff --git a/dom/datastore/tests/file_duplicate.html b/dom/datastore/tests/file_duplicate.html deleted file mode 100644 index 3a45c2535b..0000000000 --- a/dom/datastore/tests/file_duplicate.html +++ /dev/null @@ -1,75 +0,0 @@ - - - - - Test for DataStore - duplicate keys - - -
- - - diff --git a/dom/datastore/tests/file_event_maker.html b/dom/datastore/tests/file_event_maker.html deleted file mode 100644 index 4ab6e0ed74..0000000000 --- a/dom/datastore/tests/file_event_maker.html +++ /dev/null @@ -1,32 +0,0 @@ - - - - - Test for DataStore - event maker - - - - - - diff --git a/dom/datastore/tests/file_event_receiver.html b/dom/datastore/tests/file_event_receiver.html deleted file mode 100644 index 15024ff58f..0000000000 --- a/dom/datastore/tests/file_event_receiver.html +++ /dev/null @@ -1,45 +0,0 @@ - - - - - Test for DataStore - event receiver - - - - - - - diff --git a/dom/datastore/tests/file_keys.html b/dom/datastore/tests/file_keys.html deleted file mode 100644 index ff93df42d3..0000000000 --- a/dom/datastore/tests/file_keys.html +++ /dev/null @@ -1,161 +0,0 @@ - - - - - Test for DataStore - string or unsigned long keys - - -
- - - diff --git a/dom/datastore/tests/file_notify_system_message.html b/dom/datastore/tests/file_notify_system_message.html deleted file mode 100644 index b0123a24a6..0000000000 --- a/dom/datastore/tests/file_notify_system_message.html +++ /dev/null @@ -1,120 +0,0 @@ - - - - - Test for DataStore - notify updates with system messages - - -

- -
-  
-
- - diff --git a/dom/datastore/tests/file_readonly.html b/dom/datastore/tests/file_readonly.html deleted file mode 100644 index f478a45dc8..0000000000 --- a/dom/datastore/tests/file_readonly.html +++ /dev/null @@ -1,72 +0,0 @@ - - - - - Test for DataStore - basic operation on a readonly db - - -
- - - diff --git a/dom/datastore/tests/file_sync.html b/dom/datastore/tests/file_sync.html deleted file mode 100644 index 44201f9dd3..0000000000 --- a/dom/datastore/tests/file_sync.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - Test for DataStore - sync - - - -
- - - diff --git a/dom/datastore/tests/file_sync_common.js b/dom/datastore/tests/file_sync_common.js deleted file mode 100644 index 4ff97371ee..0000000000 --- a/dom/datastore/tests/file_sync_common.js +++ /dev/null @@ -1,461 +0,0 @@ -var gStore; -var gRevisions = []; -var gCursor; -var gExpectedEvents = true; - -function testGetDataStores() { - navigator.getDataStores('foo').then(function(stores) { - is(stores.length, 1, "getDataStores('foo') returns 1 element"); - - gStore = stores[0]; - gRevisions.push(gStore.revisionId); - - gStore.onchange = function(aEvent) { - ok(gExpectedEvents, "Events received!"); - runTest(); - } - - runTest(); - }, cbError); -} - -function testBasicInterface() { - var cursor = gStore.sync(); - ok(cursor, "Cursor is created"); - is(cursor.store, gStore, "Cursor.store is the store"); - - ok("next" in cursor, "Cursor.next exists"); - ok("close" in cursor, "Cursor.close exists"); - - cursor.close(); - - runTest(); -} - -function testCursor(cursor, steps) { - if (!steps.length) { - runTest(); - return; - } - - var step = steps.shift(); - cursor.next().then(function(data) { - ok(!!data, "Cursor.next returns data"); - is(data.operation, step.operation, "Waiting for operation: '" + step.operation + "' received '" + data.operation + "'"); - - - switch (data.operation) { - case 'clear': - is (data.id, null, "'clear' operation wants a null id"); - break; - - case 'done': - is(/[0-9a-zA-Z]{8}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{12}/.test(data.revisionId), true, "done has a valid revisionId"); - is (data.revisionId, gRevisions[gRevisions.length-1], "Last revision matches"); - is (data.id, null, "'done' operation wants a null id"); - break; - - case 'add': - case 'update': - if ('id' in step) { - is(data.id, step.id, "next() add: id matches: " + data.id + " " + step.id); - } - - if ('data' in step) { - is(data.data, step.data, "next() add: data matches: " + data.data + " " + step.data); - } - - break; - - case 'remove': - if ('id' in step) { - is(data.id, step.id, "next() add: id matches: " + data.id + " " + step.id); - } - - break; - } - - testCursor(cursor, steps); - }); -} - -var tests = [ - // Test for GetDataStore - testGetDataStores, - - // interface test - testBasicInterface, - - // empty DataStore - function() { - var cursor = gStore.sync(); - var steps = [ { operation: 'clear' }, - { operation: 'done' }, - { operation: 'done' }]; - testCursor(cursor, steps); - }, - - function() { - gExpectedEvents = false; - var cursor = gStore.sync('wrong revision ID'); - var steps = [ { operation: 'clear' }, - { operation: 'done' }, - { operation: 'done' }]; - testCursor(cursor, steps); - }, - - function() { - var cursor = gStore.sync(gRevisions[0]); - var steps = [ { operation: 'done' }, - { operation: 'done' }]; - testCursor(cursor, steps); - }, - - // Test add from scratch - function() { - gExpectedEvents = true; - - gStore.add(1).then(function(id) { - gRevisions.push(gStore.revisionId); - ok(true, "Item: " + id + " added"); - }); - }, - - function() { - gStore.add(2,"foobar").then(function(id) { - gRevisions.push(gStore.revisionId); - ok(true, "Item: " + id + " added"); - }); - }, - - function() { - gStore.add(3,3).then(function(id) { - gRevisions.push(gStore.revisionId); - ok(true, "Item: " + id + " added"); - }); - }, - - function() { - gExpectedEvents = false; - var cursor = gStore.sync(); - var steps = [ { operation: 'clear', }, - { operation: 'add', id: 1, data: 1 }, - { operation: 'add', id: 3, data: 3 }, - { operation: 'add', id: 'foobar', data: 2 }, - { operation: 'done' }]; - testCursor(cursor, steps); - }, - - function() { - var cursor = gStore.sync('wrong revision ID'); - var steps = [ { operation: 'clear', }, - { operation: 'add', id: 1, data: 1 }, - { operation: 'add', id: 3, data: 3 }, - { operation: 'add', id: 'foobar', data: 2 }, - { operation: 'done' }]; - testCursor(cursor, steps); - }, - - function() { - var cursor = gStore.sync(gRevisions[0]); - var steps = [ { operation: 'add', id: 1, data: 1 }, - { operation: 'add', id: 'foobar', data: 2 }, - { operation: 'add', id: 3, data: 3 }, - { operation: 'done' }]; - testCursor(cursor, steps); - }, - - function() { - var cursor = gStore.sync(gRevisions[1]); - var steps = [ { operation: 'add', id: 'foobar', data: 2 }, - { operation: 'add', id: 3, data: 3 }, - { operation: 'done' }]; - testCursor(cursor, steps); - }, - - function() { - var cursor = gStore.sync(gRevisions[2]); - var steps = [ { operation: 'add', id: 3, data: 3 }, - { operation: 'done' }]; - testCursor(cursor, steps); - }, - - function() { - var cursor = gStore.sync(gRevisions[3]); - var steps = [ { operation: 'done' }]; - testCursor(cursor, steps); - }, - - // Test after an update - function() { - gExpectedEvents = true; - gStore.put(123, 1).then(function() { - gRevisions.push(gStore.revisionId); - }); - }, - - function() { - gExpectedEvents = false; - var cursor = gStore.sync(); - var steps = [ { operation: 'clear', }, - { operation: 'add', id: 1, data: 123 }, - { operation: 'add', id: 3, data: 3 }, - { operation: 'add', id: 'foobar', data: 2 }, - { operation: 'done' }]; - testCursor(cursor, steps); - }, - - function() { - var cursor = gStore.sync('wrong revision ID'); - var steps = [ { operation: 'clear', }, - { operation: 'add', id: 1, data: 123 }, - { operation: 'add', id: 3, data: 3 }, - { operation: 'add', id: 'foobar', data: 2 }, - { operation: 'done' }]; - testCursor(cursor, steps); - }, - - function() { - var cursor = gStore.sync(gRevisions[0]); - var steps = [ { operation: 'add', id: 1, data: 123 }, - { operation: 'add', id: 'foobar', data: 2 }, - { operation: 'add', id: 3, data: 3 }, - { operation: 'done' }]; - testCursor(cursor, steps); - }, - - function() { - var cursor = gStore.sync(gRevisions[1]); - var steps = [ { operation: 'add', id: 'foobar', data: 2 }, - { operation: 'add', id: 3, data: 3 }, - { operation: 'update', id: 1, data: 123 }, - { operation: 'done' }]; - testCursor(cursor, steps); - }, - - function() { - var cursor = gStore.sync(gRevisions[2]); - var steps = [ { operation: 'add', id: 3, data: 3 }, - { operation: 'update', id: 1, data: 123 }, - { operation: 'done' }]; - testCursor(cursor, steps); - }, - - function() { - var cursor = gStore.sync(gRevisions[3]); - var steps = [ { operation: 'update', id: 1, data: 123 }, - { operation: 'done' }]; - testCursor(cursor, steps); - }, - - function() { - var cursor = gStore.sync(gRevisions[4]); - var steps = [ { operation: 'done' }]; - testCursor(cursor, steps); - }, - - // Test after a remove - function() { - gExpectedEvents = true; - gStore.remove(3).then(function() { - gRevisions.push(gStore.revisionId); - }); - }, - - function() { - gExpectedEvents = false; - var cursor = gStore.sync(); - var steps = [ { operation: 'clear', }, - { operation: 'add', id: 1, data: 123 }, - { operation: 'add', id: 'foobar', data: 2 }, - { operation: 'done' }]; - testCursor(cursor, steps); - }, - - function() { - var cursor = gStore.sync('wrong revision ID'); - var steps = [ { operation: 'clear', }, - { operation: 'add', id: 1, data: 123 }, - { operation: 'add', id: 'foobar', data: 2 }, - { operation: 'done' }]; - testCursor(cursor, steps); - }, - - function() { - var cursor = gStore.sync(gRevisions[0]); - var steps = [ { operation: 'add', id: 1, data: 123 }, - { operation: 'add', id: 'foobar', data: 2 }, - { operation: 'done' }]; - testCursor(cursor, steps); - }, - - function() { - var cursor = gStore.sync(gRevisions[1]); - var steps = [ { operation: 'add', id: 'foobar', data: 2 }, - { operation: 'update', id: 1, data: 123 }, - { operation: 'done' }]; - testCursor(cursor, steps); - }, - - function() { - var cursor = gStore.sync(gRevisions[2]); - var steps = [ { operation: 'update', id: 1, data: 123 }, - { operation: 'done' }]; - testCursor(cursor, steps); - }, - - function() { - var cursor = gStore.sync(gRevisions[3]); - var steps = [ { operation: 'update', id: 1, data: 123 }, - { operation: 'remove', id: 3 }, - { operation: 'done' }]; - testCursor(cursor, steps); - }, - - function() { - var cursor = gStore.sync(gRevisions[4]); - var steps = [ { operation: 'remove', id: 3 }, - { operation: 'done' }]; - testCursor(cursor, steps); - }, - - function() { - var cursor = gStore.sync(gRevisions[5]); - var steps = [ { operation: 'done' }]; - testCursor(cursor, steps); - }, - - // New events when the cursor is active - function() { - gCursor = gStore.sync(); - var steps = [ { operation: 'clear', }, - { operation: 'add', id: 1, data: 123 }, - { operation: 'add', id: 'foobar', data: 2 } ]; - testCursor(gCursor, steps); - }, - - function() { - gStore.add(42, 2).then(function(id) { - ok(true, "Item: " + id + " added"); - gRevisions.push(gStore.revisionId); - runTest(); - }); - }, - - function() { - var steps = [ { operation: 'clear', }, - { operation: 'add', id: 1, data: 123 }, - { operation: 'add', id: 2, data: 42 }, - { operation: 'add', id: 'foobar', data: 2 } ] - testCursor(gCursor, steps); - }, - - function() { - gStore.put(43, 2).then(function(id) { - gRevisions.push(gStore.revisionId); - runTest(); - }); - }, - - function() { - var steps = [ { operation: 'clear', }, - { operation: 'add', id: 1, data: 123 }, - { operation: 'add', id: 2, data: 43 }, - { operation: 'add', id: 'foobar', data: 2 } ] - testCursor(gCursor, steps); - }, - - function() { - gStore.remove(2).then(function(id) { - gRevisions.push(gStore.revisionId); - runTest(); - }); - }, - - function() { - var steps = [ { operation: 'clear', }, - { operation: 'add', id: 1, data: 123 }, - { operation: 'add', id: 'foobar', data: 2 } ] - testCursor(gCursor, steps); - }, - - function() { - gStore.add(42).then(function(id) { - ok(true, "Item: " + id + " added"); - gRevisions.push(gStore.revisionId); - runTest(); - }); - }, - - function() { - var steps = [ { operation: 'clear', }, - { operation: 'add', id: 1, data: 123 }, - { operation: 'add', id: 4, data: 42 }, - { operation: 'add', id: 'foobar', data: 2 } ] - testCursor(gCursor, steps); - }, - - function() { - gStore.clear().then(function() { - gRevisions.push(gStore.revisionId); - runTest(); - }); - }, - - function() { - var steps = [ { operation: 'clear' } ]; - testCursor(gCursor, steps); - }, - - function() { - gStore.add(42).then(function(id) { - ok(true, "Item: " + id + " added"); - gRevisions.push(gStore.revisionId); - runTest(); - }); - }, - - function() { - var steps = [ { operation: 'clear', }, - { operation: 'add', id: 5, data: 42 } ]; - testCursor(gCursor, steps); - }, - - function() { - gStore.clear().then(function() { - gRevisions.push(gStore.revisionId); - runTest(); - }); - }, - - function() { - gStore.add(42).then(function(id) { - ok(true, "Item: " + id + " added"); - gRevisions.push(gStore.revisionId); - runTest(); - }); - }, - - function() { - var steps = [ { operation: 'clear' }, - { operation: 'add', id: 6, data: 42 }, - { operation: 'done'} ]; - testCursor(gCursor, steps); - }, - - function() { - gExpectedEvents = true; - gStore.add(42).then(function(id) { - }); - } -]; - -function runTest() { - if (!tests.length) { - finish(); - return; - } - - var test = tests.shift(); - test(); -} diff --git a/dom/datastore/tests/file_sync_worker.html b/dom/datastore/tests/file_sync_worker.html deleted file mode 100644 index 9f5f32cd7b..0000000000 --- a/dom/datastore/tests/file_sync_worker.html +++ /dev/null @@ -1,30 +0,0 @@ - - - - - Test for DataStore - sync - - -
- - - diff --git a/dom/datastore/tests/file_sync_worker.js b/dom/datastore/tests/file_sync_worker.js deleted file mode 100644 index c26dac54f9..0000000000 --- a/dom/datastore/tests/file_sync_worker.js +++ /dev/null @@ -1,19 +0,0 @@ -function is(a, b, msg) { - postMessage((a === b ? 'OK' : 'KO') + ' ' + msg) -} - -function ok(a, msg) { - postMessage((a ? 'OK' : 'KO')+ ' ' + msg) -} - -function cbError() { - postMessage('KO error'); -} - -function finish() { - postMessage('DONE'); -} - -importScripts("file_sync_common.js"); - -runTest(); diff --git a/dom/datastore/tests/file_transactions.html b/dom/datastore/tests/file_transactions.html deleted file mode 100644 index eb2daa8280..0000000000 --- a/dom/datastore/tests/file_transactions.html +++ /dev/null @@ -1,129 +0,0 @@ - - - - - Test for DataStore - transactional semantics - - -
- - - diff --git a/dom/datastore/tests/file_worker_close.html b/dom/datastore/tests/file_worker_close.html deleted file mode 100644 index 4c9a89339a..0000000000 --- a/dom/datastore/tests/file_worker_close.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - - Test for DataStore - - -
- - - diff --git a/dom/datastore/tests/file_worker_close.js b/dom/datastore/tests/file_worker_close.js deleted file mode 100644 index 4ca8b3c30d..0000000000 --- a/dom/datastore/tests/file_worker_close.js +++ /dev/null @@ -1,18 +0,0 @@ -function is(a, b, msg) { - postMessage((a == b ? 'OK' : 'KO')+ ' ' + msg) -} - -var store; -navigator.getDataStores('foo').then(function(stores) { - is(stores.length, 1, "getDataStores('foo') returns 1 element"); - is(stores[0].name, 'foo', 'The dataStore.name is foo'); - is(stores[0].readOnly, false, 'The dataStore foo is not in readonly'); - store = stores[0]; - postMessage('DONE'); -}); - -onclose = function() { - for (var i = 0; i < 100; ++i) { - store.get(123); - } -} diff --git a/dom/datastore/tests/mochitest.ini b/dom/datastore/tests/mochitest.ini deleted file mode 100644 index fda1c4c0c8..0000000000 --- a/dom/datastore/tests/mochitest.ini +++ /dev/null @@ -1,64 +0,0 @@ -[DEFAULT] -skip-if = (buildapp != 'b2g' && buildapp != 'mulet') -support-files = - file_app_install.html - file_readonly.html - file_basic.html - file_basic_worker.html - file_basic_worker.js - file_changes.html - file_changes2.html - file_app.sjs - file_app.template.webapp - file_app2.template.webapp - file_arrays.html - file_sync.html - file_sync_worker.html - file_sync_worker.js - file_bug924104.html - file_certifiedApp.html - file_keys.html - file_duplicate.html - file_bug976311.html - file_bug976311.template.webapp - file_bug986056.html - file_bug986056.template.webapp - file_bug1058108.html - file_event_maker.html - file_event_receiver.html - file_transactions.html - file_basic_common.js - file_sync_common.js - file_bug1008044.html - file_bug957086.html - file_notify_system_message.html - file_worker_close.html - file_worker_close.js - -[test_app_install.html] -skip-if = toolkit == 'gonk' # embed-apps doesn't work in the mochitest app -[test_readonly.html] -skip-if = (toolkit == 'android' && processor == 'x86') #x86 only bug 936226 -[test_basic.html] -[test_basic_worker.html] -[test_changes.html] -[test_arrays.html] -[test_oop.html] -skip-if = (toolkit == 'android' && processor == 'x86') #x86 only bug 936226 -[test_sync.html] -skip-if = (toolkit == 'android' && processor == 'x86') #x86 only bug 936226 -[test_sync_worker.html] -[test_bug924104.html] -[test_certifiedApp.html] -[test_keys.html] -[test_duplicate.html] -[test_bug976311.html] -[test_bug986056.html] -[test_oop_events.html] -[test_transactions.html] -[test_bug1008044.html] -[test_bug957086.html] -[test_bug1058108.html] -[test_notify_system_message.html] -skip-if = buildapp == 'mulet' || buildapp == 'b2g' || toolkit == 'android' || toolkit == 'win' #bug 1053662 - Timeout prone -[test_worker_close.html] diff --git a/dom/datastore/tests/test_sync.html b/dom/datastore/tests/test_sync.html deleted file mode 100644 index 54878f8c8a..0000000000 --- a/dom/datastore/tests/test_sync.html +++ /dev/null @@ -1,128 +0,0 @@ - - - - - Test for DataStore - sync - - - - -
- - - diff --git a/dom/datastore/tests/test_sync_worker.html b/dom/datastore/tests/test_sync_worker.html deleted file mode 100644 index 37b2dcb1c0..0000000000 --- a/dom/datastore/tests/test_sync_worker.html +++ /dev/null @@ -1,128 +0,0 @@ - - - - - Test for DataStore - sync - - - - -
- - - diff --git a/dom/events/test/test_all_synthetic_events.html b/dom/events/test/test_all_synthetic_events.html index c7ca5f9a82..efb25b9d7b 100644 --- a/dom/events/test/test_all_synthetic_events.html +++ b/dom/events/test/test_all_synthetic_events.html @@ -188,10 +188,6 @@ const kEventConstructors = { return e; }, }, - DataStoreChangeEvent: { create: function (aName, aProps) { - return new DataStoreChangeEvent(aProps); - }, - }, DeviceLightEvent: { create: function (aName, aProps) { return new DeviceLightEvent(aName, aProps); }, diff --git a/dom/fmradio/FMRadioService.h b/dom/fmradio/FMRadioService.h index 3828b72dc3..2ed26aed3e 100644 --- a/dom/fmradio/FMRadioService.h +++ b/dom/fmradio/FMRadioService.h @@ -20,7 +20,7 @@ BEGIN_FMRADIO_NAMESPACE -class FMRadioReplyRunnable : public nsRunnable +class FMRadioReplyRunnable : public Runnable { public: FMRadioReplyRunnable() : mResponseType(SuccessResponse()) {} diff --git a/dom/indexedDB/IDBFactory.cpp b/dom/indexedDB/IDBFactory.cpp index 9dbfca8793..702005c87a 100644 --- a/dom/indexedDB/IDBFactory.cpp +++ b/dom/indexedDB/IDBFactory.cpp @@ -208,31 +208,6 @@ IDBFactory::CreateForMainThreadJS(JSContext* aCx, return NS_OK; } -// static -nsresult -IDBFactory::CreateForDatastore(JSContext* aCx, - JS::Handle aOwningObject, - IDBFactory** aFactory) -{ - MOZ_ASSERT(NS_IsMainThread()); - - // There should be a null principal pushed here, but it's still chrome... - MOZ_ASSERT(!nsContentUtils::IsCallerChrome()); - - nsAutoPtr principalInfo( - new PrincipalInfo(SystemPrincipalInfo())); - - nsresult rv = - CreateForMainThreadJSInternal(aCx, aOwningObject, principalInfo, aFactory); - if (NS_WARN_IF(NS_FAILED(rv))) { - return rv; - } - - MOZ_ASSERT(!principalInfo); - - return NS_OK; -} - // static nsresult IDBFactory::CreateForWorker(JSContext* aCx, diff --git a/dom/indexedDB/IDBFactory.h b/dom/indexedDB/IDBFactory.h index bad911d914..ccd3058a73 100644 --- a/dom/indexedDB/IDBFactory.h +++ b/dom/indexedDB/IDBFactory.h @@ -90,11 +90,6 @@ public: JS::Handle aOwningObject, IDBFactory** aFactory); - static nsresult - CreateForDatastore(JSContext* aCx, - JS::Handle aOwningObject, - IDBFactory** aFactory); - static nsresult CreateForWorker(JSContext* aCx, JS::Handle aOwningObject, diff --git a/dom/interfaces/apps/nsIAppsService.idl b/dom/interfaces/apps/nsIAppsService.idl index 4ba9338267..3bb2af73ed 100644 --- a/dom/interfaces/apps/nsIAppsService.idl +++ b/dom/interfaces/apps/nsIAppsService.idl @@ -95,9 +95,4 @@ interface nsIAppsService : nsISupports * Available only in the parent process. */ bool isExtensionResource(in nsIURI uri); - - /** - * Reads the manifest file for this app and update the DataStore map - */ - void updateDataStoreEntriesFromLocalId(in unsigned long localId); }; diff --git a/dom/ipc/ContentChild.cpp b/dom/ipc/ContentChild.cpp index 8481f7783a..4afecea7fb 100644 --- a/dom/ipc/ContentChild.cpp +++ b/dom/ipc/ContentChild.cpp @@ -191,7 +191,6 @@ #include "nsIPrincipal.h" #include "nsDeviceStorage.h" #include "DomainPolicy.h" -#include "mozilla/dom/DataStoreService.h" #include "mozilla/dom/ipc/StructuredCloneData.h" #include "mozilla/dom/telephony/PTelephonyChild.h" #include "mozilla/dom/time/DateCacheCleaner.h" @@ -1187,24 +1186,6 @@ NS_IMETHODIMP MemoryReportRequestChild::Run() finished, nullptr); } -bool -ContentChild::RecvDataStoreNotify(const uint32_t& aAppId, - const nsString& aName, - const nsString& aManifestURL) -{ - RefPtr service = DataStoreService::GetOrCreate(); - if (NS_WARN_IF(!service)) { - return false; - } - - nsresult rv = service->EnableDataStore(aAppId, aName, aManifestURL); - if (NS_WARN_IF(NS_FAILED(rv))) { - return false; - } - - return true; -} - bool ContentChild::DeallocPMemoryReportRequestChild(PMemoryReportRequestChild* actor) { diff --git a/dom/ipc/ContentChild.h b/dom/ipc/ContentChild.h index 3b51d1b425..bda7414cbe 100644 --- a/dom/ipc/ContentChild.h +++ b/dom/ipc/ContentChild.h @@ -250,10 +250,6 @@ public: const FileDescriptor& aGCLog, const FileDescriptor& aCCLog) override; - virtual bool - RecvDataStoreNotify(const uint32_t& aAppId, const nsString& aName, - const nsString& aManifestURL) override; - virtual PTestShellChild* AllocPTestShellChild() override; virtual bool DeallocPTestShellChild(PTestShellChild*) override; diff --git a/dom/ipc/ContentParent.cpp b/dom/ipc/ContentParent.cpp index a0330d064f..89401998de 100755 --- a/dom/ipc/ContentParent.cpp +++ b/dom/ipc/ContentParent.cpp @@ -41,7 +41,6 @@ #include "mozilla/DataStorage.h" #include "mozilla/devtools/HeapSnapshotTempFileHelperParent.h" #include "mozilla/docshell/OfflineCacheUpdateParent.h" -#include "mozilla/dom/DataStoreService.h" #include "mozilla/dom/DataTransfer.h" #include "mozilla/dom/DOMStorageIPC.h" #include "mozilla/dom/Element.h" @@ -2290,7 +2289,6 @@ ContentParent::InitializeMembers() mIsAlive = true; mMetamorphosed = false; mSendPermissionUpdates = false; - mSendDataStoreInfos = false; mCalledClose = false; mCalledCloseWithError = false; mCalledKillHard = false; @@ -2945,27 +2943,6 @@ ContentParent::RecvAudioChannelServiceStatus( return true; } -bool -ContentParent::RecvDataStoreGetStores( - const nsString& aName, - const nsString& aOwner, - const IPC::Principal& aPrincipal, - InfallibleTArray* aValue) -{ - RefPtr service = DataStoreService::GetOrCreate(); - if (NS_WARN_IF(!service)) { - return false; - } - - nsresult rv = service->GetDataStoresFromIPC(aName, aOwner, aPrincipal, aValue); - if (NS_WARN_IF(NS_FAILED(rv))) { - return false; - } - - mSendDataStoreInfos = true; - return true; -} - void ContentParent::ForkNewProcess(bool aBlocking) { diff --git a/dom/ipc/ContentParent.h b/dom/ipc/ContentParent.h index 171ac7ba00..d478820f02 100644 --- a/dom/ipc/ContentParent.h +++ b/dom/ipc/ContentParent.h @@ -328,11 +328,6 @@ public: return mSendPermissionUpdates; } - bool NeedsDataStoreInfos() const - { - return mSendDataStoreInfos; - } - /** * Kill our subprocess and make sure it dies. Should only be used * in emergency situations since it bypasses the normal shutdown @@ -980,12 +975,6 @@ private: virtual bool RecvGetLookAndFeelCache(nsTArray* aLookAndFeelIntCache) override; - virtual bool RecvDataStoreGetStores( - const nsString& aName, - const nsString& aOwner, - const IPC::Principal& aPrincipal, - InfallibleTArray* aValue) override; - virtual bool RecvSpeakerManagerGetSpeakerStatus(bool* aValue) override; virtual bool RecvSpeakerManagerForceSpeaker(const bool& aEnable) override; @@ -1147,7 +1136,6 @@ private: bool mMetamorphosed; bool mSendPermissionUpdates; - bool mSendDataStoreInfos; bool mIsForBrowser; bool mIsNuwaProcess; bool mHasGamepadListener; diff --git a/dom/ipc/NuwaChild.cpp b/dom/ipc/NuwaChild.cpp index f01eab651b..9b3eca4d2c 100644 --- a/dom/ipc/NuwaChild.cpp +++ b/dom/ipc/NuwaChild.cpp @@ -35,7 +35,7 @@ namespace dom { namespace { -class CallNuwaSpawn: public nsRunnable +class CallNuwaSpawn: public Runnable { public: NS_IMETHOD Run() @@ -94,7 +94,7 @@ NuwaFork() sNuwaForking = true; MessageLoop* ioloop = XRE_GetIOMessageLoop(); - ioloop->PostTask(FROM_HERE, NewRunnableFunction(RunNuwaFork)); + ioloop->PostTask(NewRunnableFunction(RunNuwaFork)); } } // Anonymous namespace. @@ -185,7 +185,7 @@ GetProtoFdInfos(NuwaProtoFdInfo* aInfoList, *aInfoSize = i; } -class RunAddNewIPCProcess : public nsRunnable +class RunAddNewIPCProcess : public mozilla::Runnable { public: RunAddNewIPCProcess(pid_t aPid, diff --git a/dom/ipc/PContent.ipdl b/dom/ipc/PContent.ipdl index 5adf0903b5..f2902a1574 100644 --- a/dom/ipc/PContent.ipdl +++ b/dom/ipc/PContent.ipdl @@ -290,14 +290,6 @@ struct DataStorageItem { DataStorageType type; }; -struct DataStoreSetting { - nsString name; - nsString originURL; - nsString manifestURL; - bool readOnly; - bool enabled; -}; - // Note: Any changes to this structure should also be changed in // FileSystemUpdate below. struct VolumeInfo { @@ -491,9 +483,6 @@ child: */ async BidiKeyboardNotify(bool isLangRTL); - async DataStoreNotify(uint32_t aAppId, nsString aName, - nsString aManifestURL); - /** * Dump this process's GC and CC logs to the provided files. * @@ -946,9 +935,6 @@ parent: async AudioChannelChangeDefVolChannel(int32_t aChannel, bool aHidden); - sync DataStoreGetStores(nsString aName, nsString aOwner, Principal aPrincipal) - returns (DataStoreSetting[] dataStores); - async FilePathUpdateNotify(nsString aType, nsString aStorageName, nsString aFilepath, diff --git a/dom/ipc/PreallocatedProcessManager.cpp b/dom/ipc/PreallocatedProcessManager.cpp index 697e619947..8566f6c1eb 100644 --- a/dom/ipc/PreallocatedProcessManager.cpp +++ b/dom/ipc/PreallocatedProcessManager.cpp @@ -68,7 +68,7 @@ private: void NuwaFork(); // initialization off the critical path of app startup. - CancelableTask* mPreallocateAppProcessTask; + CancelableRunnable* mPreallocateAppProcessTask; // The array containing the preallocated processes. 4 as the inline storage size // should be enough so we don't need to grow the AutoTArray. @@ -243,7 +243,7 @@ PreallocatedProcessManagerImpl::ScheduleDelayedNuwaFork() return; } - RefPtr task = NewRunnableMethod( + RefPtr task = NewRunnableMethod( this, &PreallocatedProcessManagerImpl::DelayedNuwaFork); mPreallocateAppProcessTask = task; MessageLoop::current()->PostDelayedTask(task.forget(), diff --git a/dom/messages/SystemMessagePermissionsChecker.jsm b/dom/messages/SystemMessagePermissionsChecker.jsm index 30ec8b742d..1d90ee353d 100644 --- a/dom/messages/SystemMessagePermissionsChecker.jsm +++ b/dom/messages/SystemMessagePermissionsChecker.jsm @@ -14,10 +14,6 @@ Cu.import("resource://gre/modules/PermissionsInstaller.jsm"); Cu.import("resource://gre/modules/PermissionsTable.jsm"); Cu.import("resource://gre/modules/PermissionSettings.jsm"); -XPCOMUtils.defineLazyServiceGetter(this, "dataStoreService", - "@mozilla.org/datastore-service;1", - "nsIDataStoreService"); - this.EXPORTED_SYMBOLS = ["SystemMessagePermissionsChecker", "SystemMessagePermissionsTable"]; @@ -185,34 +181,6 @@ this.SystemMessagePermissionsChecker = { return object }, - /** - * Check if the message is a datastore-update message - * @param string aSysMsgName - * The system messsage name. - */ - isDataStoreSystemMessage: function(aSysMsgName) { - return aSysMsgName.indexOf('datastore-update-') === 0; - }, - - /** - * Check if this manifest can deliver this particular datastore message. - */ - canDeliverDataStoreSystemMessage: function(aSysMsgName, aManifestURL) { - let store = aSysMsgName.substr('datastore-update-'.length); - - // Get all the manifest URLs of the apps which can access the datastore. - let manifestURLs = dataStoreService.getAppManifestURLsForDataStore(store); - let enumerate = manifestURLs.enumerate(); - while (enumerate.hasMoreElements()) { - let manifestURL = enumerate.getNext().QueryInterface(Ci.nsISupportsString); - if (manifestURL == aManifestURL) { - return true; - } - } - - return false; - }, - /** * Check if the system message is permitted to be registered for the given * app at start-up based on the permissions claimed in the app's manifest. @@ -258,11 +226,6 @@ this.SystemMessagePermissionsChecker = { "aPageURL: " + aPageURL + ", " + "aManifestURL: " + aManifestURL); - if (this.isDataStoreSystemMessage(aSysMsgName) && - this.canDeliverDataStoreSystemMessage(aSysMsgName, aManifestURL)) { - return true; - } - let permNames = this.getSystemMessagePermissions(aSysMsgName); if (permNames === null) { return false; diff --git a/dom/moz.build b/dom/moz.build index 74d73439f1..74a58d0b25 100644 --- a/dom/moz.build +++ b/dom/moz.build @@ -55,7 +55,6 @@ DIRS += [ 'crypto', 'phonenumberutils', 'alarm', - 'datastore', 'devicestorage', 'encoding', 'events', diff --git a/dom/nfc/gonk/NfcService.cpp b/dom/nfc/gonk/NfcService.cpp index e1451f6197..34674b927f 100644 --- a/dom/nfc/gonk/NfcService.cpp +++ b/dom/nfc/gonk/NfcService.cpp @@ -169,7 +169,7 @@ NfcConsumer::Send(const CommandOptions& aOptions) } // Runnable used dispatch the NfcEventOptions on the main thread. -class NfcConsumer::DispatchNfcEventRunnable final : public nsRunnable +class NfcConsumer::DispatchNfcEventRunnable final : public Runnable { public: DispatchNfcEventRunnable(NfcService* aNfcService, const EventOptions& aEvent) @@ -391,7 +391,7 @@ NfcConsumer::OnConnectSuccess(int aIndex) } } -class NfcConsumer::ShutdownServiceRunnable final : public nsRunnable +class NfcConsumer::ShutdownServiceRunnable final : public Runnable { public: ShutdownServiceRunnable(NfcService* aNfcService) @@ -463,7 +463,7 @@ NfcService::FactoryCreate() /** * |StartConsumerRunnable| calls |NfcConsumer::Start| on the NFC thread. */ -class NfcService::StartConsumerRunnable final : public nsRunnable +class NfcService::StartConsumerRunnable final : public Runnable { public: StartConsumerRunnable(NfcConsumer* aNfcConsumer) @@ -516,7 +516,7 @@ NfcService::Start(nsINfcGonkEventListener* aListener) * thread on the main thread. This has to be down after shutting * down the NFC consumer on the NFC thread. */ -class NfcService::CleanupRunnable final : public nsRunnable +class NfcService::CleanupRunnable final : public Runnable { public: CleanupRunnable(NfcConsumer* aNfcConsumer, @@ -550,7 +550,7 @@ private: * NFC thread. Optionally, it can dispatch a |CleanupRunnable| to * the main thread for cleaning up the NFC resources. */ -class NfcService::ShutdownConsumerRunnable final : public nsRunnable +class NfcService::ShutdownConsumerRunnable final : public Runnable { public: ShutdownConsumerRunnable(NfcConsumer* aNfcConsumer, bool aCleanUp) @@ -601,7 +601,7 @@ NfcService::Shutdown() /** * |SendRunnable| calls |NfcConsumer::Send| on the NFC thread. */ -class NfcService::SendRunnable final : public nsRunnable +class NfcService::SendRunnable final : public Runnable { public: SendRunnable(NfcConsumer* aNfcConsumer, const CommandOptions& aOptions) diff --git a/dom/push/PushManager.cpp b/dom/push/PushManager.cpp index 5e49afe11d..f77f4d95db 100644 --- a/dom/push/PushManager.cpp +++ b/dom/push/PushManager.cpp @@ -98,8 +98,8 @@ CopySubscriptionKeyToArray(nsIPushSubscription* aSubscription, if (NS_FAILED(rv)) { return rv; } - if (!aKey.SetLength(keyLen, fallible) || - !aKey.ReplaceElementsAt(0, keyLen, keyBuffer, keyLen, fallible)) { + if (!aKey.SetCapacity(keyLen, fallible) || + !aKey.InsertElementsAt(0, keyBuffer, keyLen, fallible)) { return NS_ERROR_OUT_OF_MEMORY; } return NS_OK; diff --git a/dom/push/PushSubscription.cpp b/dom/push/PushSubscription.cpp index 0d82709add..db626269f8 100644 --- a/dom/push/PushSubscription.cpp +++ b/dom/push/PushSubscription.cpp @@ -341,13 +341,10 @@ PushSubscription::ToJSON(PushSubscriptionJSON& aJSON, ErrorResult& aRv) aJSON.mEndpoint.Construct(); aJSON.mEndpoint.Value() = mEndpoint; - Base64URLEncodeOptions encodeOptions; - encodeOptions.mPad = false; - aJSON.mKeys.mP256dh.Construct(); nsresult rv = Base64URLEncode(mRawP256dhKey.Length(), mRawP256dhKey.Elements(), - encodeOptions, + Base64URLEncodePaddingPolicy::Omit, aJSON.mKeys.mP256dh.Value()); if (NS_WARN_IF(NS_FAILED(rv))) { aRv.Throw(rv); @@ -356,7 +353,8 @@ PushSubscription::ToJSON(PushSubscriptionJSON& aJSON, ErrorResult& aRv) aJSON.mKeys.mAuth.Construct(); rv = Base64URLEncode(mAuthSecret.Length(), mAuthSecret.Elements(), - encodeOptions, aJSON.mKeys.mAuth.Value()); + Base64URLEncodePaddingPolicy::Omit, + aJSON.mKeys.mAuth.Value()); if (NS_WARN_IF(NS_FAILED(rv))) { aRv.Throw(rv); return; diff --git a/dom/push/PushUtil.cpp b/dom/push/PushUtil.cpp index 43d233e7a1..408b62048d 100644 --- a/dom/push/PushUtil.cpp +++ b/dom/push/PushUtil.cpp @@ -11,10 +11,20 @@ namespace dom { PushUtil::CopyArrayBufferToArray(const ArrayBuffer& aBuffer, nsTArray& aArray) { + MOZ_ASSERT(aArray.IsEmpty()); aBuffer.ComputeLengthAndData(); - return aArray.SetLength(aBuffer.Length(), fallible) && - aArray.ReplaceElementsAt(0, aBuffer.Length(), aBuffer.Data(), - aBuffer.Length(), fallible); + return aArray.SetCapacity(aBuffer.Length(), fallible) && + aArray.InsertElementsAt(0, aBuffer.Data(), aBuffer.Length(), fallible); +} + +/* static */ bool +PushUtil::CopyArrayBufferViewToArray(const ArrayBufferView& aView, + nsTArray& aArray) +{ + MOZ_ASSERT(aArray.IsEmpty()); + aView.ComputeLengthAndData(); + return aArray.SetCapacity(aView.Length(), fallible) && + aArray.InsertElementsAt(0, aView.Data(), aView.Length(), fallible); } /* static */ bool @@ -25,11 +35,7 @@ PushUtil::CopyBufferSourceToArray( return CopyArrayBufferToArray(aSource.GetAsArrayBuffer(), aArray); } if (aSource.IsArrayBufferView()) { - const ArrayBufferView& view = aSource.GetAsArrayBufferView(); - view.ComputeLengthAndData(); - return aArray.SetLength(view.Length(), fallible) && - aArray.ReplaceElementsAt(0, view.Length(), view.Data(), - view.Length(), fallible); + return CopyArrayBufferViewToArray(aSource.GetAsArrayBufferView(), aArray); } MOZ_CRASH("Uninitialized union: expected buffer or view"); } diff --git a/dom/push/PushUtil.h b/dom/push/PushUtil.h index 76843e1d33..548ae23491 100644 --- a/dom/push/PushUtil.h +++ b/dom/push/PushUtil.h @@ -5,6 +5,10 @@ #ifndef mozilla_dom_PushUtil_h #define mozilla_dom_PushUtil_h +#include "nsTArray.h" + +#include "mozilla/dom/TypedArray.h" + namespace mozilla { namespace dom { @@ -20,6 +24,10 @@ public: CopyArrayBufferToArray(const ArrayBuffer& aBuffer, nsTArray& aArray); + static bool + CopyArrayBufferViewToArray(const ArrayBufferView& aView, + nsTArray& aArray); + static bool CopyBufferSourceToArray(const OwningArrayBufferViewOrArrayBuffer& aSource, nsTArray& aArray); diff --git a/dom/system/gonk/AudioManager.cpp b/dom/system/gonk/AudioManager.cpp index c9216accae..910f52cf31 100644 --- a/dom/system/gonk/AudioManager.cpp +++ b/dom/system/gonk/AudioManager.cpp @@ -126,12 +126,22 @@ static const uint32_t sChannelStreamTbl[NUMBER_OF_AUDIO_CHANNELS] = { AUDIO_STREAM_SYSTEM, // AudioChannel::System }; -// Mappings AudioOutputProfiles to strings. -static const nsAttrValue::EnumTable kAudioOutputProfilesTable[] = { - { "primary", DEVICE_PRIMARY }, - { "headset", DEVICE_HEADSET }, - { "bluetooth", DEVICE_BLUETOOTH }, - { nullptr } + +struct AudioDeviceInfo { + /** The string the value maps to */ + const char* tag; + /** The enum value that maps to this string */ + uint32_t value; +}; + +// Mappings audio output devices to strings. +static const AudioDeviceInfo kAudioDeviceInfos[] = { + { "earpiece", AUDIO_DEVICE_OUT_EARPIECE }, + { "speaker", AUDIO_DEVICE_OUT_SPEAKER }, + { "wired_headset", AUDIO_DEVICE_OUT_WIRED_HEADSET }, + { "wired_headphone", AUDIO_DEVICE_OUT_WIRED_HEADPHONE }, + { "bt_scoheadset", AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET }, + { "bt_a2dp", AUDIO_DEVICE_OUT_BLUETOOTH_A2DP }, }; static const int kBtSampleRate = 8000; @@ -164,15 +174,15 @@ static const VolumeData gVolumeData[] = { {"audio.volume.bt_sco", AUDIO_STREAM_BLUETOOTH_SCO} }; -class RunnableCallTask : public Task +class RunnableCallTask : public Runnable { public: explicit RunnableCallTask(nsIRunnable* aRunnable) : mRunnable(aRunnable) {} - void Run() override + NS_IMETHOD Run() override { - mRunnable->Run(); + return mRunnable->Run(); } protected: nsCOMPtr mRunnable; @@ -261,7 +271,7 @@ AudioManager::HandleAudioFlingerDied() // Enable volume change notification mIsVolumeInited = true; - mAudioOutProfileUpdated = 0; + mAudioOutDevicesUpdated = 0; MaybeUpdateVolumeSettingToDatabase(true); } @@ -288,19 +298,20 @@ public: for (uint32_t idx = 0; idx < MOZ_ARRAY_LENGTH(gVolumeData); ++idx) { NS_ConvertASCIItoUTF16 volumeType(gVolumeData[idx].mChannelName); if (StringBeginsWith(aName, volumeType)) { - AudioOutputProfiles profile = GetProfileFromSettingName(aName); - MOZ_ASSERT(profile != DEVICE_ERROR); - int32_t stream = gVolumeData[idx].mStreamType; - uint32_t volIndex = aResult.isInt32() ? - aResult.toInt32() : sDefaultStreamVolumeTbl[stream]; - nsresult rv = audioManager->ValidateVolumeIndex(stream, volIndex); - if (NS_WARN_IF(NS_FAILED(rv))) { - mPromiseHolder.Reject("Error : invalid volume index.", __func__); - return rv; + uint32_t device = GetDeviceFromSettingName(aName); + MOZ_ASSERT(device != AUDIO_DEVICE_NONE); + if (aResult.isInt32()) { + int32_t stream = gVolumeData[idx].mStreamType; + uint32_t volIndex = aResult.toInt32(); + nsresult rv = audioManager->ValidateVolumeIndex(stream, volIndex); + if (NS_WARN_IF(NS_FAILED(rv))) { + mPromiseHolder.Reject("Error : invalid volume index.", __func__); + return rv; + } + audioManager->SetStreamVolumeForDevice(stream, volIndex, device); } - audioManager->InitVolumeForProfile(profile, stream, volIndex); - if (++mInitCounter == DEVICE_TOTAL_NUMBER * MOZ_ARRAY_LENGTH(gVolumeData)) { + if (++mInitCounter == MOZ_ARRAY_LENGTH(kAudioDeviceInfos) * MOZ_ARRAY_LENGTH(gVolumeData)) { mPromiseHolder.Resolve(true, __func__); } return NS_OK; @@ -319,15 +330,15 @@ public: protected: ~VolumeInitCallback() {} - AudioOutputProfiles GetProfileFromSettingName(const nsAString& aName) const + uint32_t GetDeviceFromSettingName(const nsAString& aName) const { - for (uint32_t idx = 0; kAudioOutputProfilesTable[idx].tag; ++idx) { - NS_ConvertASCIItoUTF16 profile(kAudioOutputProfilesTable[idx].tag); - if (StringEndsWith(aName, profile)) { - return static_cast(kAudioOutputProfilesTable[idx].value); + for (uint32_t idx = 0; idx < MOZ_ARRAY_LENGTH(kAudioDeviceInfos); ++idx) { + NS_ConvertASCIItoUTF16 device(kAudioDeviceInfos[idx].tag); + if (StringEndsWith(aName, device)) { + return kAudioDeviceInfos[idx].value; } } - return DEVICE_ERROR; + return AUDIO_DEVICE_NONE; } RefPtr mPromise; @@ -364,9 +375,10 @@ AudioManager::IsFmOutConnected() NS_IMPL_ISUPPORTS(AudioManager, nsIAudioManager, nsIObserver) void -AudioManager::AudioOutProfileUpdated(AudioOutputProfiles aProfile) +AudioManager::AudioOutDeviceUpdated(uint32_t aDevice) { - mAudioOutProfileUpdated |= (1 << aProfile); + MOZ_ASSERT(audio_is_output_device(aDevice)); + mAudioOutDevicesUpdated |= aDevice; } void @@ -492,7 +504,7 @@ AudioManager::HandleBluetoothStatusChanged(nsISupports* aSubject, self->mA2dpSwitchDone = true; }); MessageLoop::current()->PostDelayedTask( - FROM_HERE, new RunnableCallTask(runnable), 1000); + MakeAndAddRef(runnable), 1000); mA2dpSwitchDone = false; } else { @@ -651,7 +663,8 @@ AudioManager::HandleHeadphoneSwitchEvent(const hal::SwitchEvent& aEvent) self->UpdateHeadsetConnectionState(hal::SWITCH_STATE_OFF); self->mSwitchDone = true; }); - MessageLoop::current()->PostDelayedTask(FROM_HERE, new RunnableCallTask(runnable), 1000); + MessageLoop::current()->PostDelayedTask( + MakeAndAddRef(runnable), 1000); mSwitchDone = false; } else if (aEvent.status() != hal::SWITCH_STATE_OFF) { UpdateHeadsetConnectionState(aEvent.status()); @@ -672,7 +685,7 @@ AudioManager::HandleHeadphoneSwitchEvent(const hal::SwitchEvent& aEvent) AudioManager::AudioManager() : mPhoneState(PHONE_STATE_CURRENT) , mIsVolumeInited(false) - , mAudioOutProfileUpdated(0) + , mAudioOutDevicesUpdated(0) , mSwitchDone(true) #if defined(MOZ_B2G_BT) || ANDROID_VERSION >= 17 , mBluetoothA2dpEnabled(false) @@ -685,6 +698,10 @@ AudioManager::AudioManager() , mMuteCallToRIL(false) #endif { + for (uint32_t idx = 0; idx < MOZ_ARRAY_LENGTH(kAudioDeviceInfos); ++idx) { + mAudioDeviceTableIdMaps.Put(kAudioDeviceInfos[idx].value, idx); + } + AudioSystem::setErrorCallback(BinderDeadCallback); #if ANDROID_VERSION >= 21 android::sp callback = new GonkAudioPortCallback(); @@ -697,6 +714,11 @@ AudioManager::AudioManager() new VolumeStreamState(*this, static_cast(loop)); mStreamStates.AppendElement(streamState); } + // Initialize stream volumes with default values + for (int32_t streamType = 0; streamType < AUDIO_STREAM_MAX; streamType++) { + uint32_t volIndex = sDefaultStreamVolumeTbl[streamType]; + SetStreamVolumeForDevice(streamType, volIndex, AUDIO_DEVICE_OUT_DEFAULT); + } UpdateCachedActiveDevicesForStreams(); RegisterSwitchObserver(hal::SWITCH_HEADPHONES, mObserver); @@ -978,31 +1000,17 @@ AudioManager::ValidateVolumeIndex(int32_t aStream, uint32_t aIndex) const } nsresult -AudioManager::SetStreamVolumeForProfile(AudioOutputProfiles aProfile, - int32_t aStream, - uint32_t aIndex) +AudioManager::SetStreamVolumeForDevice(int32_t aStream, + uint32_t aIndex, + uint32_t aDevice) { if (aStream <= AUDIO_STREAM_DEFAULT || aStream >= AUDIO_STREAM_MAX) { return NS_ERROR_INVALID_ARG; } int32_t streamAlias = sStreamVolumeAliasTbl[aStream]; - VolumeStreamState* state = mStreamStates[streamAlias].get(); - // Rescaling of index is not necessary. - switch (aProfile) { - case DEVICE_PRIMARY: - state->SetVolumeIndexToAliasStreams(aIndex, AUDIO_DEVICE_OUT_SPEAKER); - break; - case DEVICE_HEADSET: - state->SetVolumeIndexToAliasStreams(aIndex, AUDIO_DEVICE_OUT_WIRED_HEADSET); - break; - case DEVICE_BLUETOOTH: - state->SetVolumeIndexToAliasStreams(aIndex, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP); - break; - default: - break; - } - return NS_OK; + VolumeStreamState* streamState = mStreamStates[streamAlias].get(); + return streamState->SetVolumeIndexToAliasStreams(aIndex, aDevice); } nsresult @@ -1056,17 +1064,15 @@ AudioManager::GetStreamVolumeIndex(int32_t aStream, uint32_t *aIndex) } nsAutoCString -AudioManager::AppendProfileToVolumeSetting(const char* aName, AudioOutputProfiles aProfile) +AudioManager::AppendDeviceToVolumeSetting(const char* aName, uint32_t aDevice) { nsAutoCString topic; topic.Assign(aName); - for (uint32_t idx = 0; kAudioOutputProfilesTable[idx].tag; ++idx) { - if (kAudioOutputProfilesTable[idx].value == aProfile) { - topic.Append("."); - topic.Append(kAudioOutputProfilesTable[idx].tag); - break; - } - } + topic.Append("."); + uint32_t index = 0; + DebugOnly exist = mAudioDeviceTableIdMaps.Get(aDevice, &index); + MOZ_ASSERT(exist); + topic.Append(kAudioDeviceInfos[index].tag); return topic; } @@ -1088,37 +1094,29 @@ AudioManager::InitVolumeFromDatabase() RefPtr callback = new VolumeInitCallback(); MOZ_ASSERT(callback); callback->GetPromise()->Then(AbstractThread::MainThread(), __func__, this, - &AudioManager::InitProfileVolumeSucceeded, - &AudioManager::InitProfileVolumeFailed); + &AudioManager::InitDeviceVolumeSucceeded, + &AudioManager::InitDeviceVolumeFailed); for (uint32_t idx = 0; idx < MOZ_ARRAY_LENGTH(gVolumeData); ++idx) { - for (uint32_t profile = 0; profile < DEVICE_TOTAL_NUMBER; ++profile) { - lock->Get(AppendProfileToVolumeSetting(gVolumeData[idx].mChannelName, - static_cast(profile)).get(), callback); + for (uint32_t idx2 = 0; idx2 < MOZ_ARRAY_LENGTH(kAudioDeviceInfos); ++idx2) { + lock->Get(AppendDeviceToVolumeSetting(gVolumeData[idx].mChannelName, + kAudioDeviceInfos[idx2].value).get(), + callback); } } } void -AudioManager::InitProfileVolumeSucceeded() +AudioManager::InitDeviceVolumeSucceeded() { mIsVolumeInited = true; MaybeUpdateVolumeSettingToDatabase(true); } void -AudioManager::InitProfileVolumeFailed(const char* aError) +AudioManager::InitDeviceVolumeFailed(const char* aError) { - // Initialize stream volumes with default values - for (uint32_t idx = 0; idx < MOZ_ARRAY_LENGTH(gVolumeData); ++idx) { - for (int32_t profile = 0; profile < DEVICE_TOTAL_NUMBER; ++profile) { - int32_t stream = gVolumeData[idx].mStreamType; - uint32_t volIndex = sDefaultStreamVolumeTbl[stream]; - InitVolumeForProfile(static_cast(profile), - stream, - volIndex); - } - } + // Default volume of AUDIO_DEVICE_OUT_DEFAULT is already set. mIsVolumeInited = true; MaybeUpdateVolumeSettingToDatabase(true); NS_WARNING(aError); @@ -1152,7 +1150,7 @@ AudioManager::MaybeUpdateVolumeSettingToDatabase(bool aForce) } // For reducing the code dependency, Gaia doesn't need to know the - // profile volume, it only need to care about different volume categories. + // device volume, it only need to care about different volume categories. // However, we need to send the setting volume to the permanent database, // so that we can store the volume setting even if the phone reboots. @@ -1164,29 +1162,21 @@ AudioManager::MaybeUpdateVolumeSettingToDatabase(bool aForce) continue; } - if (mAudioOutProfileUpdated & (1 << DEVICE_PRIMARY)) { - volume = streamState->GetVolumeIndex(AUDIO_DEVICE_OUT_SPEAKER); + uint32_t remainingDevices = mAudioOutDevicesUpdated; + for (uint32_t i = 0; remainingDevices != 0; i++) { + uint32_t device = (1 << i); + if ((device & remainingDevices) == 0) { + continue; + } + remainingDevices &= ~device; + if (!mAudioDeviceTableIdMaps.Get(device, nullptr)) { + continue; + } + volume = streamState->GetVolumeIndex(device); value.setInt32(volume); - lock->Set(AppendProfileToVolumeSetting( - gVolumeData[idx].mChannelName, - DEVICE_PRIMARY).get(), - value, nullptr, nullptr); - } - if (mAudioOutProfileUpdated & (1 << DEVICE_HEADSET)) { - volume = streamState->GetVolumeIndex(AUDIO_DEVICE_OUT_WIRED_HEADSET); - value.setInt32(volume); - lock->Set(AppendProfileToVolumeSetting( - gVolumeData[idx].mChannelName, - DEVICE_HEADSET).get(), - value, nullptr, nullptr); - } - if (mAudioOutProfileUpdated & (1 << DEVICE_BLUETOOTH)) { - volume = streamState->GetVolumeIndex(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP); - value.setInt32(volume); - lock->Set(AppendProfileToVolumeSetting( - gVolumeData[idx].mChannelName, - DEVICE_BLUETOOTH).get(), - value, nullptr, nullptr); + lock->Set(AppendDeviceToVolumeSetting(gVolumeData[idx].mChannelName, + device).get(), + value, nullptr, nullptr); } } @@ -1196,21 +1186,8 @@ AudioManager::MaybeUpdateVolumeSettingToDatabase(bool aForce) mStreamStates[streamType]->ClearDevicesChanged(); mStreamStates[streamType]->ClearVolumeIndexesChanged(); } - // Clear mAudioOutProfileUpdated - mAudioOutProfileUpdated = 0; -} - -void -AudioManager::InitVolumeForProfile(AudioOutputProfiles aProfile, - int32_t aStreamType, - uint32_t aIndex) -{ - // Set volume to streams of aStreamType and devices of Profile. - for (int32_t streamType = 0; streamType < AUDIO_STREAM_MAX; streamType++) { - if (aStreamType == sStreamVolumeAliasTbl[streamType]) { - SetStreamVolumeForProfile(aProfile, streamType, aIndex); - } - } + // Clear mAudioOutDevicesUpdated + mAudioOutDevicesUpdated = 0; } void @@ -1249,7 +1226,9 @@ AudioManager::GetDevicesForStream(int32_t aStream, bool aFromCache) return static_cast(devices); #else - return AUDIO_DEVICE_OUT_DEFAULT; + // Per audio out device volume is not supported. + // Use AUDIO_DEVICE_OUT_SPEAKER just to store audio volume to DB. + return AUDIO_DEVICE_OUT_SPEAKER; #endif } @@ -1286,6 +1265,7 @@ AudioManager::SelectDeviceFromDevices(uint32_t aOutDevices) device &= AUDIO_DEVICE_OUT_ALL_A2DP; } } + MOZ_ASSERT(audio_is_output_device(device)); return device; } AudioManager::VolumeStreamState::VolumeStreamState(AudioManager& aManager, @@ -1381,24 +1361,12 @@ AudioManager::VolumeStreamState::SetVolumeIndexToActiveDevices(uint32_t aIndex) // AudioPolicyManager::setStreamVolumeIndex() set volumes of all active // devices for stream. - nsresult rv = SetVolumeIndexToAliasDevices(aIndex, device); + nsresult rv; + rv = SetVolumeIndexToConsistentDeviceIfNeeded(aIndex, device); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } - // Workaround to make audio volume control consisitent. - // Active devices of AUDIO_STREAM_NOTIFICATION are affected by - // AUDIO_STREAM_MUSIC's activity. It makes audio volume control inconsistent. - // See Bug 1196724 - if (device != AUDIO_DEVICE_OUT_SPEAKER && - mStreamType == AUDIO_STREAM_NOTIFICATION) { - // Rescaling of index is not necessary. - rv = SetVolumeIndexToAliasDevices(aIndex, AUDIO_DEVICE_OUT_SPEAKER); - if (NS_WARN_IF(NS_FAILED(rv))) { - return rv; - } - } - return NS_OK; } @@ -1412,7 +1380,8 @@ AudioManager::VolumeStreamState::SetVolumeIndexToAliasStreams(uint32_t aIndex, // No update return NS_OK; } - nsresult rv = SetVolumeIndexToAliasDevices(aIndex, aDevice); + + nsresult rv = SetVolumeIndexToConsistentDeviceIfNeeded(aIndex, aDevice); if (NS_WARN_IF(NS_FAILED(rv))) { return rv; } @@ -1428,66 +1397,29 @@ AudioManager::VolumeStreamState::SetVolumeIndexToAliasStreams(uint32_t aIndex, } } } + return NS_OK; } nsresult -AudioManager::VolumeStreamState::SetVolumeIndexToAliasDevices(uint32_t aIndex, - uint32_t aDevice) +AudioManager::VolumeStreamState::SetVolumeIndexToConsistentDeviceIfNeeded(uint32_t aIndex, uint32_t aDevice) { -#if ANDROID_VERSION >= 17 - nsresult rv = NS_ERROR_FAILURE; - switch (aDevice) { - case AUDIO_DEVICE_OUT_EARPIECE: - case AUDIO_DEVICE_OUT_SPEAKER: - // Apply volume index of DEVICE_PRIMARY devices - rv = SetVolumeIndex(aIndex, AUDIO_DEVICE_OUT_EARPIECE); - if (NS_WARN_IF(NS_FAILED(rv))) { - return rv; - } - rv = SetVolumeIndex(aIndex, AUDIO_DEVICE_OUT_SPEAKER); - if (NS_WARN_IF(NS_FAILED(rv))) { - return rv; - } - mManager.AudioOutProfileUpdated(DEVICE_PRIMARY); - break; - case AUDIO_DEVICE_OUT_WIRED_HEADSET: - case AUDIO_DEVICE_OUT_WIRED_HEADPHONE: - // Apply volume index of DEVICE_HEADSET devices - rv = SetVolumeIndex(aIndex, AUDIO_DEVICE_OUT_WIRED_HEADSET); - if (NS_WARN_IF(NS_FAILED(rv))) { - return rv; - } - rv = SetVolumeIndex(aIndex, AUDIO_DEVICE_OUT_WIRED_HEADPHONE); - if (NS_WARN_IF(NS_FAILED(rv))) { - return rv; - } - mManager.AudioOutProfileUpdated(DEVICE_HEADSET); - break; - case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET: - case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP: - // Apply volume index of DEVICE_BLUETOOTH devices - rv = SetVolumeIndex(aIndex, AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET); - if (NS_WARN_IF(NS_FAILED(rv))) { - return rv; - } - rv = SetVolumeIndex(aIndex, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP); - if (NS_WARN_IF(NS_FAILED(rv))) { - return rv; - } - mManager.AudioOutProfileUpdated(DEVICE_BLUETOOTH); - break; - default: - rv = SetVolumeIndex(aIndex, aDevice); - if (NS_WARN_IF(NS_FAILED(rv))) { - return rv; - } - break; + nsresult rv; + if (aDevice == AUDIO_DEVICE_OUT_SPEAKER || aDevice == AUDIO_DEVICE_OUT_EARPIECE) { + // Set AUDIO_DEVICE_OUT_SPEAKER and AUDIO_DEVICE_OUT_EARPIECE to same volume. + rv = SetVolumeIndex(aIndex, AUDIO_DEVICE_OUT_SPEAKER); + if (NS_WARN_IF(NS_FAILED(rv))) { + return rv; + } + rv = SetVolumeIndex(aIndex, AUDIO_DEVICE_OUT_EARPIECE); + if (NS_WARN_IF(NS_FAILED(rv))) { + return rv; + } + } else { + // No alias device + rv = SetVolumeIndex(aIndex, aDevice); } -#else - SetVolumeIndex(aIndex, aDevice); -#endif - return NS_OK; + return rv; } nsresult @@ -1500,6 +1432,7 @@ AudioManager::VolumeStreamState::SetVolumeIndex(uint32_t aIndex, if (aUpdateCache) { mVolumeIndexes.Put(aDevice, aIndex); mIsVolumeIndexesChanged = true; + mManager.AudioOutDeviceUpdated(aDevice); } rv = AudioSystem::setStreamVolumeIndex( @@ -1509,8 +1442,11 @@ AudioManager::VolumeStreamState::SetVolumeIndex(uint32_t aIndex, return rv ? NS_ERROR_FAILURE : NS_OK; #else if (aUpdateCache) { - mVolumeIndexes.Put(AUDIO_DEVICE_OUT_DEFAULT, aIndex); + // Per audio out device volume is not supported. + // Use AUDIO_DEVICE_OUT_SPEAKER just to store audio volume to DB. + mVolumeIndexes.Put(AUDIO_DEVICE_OUT_SPEAKER, aIndex); mIsVolumeIndexesChanged = true; + mManager.AudioOutDeviceUpdated(AUDIO_DEVICE_OUT_SPEAKER); } rv = AudioSystem::setStreamVolumeIndex( static_cast(mStreamType), diff --git a/dom/system/gonk/AudioManager.h b/dom/system/gonk/AudioManager.h index ce0a8e3e3b..6b0d46fc2f 100644 --- a/dom/system/gonk/AudioManager.h +++ b/dom/system/gonk/AudioManager.h @@ -41,20 +41,6 @@ typedef Observer SwitchObserver; namespace dom { namespace gonk { -/** - * FxOS can remeber the separate volume settings on difference output profiles. - * (1) Primary : speaker, receiver - * (2) Headset : wired headphone/headset - * (3) Bluetooth : BT SCO/A2DP devices - **/ -enum AudioOutputProfiles { - DEVICE_ERROR = -1, - DEVICE_PRIMARY = 0, - DEVICE_HEADSET = 1, - DEVICE_BLUETOOTH = 2, - DEVICE_TOTAL_NUMBER = 3, -}; - class VolumeInitCallback; class AudioManager final : public nsIAudioManager @@ -99,12 +85,9 @@ public: // Set volume index to all active devices. // Active devices are chosen by android AudioPolicyManager. nsresult SetVolumeIndexToActiveDevices(uint32_t aIndex); - // Set volume index to all alias streams. Alias streams have same volume. - // It is used to update volume based on audio output profile data. + // Set volume index to all alias streams for device. Alias streams have same volume. nsresult SetVolumeIndexToAliasStreams(uint32_t aIndex, uint32_t aDevice); - // Set volume index to all alias devices in audio output profile. - // Alias devices have same volume. - nsresult SetVolumeIndexToAliasDevices(uint32_t aIndex, uint32_t aDevice); + nsresult SetVolumeIndexToConsistentDeviceIfNeeded(uint32_t aIndex, uint32_t aDevice); nsresult SetVolumeIndex(uint32_t aIndex, uint32_t aDevice, bool aUpdateCache = true); // Restore volume index to all devices. Called when AudioFlinger is restarted. void RestoreVolumeIndexToAllDevices(); @@ -122,12 +105,15 @@ protected: bool mIsVolumeInited; - // A bitwise variable for volume update of audio output profiles - uint32_t mAudioOutProfileUpdated; + // A bitwise variable for volume update of audio output devices, + // clear it after store the value into database. + uint32_t mAudioOutDevicesUpdated; // Connected devices that are controlled by setDeviceConnectionState() nsDataHashtable mConnectedDevices; + nsDataHashtable mAudioDeviceTableIdMaps; + bool mSwitchDone; #if defined(MOZ_B2G_BT) || ANDROID_VERSION >= 17 @@ -141,11 +127,11 @@ protected: bool IsFmOutConnected(); - nsresult SetStreamVolumeForProfile(AudioOutputProfiles aProfile, - int32_t aStream, - uint32_t aIndex); + nsresult SetStreamVolumeForDevice(int32_t aStream, + uint32_t aIndex, + uint32_t aDevice); nsresult SetStreamVolumeIndex(int32_t aStream, uint32_t aIndex); - nsresult GetStreamVolumeIndex(int32_t aStream, uint32_t *aIndex); + nsresult GetStreamVolumeIndex(int32_t aStream, uint32_t* aIndex); void UpdateCachedActiveDevicesForStreams(); uint32_t GetDevicesForStream(int32_t aStream, bool aFromCache = true); @@ -166,24 +152,19 @@ private: const nsCString aAddress); void HandleAudioChannelProcessChanged(); - // Initialize volume index for audio output profile - void InitVolumeForProfile(AudioOutputProfiles aProfile, - int32_t aStreamType, - uint32_t aIndex); - - // Append the audio output profile to the volume setting string. - nsAutoCString AppendProfileToVolumeSetting(const char* aName, - AudioOutputProfiles aProfile); + // Append the audio output device to the volume setting string. + nsAutoCString AppendDeviceToVolumeSetting(const char* aName, + uint32_t aDevice); // We store the volume setting in the database, these are related functions. void InitVolumeFromDatabase(); void MaybeUpdateVolumeSettingToDatabase(bool aForce = false); // Promise functions. - void InitProfileVolumeSucceeded(); - void InitProfileVolumeFailed(const char* aError); + void InitDeviceVolumeSucceeded(); + void InitDeviceVolumeFailed(const char* aError); - void AudioOutProfileUpdated(AudioOutputProfiles aProfile); + void AudioOutDeviceUpdated(uint32_t aDevice); void UpdateHeadsetConnectionState(hal::SwitchState aState); void UpdateDeviceConnectionState(bool aIsConnected, uint32_t aDevice, const nsCString& aDeviceName); diff --git a/dom/system/gonk/AutoMounter.cpp b/dom/system/gonk/AutoMounter.cpp index 587e111520..3e87726a2c 100644 --- a/dom/system/gonk/AutoMounter.cpp +++ b/dom/system/gonk/AutoMounter.cpp @@ -962,8 +962,7 @@ AutoMounter::UpdateState() if (delay <= 4000) { LOG("UpdateState: Volume '%s' is inaccessible, checking again in %d msec", vol->NameStr(), delay); MessageLoopForIO::current()-> - PostDelayedTask(FROM_HERE, - NewRunnableMethod(this, &AutoMounter::UpdateState), + PostDelayedTask(NewRunnableMethod(this, &AutoMounter::UpdateState), delay); delay *= 2; } else { @@ -1037,8 +1036,7 @@ AutoMounter::UpdateState() delay = 5000; } MessageLoopForIO::current()-> - PostDelayedTask(FROM_HERE, - NewRunnableMethod(this, &AutoMounter::UpdateState), + PostDelayedTask(NewRunnableMethod(this, &AutoMounter::UpdateState), delay); filesOpen = true; break; @@ -1390,7 +1388,6 @@ public: DBG("UsbCable switch device: %d state: %s\n", aEvent.device(), SwitchStateStr(aEvent)); XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(UsbCableEventIOThread)); } }; @@ -1405,7 +1402,6 @@ InitAutoMounter() sAutoMounterSetting = new AutoMounterSetting(); XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(InitAutoMounterIOThread)); // Switch Observers need to run on the main thread, so we need to @@ -1442,7 +1438,6 @@ void SetAutoMounterMode(int32_t aMode) { XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(SetAutoMounterModeIOThread, aMode)); } @@ -1450,7 +1445,6 @@ void SetAutoMounterSharingMode(const nsCString& aVolumeName, bool aAllowSharing) { XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(SetAutoMounterSharingModeIOThread, aVolumeName, aAllowSharing)); } @@ -1459,7 +1453,6 @@ void AutoMounterFormatVolume(const nsCString& aVolumeName) { XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(AutoMounterFormatVolumeIOThread, aVolumeName)); } @@ -1468,7 +1461,6 @@ void AutoMounterMountVolume(const nsCString& aVolumeName) { XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(AutoMounterMountVolumeIOThread, aVolumeName)); } @@ -1477,7 +1469,6 @@ void AutoMounterUnmountVolume(const nsCString& aVolumeName) { XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(AutoMounterUnmountVolumeIOThread, aVolumeName)); } @@ -1498,7 +1489,6 @@ ShutdownAutoMounter() sUsbCableObserver = nullptr; XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(ShutdownAutoMounterIOThread)); } diff --git a/dom/system/gonk/AutoMounterSetting.cpp b/dom/system/gonk/AutoMounterSetting.cpp index a78f692438..72c8dd9210 100644 --- a/dom/system/gonk/AutoMounterSetting.cpp +++ b/dom/system/gonk/AutoMounterSetting.cpp @@ -161,7 +161,7 @@ AutoMounterSetting::StatusStr(int32_t aStatus) return "??? Unknown ???"; } -class CheckVolumeSettingsRunnable : public nsRunnable +class CheckVolumeSettingsRunnable : public Runnable { public: CheckVolumeSettingsRunnable(const nsACString& aVolumeName) @@ -194,7 +194,7 @@ AutoMounterSetting::CheckVolumeSettings(const nsACString& aVolumeName) NS_DispatchToMainThread(new CheckVolumeSettingsRunnable(aVolumeName)); } -class SetStatusRunnable : public nsRunnable +class SetStatusRunnable : public Runnable { public: SetStatusRunnable(int32_t aStatus) : mStatus(aStatus) {} diff --git a/dom/system/gonk/GonkGPSGeolocationProvider.cpp b/dom/system/gonk/GonkGPSGeolocationProvider.cpp index 47db97797b..6d8d4c55ee 100644 --- a/dom/system/gonk/GonkGPSGeolocationProvider.cpp +++ b/dom/system/gonk/GonkGPSGeolocationProvider.cpp @@ -56,6 +56,13 @@ #define FLUSH_AIDE_DATA 0 +#undef LOG +#undef ERR +#undef DBG +#define LOG(args...) __android_log_print(ANDROID_LOG_INFO, "GonkGPSGeolocationProvider", ## args) +#define ERR(args...) __android_log_print(ANDROID_LOG_ERROR, "GonkGPSGeolocationProvider", ## args) +#define DBG(args...) __android_log_print(ANDROID_LOG_DEBUG, "GonkGPSGeolocationProvider" , ## args) + using namespace mozilla; using namespace mozilla::dom; @@ -98,7 +105,7 @@ GonkGPSGeolocationProvider::LocationCallback(GpsLocation* location) return; } - class UpdateLocationEvent : public nsRunnable { + class UpdateLocationEvent : public Runnable { public: UpdateLocationEvent(nsGeoPosition* aPosition) : mPosition(aPosition) @@ -139,10 +146,10 @@ GonkGPSGeolocationProvider::LocationCallback(GpsLocation* location) // set in the DOM JS. if (gDebug_isLoggingEnabled) { - nsContentUtils::LogMessageToConsole("geo: GPS got a fix (%f, %f). accuracy: %f", - location->latitude, - location->longitude, - location->accuracy); + DBG("geo: GPS got a fix (%f, %f). accuracy: %f", + location->latitude, + location->longitude, + location->accuracy); } RefPtr event = new UpdateLocationEvent(somewhere); @@ -153,30 +160,53 @@ GonkGPSGeolocationProvider::LocationCallback(GpsLocation* location) #endif } +class NotifyObserversGPSTask final : public Runnable +{ +public: + explicit NotifyObserversGPSTask(const char16_t* aData) + : mData(aData) + {} + NS_IMETHOD Run() override { + RefPtr provider = + GonkGPSGeolocationProvider::GetSingleton(); + nsCOMPtr obsService = services::GetObserverService(); + obsService->NotifyObservers(provider, "geolocation-device-events", mData); + return NS_OK; + } +private: + const char16_t* mData; +}; + + + void GonkGPSGeolocationProvider::StatusCallback(GpsStatus* status) { - if (gDebug_isLoggingEnabled) { - switch (status->status) { - case GPS_STATUS_NONE: - nsContentUtils::LogMessageToConsole("geo: GPS_STATUS_NONE\n"); - break; - case GPS_STATUS_SESSION_BEGIN: - nsContentUtils::LogMessageToConsole("geo: GPS_STATUS_SESSION_BEGIN\n"); - break; - case GPS_STATUS_SESSION_END: - nsContentUtils::LogMessageToConsole("geo: GPS_STATUS_SESSION_END\n"); - break; - case GPS_STATUS_ENGINE_ON: - nsContentUtils::LogMessageToConsole("geo: GPS_STATUS_ENGINE_ON\n"); - break; - case GPS_STATUS_ENGINE_OFF: - nsContentUtils::LogMessageToConsole("geo: GPS_STATUS_ENGINE_OFF\n"); - break; - default: - nsContentUtils::LogMessageToConsole("geo: Unknown GPS status\n"); - break; - } + const char* msgStream=0; + switch (status->status) { + case GPS_STATUS_NONE: + msgStream = "geo: GPS_STATUS_NONE\n"; + break; + case GPS_STATUS_SESSION_BEGIN: + msgStream = "geo: GPS_STATUS_SESSION_BEGIN\n"; + break; + case GPS_STATUS_SESSION_END: + msgStream = "geo: GPS_STATUS_SESSION_END\n"; + break; + case GPS_STATUS_ENGINE_ON: + msgStream = "geo: GPS_STATUS_ENGINE_ON\n"; + NS_DispatchToMainThread(new NotifyObserversGPSTask( MOZ_UTF16("GPSStarting"))); + break; + case GPS_STATUS_ENGINE_OFF: + msgStream = "geo: GPS_STATUS_ENGINE_OFF\n"; + NS_DispatchToMainThread(new NotifyObserversGPSTask( MOZ_UTF16("GPSShutdown"))); + break; + default: + msgStream = "geo: Unknown GPS status\n"; + break; + } + if (gDebug_isLoggingEnabled){ + DBG("%s", msgStream); } } @@ -217,7 +247,7 @@ GonkGPSGeolocationProvider::SvStatusCallback(GpsSvStatus* sv_info) svEphemerisCount != numEphemeris || svUsedCount != numUsedInFix) { - nsContentUtils::LogMessageToConsole( + LOG( "geo: Number of SVs have (visibility, almanac, ephemeris): (%d, %d, %d)." " %d of these SVs were used in fix.\n", sv_info->num_svs, svAlmanacCount, svEphemerisCount, svUsedCount); @@ -234,15 +264,14 @@ void GonkGPSGeolocationProvider::NmeaCallback(GpsUtcTime timestamp, const char* nmea, int length) { if (gDebug_isLoggingEnabled) { - nsContentUtils::LogMessageToConsole("geo: NMEA: timestamp:\t%lld, length: %d, %s", - timestamp, length, nmea); + DBG("NMEA: timestamp:\t%lld, length: %d, %s", timestamp, length, nmea); } } void GonkGPSGeolocationProvider::SetCapabilitiesCallback(uint32_t capabilities) { - class UpdateCapabilitiesEvent : public nsRunnable { + class UpdateCapabilitiesEvent : public Runnable { public: UpdateCapabilitiesEvent(uint32_t aCapabilities) : mCapabilities(aCapabilities) @@ -310,7 +339,7 @@ GonkGPSGeolocationProvider::AGPSStatusCallback(AGpsStatus* status) { MOZ_ASSERT(status); - class AGPSStatusEvent : public nsRunnable { + class AGPSStatusEvent : public Runnable { public: AGPSStatusEvent(AGpsStatusValue aStatus) : mStatus(aStatus) @@ -339,7 +368,7 @@ GonkGPSGeolocationProvider::AGPSStatusCallback(AGpsStatus* status) void GonkGPSGeolocationProvider::AGPSRILSetIDCallback(uint32_t flags) { - class RequestSetIDEvent : public nsRunnable { + class RequestSetIDEvent : public Runnable { public: RequestSetIDEvent(uint32_t flags) : mFlags(flags) @@ -360,7 +389,7 @@ GonkGPSGeolocationProvider::AGPSRILSetIDCallback(uint32_t flags) void GonkGPSGeolocationProvider::AGPSRILRefLocCallback(uint32_t flags) { - class RequestRefLocEvent : public nsRunnable { + class RequestRefLocEvent : public Runnable { public: RequestRefLocEvent() {} @@ -509,15 +538,13 @@ GonkGPSGeolocationProvider::RequestSettingValue(const char* aKey) nsCOMPtr lock; nsresult rv = ss->CreateLock(nullptr, getter_AddRefs(lock)); if (NS_FAILED(rv)) { - nsContentUtils::LogMessageToConsole( - "geo: error while createLock setting '%s': %d\n", aKey, rv); + ERR("error while createLock setting '%s': %d\n", aKey, uint32_t(rv)); return; } rv = lock->Get(aKey, this); if (NS_FAILED(rv)) { - nsContentUtils::LogMessageToConsole( - "geo: error while get setting '%s': %d\n", aKey, rv); + ERR("error while get setting '%s': %d\n", aKey, uint32_t(rv)); return; } } @@ -616,8 +643,8 @@ ConvertToGpsRefLocationType(const nsAString& aConnectionType) } if (gDebug_isLoggingEnabled) { - nsContentUtils::LogMessageToConsole("geo: Unsupported connection type %s\n", - NS_ConvertUTF16toUTF8(aConnectionType).get()); + DBG("geo: Unsupported connection type %s\n", + NS_ConvertUTF16toUTF8(aConnectionType).get()); } return AGPS_REF_LOCATION_TYPE_GSM_CELLID; } @@ -721,8 +748,7 @@ GonkGPSGeolocationProvider::InjectLocation(double latitude, float accuracy) { if (gDebug_isLoggingEnabled) { - nsContentUtils::LogMessageToConsole("geo: injecting location (%f, %f) accuracy: %f", - latitude, longitude, accuracy); + DBG("injecting location (%f, %f) accuracy: %f", latitude, longitude, accuracy); } MOZ_ASSERT(NS_IsMainThread()); @@ -924,14 +950,12 @@ GonkGPSGeolocationProvider::NetworkLocationUpdate::Update(nsIDOMGeoPosition *pos (isGPSTempInactive && delta > kMinMLSCoordChangeInMeters)) { if (gDebug_isLoggingEnabled) { - nsContentUtils::LogMessageToConsole("geo: Using MLS, GPS age:%fs, MLS Delta:%fm\n", - diff_ms / 1000.0, delta); + DBG("Using MLS, GPS age:%fs, MLS Delta:%fm\n", diff_ms / 1000.0, delta); } provider->mLocationCallback->Update(position); } else if (provider->mLastGPSPosition) { if (gDebug_isLoggingEnabled) { - nsContentUtils::LogMessageToConsole("geo: Using old GPS age:%fs\n", - diff_ms / 1000.0); + DBG("Using old GPS age:%fs\n", diff_ms / 1000.0); } // This is a fallback case so that the GPS provider responds with its last @@ -1153,16 +1177,15 @@ GonkGPSGeolocationProvider::Observe(nsISupports* aSubject, } if (setting.mKey.EqualsASCII(kSettingDebugGpsIgnored)) { - nsContentUtils::LogMessageToConsole("geo: received mozsettings-changed: ignoring\n"); + LOG("received mozsettings-changed: ignoring\n"); gDebug_isGPSLocationIgnored = setting.mValue.isBoolean() ? setting.mValue.toBoolean() : false; if (gDebug_isLoggingEnabled) { - nsContentUtils::LogMessageToConsole("geo: Debug: GPS ignored %d\n", - gDebug_isGPSLocationIgnored); + DBG("GPS ignored %d\n", gDebug_isGPSLocationIgnored); } return NS_OK; } else if (setting.mKey.EqualsASCII(kSettingDebugEnabled)) { - nsContentUtils::LogMessageToConsole("geo: received mozsettings-changed: logging\n"); + LOG("received mozsettings-changed: logging\n"); gDebug_isLoggingEnabled = setting.mValue.isBoolean() ? setting.mValue.toBoolean() : false; return NS_OK; diff --git a/dom/system/gonk/MozMtpDatabase.cpp b/dom/system/gonk/MozMtpDatabase.cpp index 47696265d8..63feed5168 100644 --- a/dom/system/gonk/MozMtpDatabase.cpp +++ b/dom/system/gonk/MozMtpDatabase.cpp @@ -255,7 +255,7 @@ MozMtpDatabase::UpdateEntry(MtpObjectHandle aHandle, DeviceStorageFile* aFile) } -class MtpWatcherNotifyRunnable final : public nsRunnable +class MtpWatcherNotifyRunnable final : public Runnable { public: MtpWatcherNotifyRunnable(nsACString& aStorageName, diff --git a/dom/system/gonk/MozMtpServer.cpp b/dom/system/gonk/MozMtpServer.cpp index 46ae58c67b..d1b195f926 100644 --- a/dom/system/gonk/MozMtpServer.cpp +++ b/dom/system/gonk/MozMtpServer.cpp @@ -41,7 +41,7 @@ BEGIN_MTP_NAMESPACE static const char* kMtpWatcherUpdate = "mtp-watcher-update"; -class MtpWatcherUpdateRunnable final : public nsRunnable +class MtpWatcherUpdateRunnable final : public Runnable { public: MtpWatcherUpdateRunnable(MozMtpDatabase* aMozMtpDatabase, @@ -142,7 +142,7 @@ private: NS_IMPL_ISUPPORTS(MtpWatcherUpdate, nsIObserver) static StaticRefPtr sMtpWatcherUpdate; -class AllocMtpWatcherUpdateRunnable final : public nsRunnable +class AllocMtpWatcherUpdateRunnable final : public Runnable { public: AllocMtpWatcherUpdateRunnable(MozMtpServer* aMozMtpServer) @@ -160,7 +160,7 @@ private: RefPtr mMozMtpServer; }; -class FreeMtpWatcherUpdateRunnable final : public nsRunnable +class FreeMtpWatcherUpdateRunnable final : public Runnable { public: FreeMtpWatcherUpdateRunnable(MozMtpServer* aMozMtpServer) @@ -178,7 +178,7 @@ private: RefPtr mMozMtpServer; }; -class MtpServerRunnable : public nsRunnable +class MtpServerRunnable : public Runnable { public: MtpServerRunnable(int aMtpUsbFd, MozMtpServer* aMozMtpServer) diff --git a/dom/system/gonk/NetworkWorker.cpp b/dom/system/gonk/NetworkWorker.cpp index 1608d688b2..d217590b48 100644 --- a/dom/system/gonk/NetworkWorker.cpp +++ b/dom/system/gonk/NetworkWorker.cpp @@ -29,7 +29,7 @@ StaticRefPtr gNetworkWorker; static nsAutoPtr gNetworkUtils; // Runnable used dispatch command result on the main thread. -class NetworkResultDispatcher : public nsRunnable +class NetworkResultDispatcher : public Runnable { public: NetworkResultDispatcher(const NetworkResultOptions& aResult) @@ -52,7 +52,7 @@ private: }; // Runnable used dispatch netd command on the worker thread. -class NetworkCommandDispatcher : public nsRunnable +class NetworkCommandDispatcher : public Runnable { public: NetworkCommandDispatcher(const NetworkParams& aParams) @@ -75,7 +75,7 @@ private: }; // Runnable used dispatch netd result on the worker thread. -class NetdEventRunnable : public nsRunnable +class NetdEventRunnable : public Runnable { public: NetdEventRunnable(NetdCommand* aCommand) diff --git a/dom/system/gonk/VolumeManager.cpp b/dom/system/gonk/VolumeManager.cpp index 0a73531ff7..bd0b7d7761 100644 --- a/dom/system/gonk/VolumeManager.cpp +++ b/dom/system/gonk/VolumeManager.cpp @@ -528,8 +528,7 @@ VolumeManager::Start() if (!sVolumeManager->OpenSocket()) { // Socket open failed, try again in a second. MessageLoopForIO::current()-> - PostDelayedTask(FROM_HERE, - NewRunnableFunction(VolumeManager::Start), + PostDelayedTask(NewRunnableFunction(VolumeManager::Start), 1000); } } @@ -575,7 +574,6 @@ void InitVolumeManager() { XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(InitVolumeManagerIOThread)); } @@ -585,7 +583,6 @@ ShutdownVolumeManager() ShutdownVolumeServiceTest(); XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(ShutdownVolumeManagerIOThread)); } diff --git a/dom/system/gonk/VolumeServiceTest.cpp b/dom/system/gonk/VolumeServiceTest.cpp index 0f366778e4..e78f81a9d8 100644 --- a/dom/system/gonk/VolumeServiceTest.cpp +++ b/dom/system/gonk/VolumeServiceTest.cpp @@ -157,7 +157,7 @@ VolumeTestObserver::Observe(nsISupports* aSubject, return NS_OK; } -class InitVolumeServiceTestIO : public nsRunnable +class InitVolumeServiceTestIO : public Runnable { public: NS_IMETHOD Run() diff --git a/dom/system/gonk/android_audio/AudioSystem.h b/dom/system/gonk/android_audio/AudioSystem.h index 10402e9cf4..d5841eaaa6 100644 --- a/dom/system/gonk/android_audio/AudioSystem.h +++ b/dom/system/gonk/android_audio/AudioSystem.h @@ -241,6 +241,7 @@ typedef enum { #if ANDROID_VERSION < 17 typedef enum { + AUDIO_DEVICE_NONE = 0x0, /* output devices */ AUDIO_DEVICE_OUT_EARPIECE = 0x1, AUDIO_DEVICE_OUT_SPEAKER = 0x2, @@ -547,6 +548,22 @@ enum { typedef uint32_t audio_devices_t; #endif +static inline bool audio_is_output_device(uint32_t device) +{ +#if ANDROID_VERSION < 17 + if ((__builtin_popcount(device) == 1) && ((device & ~AUDIO_DEVICE_OUT_ALL) == 0)) + return true; + else + return false; +#else + if (((device & AUDIO_DEVICE_BIT_IN) == 0) && + (__builtin_popcount(device) == 1) && ((device & ~AUDIO_DEVICE_OUT_ALL) == 0)) + return true; + else + return false; +#endif +} + /* device connection states used for audio_policy->set_device_connection_state() * */ typedef enum { diff --git a/dom/system/gonk/mozstumbler/MozStumbler.cpp b/dom/system/gonk/mozstumbler/MozStumbler.cpp index 8a43f3633b..e78424070c 100644 --- a/dom/system/gonk/mozstumbler/MozStumbler.cpp +++ b/dom/system/gonk/mozstumbler/MozStumbler.cpp @@ -28,7 +28,7 @@ using namespace mozilla::dom; NS_IMPL_ISUPPORTS(StumblerInfo, nsICellInfoListCallback, nsIWifiScanResultsReady) -class RequestCellInfoEvent : public nsRunnable { +class RequestCellInfoEvent : public Runnable { public: RequestCellInfoEvent(StumblerInfo *callback) : mRequestCallback(callback) diff --git a/dom/system/gonk/mozstumbler/UploadStumbleRunnable.h b/dom/system/gonk/mozstumbler/UploadStumbleRunnable.h index a9ea83e37d..462665a869 100644 --- a/dom/system/gonk/mozstumbler/UploadStumbleRunnable.h +++ b/dom/system/gonk/mozstumbler/UploadStumbleRunnable.h @@ -17,7 +17,7 @@ class nsIInputStream; This runnable is managed by WriteStumbleOnThread only, see that class for how this is scheduled. */ -class UploadStumbleRunnable final : public nsRunnable +class UploadStumbleRunnable final : public Runnable { public: explicit UploadStumbleRunnable(nsIInputStream* aUploadInputStream); diff --git a/dom/system/gonk/mozstumbler/WriteStumbleOnThread.cpp b/dom/system/gonk/mozstumbler/WriteStumbleOnThread.cpp index ef8593ed89..41ca0197d7 100644 --- a/dom/system/gonk/mozstumbler/WriteStumbleOnThread.cpp +++ b/dom/system/gonk/mozstumbler/WriteStumbleOnThread.cpp @@ -25,7 +25,7 @@ WriteStumbleOnThread::UploadFreqGuard WriteStumbleOnThread::sUploadFreqGuard = { #define FILENAME_COMPLETED NS_LITERAL_CSTRING("stumbles.done.json.gz") #define OUTPUT_DIR NS_LITERAL_CSTRING("mozstumbler") -class DeleteRunnable : public nsRunnable +class DeleteRunnable : public Runnable { public: DeleteRunnable() {} diff --git a/dom/system/gonk/mozstumbler/WriteStumbleOnThread.h b/dom/system/gonk/mozstumbler/WriteStumbleOnThread.h index 1e65ad08a6..650c73fc52 100644 --- a/dom/system/gonk/mozstumbler/WriteStumbleOnThread.h +++ b/dom/system/gonk/mozstumbler/WriteStumbleOnThread.h @@ -33,7 +33,7 @@ This thread is guarded so that only one instance is active (see the mozilla::Atomics used for this). */ -class WriteStumbleOnThread : public nsRunnable +class WriteStumbleOnThread : public mozilla::Runnable { public: explicit WriteStumbleOnThread(const nsCString& aDesc) diff --git a/dom/system/gonk/nsVolume.cpp b/dom/system/gonk/nsVolume.cpp index efb28facd6..e98225cc64 100644 --- a/dom/system/gonk/nsVolume.cpp +++ b/dom/system/gonk/nsVolume.cpp @@ -265,7 +265,6 @@ NS_IMETHODIMP nsVolume::Format() MOZ_ASSERT(XRE_IsParentProcess()); XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(FormatVolumeIOThread, NameStr())); return NS_OK; @@ -289,7 +288,6 @@ NS_IMETHODIMP nsVolume::Mount() MOZ_ASSERT(XRE_IsParentProcess()); XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(MountVolumeIOThread, NameStr())); return NS_OK; @@ -313,7 +311,6 @@ NS_IMETHODIMP nsVolume::Unmount() MOZ_ASSERT(XRE_IsParentProcess()); XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(UnmountVolumeIOThread, NameStr())); return NS_OK; @@ -411,7 +408,6 @@ nsVolume::UpdateMountLock(bool aMountLocked) mMountLocked = aMountLocked; LogState(); XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(Volume::UpdateMountLock, NS_LossyConvertUTF16toASCII(Name()), MountGeneration(), aMountLocked)); diff --git a/dom/system/gonk/nsVolumeService.cpp b/dom/system/gonk/nsVolumeService.cpp index 6fa93057c1..07fd4ff3ed 100644 --- a/dom/system/gonk/nsVolumeService.cpp +++ b/dom/system/gonk/nsVolumeService.cpp @@ -80,7 +80,6 @@ nsVolumeService::Shutdown() } XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(ShutdownVolumeServiceIOThread)); sSingleton = nullptr; @@ -101,7 +100,6 @@ nsVolumeService::nsVolumeService() // Startup the IOThread side of things. The actual volume changes // are captured by the IOThread and forwarded to main thread. XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(InitVolumeServiceIOThread, this)); nsCOMPtr pmService = @@ -505,7 +503,7 @@ nsVolumeService::RemoveVolumeByName(const nsAString& aName) * The UpdateVolumeRunnable creates an nsVolume and updates the main thread * data structure while running on the main thread. */ -class UpdateVolumeRunnable : public nsRunnable +class UpdateVolumeRunnable : public Runnable { public: UpdateVolumeRunnable(nsVolumeService* aVolumeService, const Volume* aVolume) diff --git a/dom/tests/mochitest/general/test_interfaces.html b/dom/tests/mochitest/general/test_interfaces.html index 0b518b9809..cfdb849b9f 100644 --- a/dom/tests/mochitest/general/test_interfaces.html +++ b/dom/tests/mochitest/general/test_interfaces.html @@ -383,12 +383,6 @@ var interfaceNamesInGlobalScope = "DataChannel", // IMPORTANT: Do not change this list without review from a DOM peer! {name: "DataErrorEvent", b2g: true}, -// IMPORTANT: Do not change this list without review from a DOM peer! - {name: "DataStore", b2g: true}, -// IMPORTANT: Do not change this list without review from a DOM peer! - {name: "DataStoreChangeEvent", b2g: true}, -// IMPORTANT: Do not change this list without review from a DOM peer! - {name: "DataStoreCursor", b2g: true}, // IMPORTANT: Do not change this list without review from a DOM peer! "DataTransfer", // IMPORTANT: Do not change this list without review from a DOM peer! diff --git a/dom/webidl/DataStore.webidl b/dom/webidl/DataStore.webidl deleted file mode 100644 index 79f0b7cd5a..0000000000 --- a/dom/webidl/DataStore.webidl +++ /dev/null @@ -1,112 +0,0 @@ -/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ - -typedef (DOMString or unsigned long) DataStoreKey; - -// TODO Bug 957086 - The constructor and the setDataStoreImpl(...) will be -// removed once the DataStore API is fully rewritten in C++, -// which currently plays a role of C++ proxy directing to the -// JS codes implemented by the DataStoreImpl WebIDL. - -[Func="Navigator::HasDataStoreSupport", - ChromeConstructor, - Exposed=(Window,Worker)] -interface DataStore : EventTarget { - // Returns the label of the DataSource. - [GetterThrows] - readonly attribute DOMString name; - - // Returns the origin of the DataSource (e.g., 'facebook.com'). - // This value is the manifest URL of the owner app. - [GetterThrows] - readonly attribute DOMString owner; - - // is readOnly a F(current_app, datastore) function? yes - [GetterThrows] - readonly attribute boolean readOnly; - - [Throws] - Promise get(DataStoreKey... id); - - [Throws] - Promise put(any obj, DataStoreKey id, optional DOMString revisionId = ""); - - [Throws] - Promise add(any obj, optional DataStoreKey id, - optional DOMString revisionId = ""); - - [Throws] - Promise remove(DataStoreKey id, optional DOMString revisionId = ""); - - [Throws] - Promise clear(optional DOMString revisionId = ""); - - [GetterThrows] - readonly attribute DOMString revisionId; - - attribute EventHandler onchange; - - [Throws] - Promise getLength(); - - [NewObject, Throws] - DataStoreCursor sync(optional DOMString revisionId = ""); -}; - -partial interface DataStore { - [ChromeOnly, Throws, Exposed=Window] - void setDataStoreImpl(DataStoreImpl store); -}; - -// TODO Bug 957086 - The constructor and the setDataStoreCursorImpl(...) will be -// removed once the DataStore API is fully rewritten in C++, -// which currently plays a role of C++ proxy directing to the -// JS codes implemented by the DataStoreCursorImpl WebIDL. - -[Func="Navigator::HasDataStoreSupport", - ChromeConstructor, - Exposed=(Window,Worker)] -interface DataStoreCursor { - // the DataStore - [GetterThrows] - readonly attribute DataStore store; - - [Throws] - Promise next(); - - [Throws] - void close(); -}; - -partial interface DataStoreCursor { - [ChromeOnly, Exposed=Window] - void setDataStoreCursorImpl(DataStoreCursorImpl cursor); -}; - -enum DataStoreOperation { - "add", - "update", - "remove", - "clear", - "done" -}; - -dictionary DataStoreTask { - DOMString revisionId; - - DataStoreOperation operation; - - // When |operation| is "clear" or "done", this must return null. - DataStoreKey? id; - any data; -}; - -// For internal use. -dictionary DataStoreRevisionData { - DOMString revisionId = ""; - unsigned long objectId = 0; - DOMString operation = ""; -}; diff --git a/dom/webidl/DataStoreChangeEvent.webidl b/dom/webidl/DataStoreChangeEvent.webidl deleted file mode 100644 index 6b6176e8ac..0000000000 --- a/dom/webidl/DataStoreChangeEvent.webidl +++ /dev/null @@ -1,24 +0,0 @@ -/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ - -dictionary DataStoreChangeEventInit : EventInit { - DOMString revisionId = ""; - - // When |operation| is "clear" or "done", this must return null. - DataStoreKey? id = null; - - DOMString operation = ""; - DOMString owner = ""; -}; - -[Func="Navigator::HasDataStoreSupport", - Constructor(DOMString type, optional DataStoreChangeEventInit eventInitDict)] -interface DataStoreChangeEvent : Event { - readonly attribute DOMString revisionId; - readonly attribute DataStoreKey? id; - readonly attribute DOMString operation; - readonly attribute DOMString owner; -}; diff --git a/dom/webidl/DataStoreImpl.webidl b/dom/webidl/DataStoreImpl.webidl deleted file mode 100644 index 564f4ff997..0000000000 --- a/dom/webidl/DataStoreImpl.webidl +++ /dev/null @@ -1,61 +0,0 @@ -/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. - */ - -// TODO Bug 957086 - The DataStoreImpl WebIDL will be removed once the -// DataStore API is fully rewritten in C++ (i.e. should be -// directly implemented by the DataStore WebIDL). - -[HeaderFile="mozilla/dom/DataStore.h", - Func="mozilla::dom::DataStore::EnabledForScope", - JSImplementation="@mozilla.org/dom/datastore-impl;1"] -interface DataStoreImpl { - void setEventTarget(EventTarget eventTarget); - - // Returns the label of the DataSource. - readonly attribute DOMString name; - - // Returns the origin of the DataSource (e.g., 'facebook.com'). - // This value is the manifest URL of the owner app. - readonly attribute DOMString owner; - - // is readOnly a F(current_app, datastore) function? yes - readonly attribute boolean readOnly; - - Promise get(DataStoreKey... id); - - Promise put(any obj, DataStoreKey id, optional DOMString revisionId = ""); - - Promise add(any obj, optional DataStoreKey id, - optional DOMString revisionId = ""); - - Promise remove(DataStoreKey id, optional DOMString revisionId = ""); - - Promise clear(optional DOMString revisionId = ""); - - readonly attribute DOMString revisionId; - - Promise getLength(); - - [NewObject] - DataStoreCursor sync(optional DOMString revisionId = ""); -}; - - -// TODO Bug 957086 - The DataStoreCursorImpl WebIDL will be removed once the -// DataStore API is fully rewritten in C++ (i.e. should be -// directly implemented by the DataStoreCursor WebIDL). - -[HeaderFile="mozilla/dom/DataStore.h", - Func="mozilla::dom::DataStore::EnabledForScope", - JSImplementation="@mozilla.org/dom/datastore-cursor-impl;1"] -interface DataStoreCursorImpl { - // the DataStore - readonly attribute DataStore store; - - Promise next(); - - void close(); -}; diff --git a/dom/webidl/Navigator.webidl b/dom/webidl/Navigator.webidl index 162cbd20f1..712a1aba72 100644 --- a/dom/webidl/Navigator.webidl +++ b/dom/webidl/Navigator.webidl @@ -139,16 +139,6 @@ partial interface Navigator { readonly attribute BatteryManager? battery; }; -// https://wiki.mozilla.org/WebAPI/DataStore -[NoInterfaceObject, - Exposed=(Window,Worker)] -interface NavigatorDataStore { - [NewObject, Func="Navigator::HasDataStoreSupport"] - Promise> getDataStores(DOMString name, - optional DOMString? owner = null); -}; -Navigator implements NavigatorDataStore; - // http://www.w3.org/TR/vibration/#vibration-interface partial interface Navigator { // We don't support sequences in unions yet diff --git a/dom/webidl/WorkerNavigator.webidl b/dom/webidl/WorkerNavigator.webidl index faa715fd9c..affbfba82c 100644 --- a/dom/webidl/WorkerNavigator.webidl +++ b/dom/webidl/WorkerNavigator.webidl @@ -10,5 +10,4 @@ interface WorkerNavigator { WorkerNavigator implements NavigatorID; WorkerNavigator implements NavigatorLanguage; WorkerNavigator implements NavigatorOnLine; -WorkerNavigator implements NavigatorDataStore; WorkerNavigator implements NavigatorConcurrentHardware; diff --git a/dom/webidl/moz.build b/dom/webidl/moz.build index ed8069444d..aaa50aa9a5 100644 --- a/dom/webidl/moz.build +++ b/dom/webidl/moz.build @@ -108,8 +108,6 @@ WEBIDL_FILES = [ 'CSSValue.webidl', 'CSSValueList.webidl', 'DataContainerEvent.webidl', - 'DataStore.webidl', - 'DataStoreImpl.webidl', 'DataTransfer.webidl', 'DecoderDoctorNotification.webidl', 'DedicatedWorkerGlobalScope.webidl', @@ -781,7 +779,6 @@ GENERATED_EVENTS_WEBIDL_FILES = [ 'CFStateChangeEvent.webidl', 'CloseEvent.webidl', 'DataErrorEvent.webidl', - 'DataStoreChangeEvent.webidl', 'DeviceLightEvent.webidl', 'DeviceOrientationEvent.webidl', 'DeviceProximityEvent.webidl', diff --git a/dom/wifi/WifiProxyService.cpp b/dom/wifi/WifiProxyService.cpp index 81c9dc0ce4..cee8757b52 100644 --- a/dom/wifi/WifiProxyService.cpp +++ b/dom/wifi/WifiProxyService.cpp @@ -29,10 +29,10 @@ namespace mozilla { static StaticRefPtr gWifiProxyService; // The singleton supplicant class, that can be used on any thread. -static nsAutoPtr gWpaSupplicant; +static UniquePtr gWpaSupplicant; // Runnable used dispatch the WaitForEvent result on the main thread. -class WifiEventDispatcher : public nsRunnable +class WifiEventDispatcher : public Runnable { public: WifiEventDispatcher(const nsAString& aEvent, const nsACString& aInterface) @@ -55,7 +55,7 @@ private: }; // Runnable used to call WaitForEvent on the event thread. -class EventRunnable : public nsRunnable +class EventRunnable : public Runnable { public: EventRunnable(const nsACString& aInterface) @@ -87,7 +87,7 @@ private: }; // Runnable used dispatch the Command result on the main thread. -class WifiResultDispatcher : public nsRunnable +class WifiResultDispatcher : public Runnable { public: WifiResultDispatcher(WifiResultOptions& aResult, const nsACString& aInterface) @@ -110,7 +110,7 @@ private: }; // Runnable used to call SendCommand on the control thread. -class ControlRunnable : public nsRunnable +class ControlRunnable : public Runnable { public: ControlRunnable(CommandOptions aOptions, const nsACString& aInterface) @@ -160,7 +160,7 @@ WifiProxyService::FactoryCreate() gWifiProxyService = new WifiProxyService(); ClearOnShutdown(&gWifiProxyService); - gWpaSupplicant = new WpaSupplicant(); + gWpaSupplicant = MakeUnique(); ClearOnShutdown(&gWpaSupplicant); } @@ -248,6 +248,10 @@ WifiProxyService::SendCommand(JS::Handle aOptions, return NS_ERROR_FAILURE; } + if (!mControlThread) { + return NS_ERROR_FAILURE; + } + // Dispatch the command to the control thread. CommandOptions commandOptions(options); nsCOMPtr runnable = new ControlRunnable(commandOptions, aInterface); @@ -293,8 +297,10 @@ WifiProxyService::DispatchWifiResult(const WifiResultOptions& aOptions, const ns return; } - // Call the listener with a JS value. - mListener->OnCommand(val, aInterface); + if (mListener) { + // Call the listener with a JS value. + mListener->OnCommand(val, aInterface); + } } void diff --git a/dom/wifi/WifiUtils.cpp b/dom/wifi/WifiUtils.cpp index 6d5f74ad6d..7c26fc423a 100644 --- a/dom/wifi/WifiUtils.cpp +++ b/dom/wifi/WifiUtils.cpp @@ -387,13 +387,13 @@ WpaSupplicant::WpaSupplicant() mSdkVersion = strtol(propVersion, nullptr, 10); if (mSdkVersion < 16) { - mImpl = new ICSWpaSupplicantImpl(); + mImpl = MakeUnique(); } else if (mSdkVersion < 19) { - mImpl = new JBWpaSupplicantImpl(); + mImpl = MakeUnique(); } else { - mImpl = new KKWpaSupplicantImpl(); + mImpl = MakeUnique(); } - mWifiHotspotUtils = new WifiHotspotUtils(); + mWifiHotspotUtils = MakeUnique(); }; void WpaSupplicant::WaitForEvent(nsAString& aEvent, const nsCString& aInterface) diff --git a/dom/wifi/WifiUtils.h b/dom/wifi/WifiUtils.h index 2f7da88d14..a83ba9c152 100644 --- a/dom/wifi/WifiUtils.h +++ b/dom/wifi/WifiUtils.h @@ -13,8 +13,8 @@ #define WifiUtils_h #include "nsString.h" -#include "nsAutoPtr.h" #include "mozilla/dom/WifiOptionsBinding.h" +#include "mozilla/UniquePtr.h" #include "WifiHotspotUtils.h" // Needed to add a copy constructor to WifiCommandOptions. @@ -51,7 +51,7 @@ public: class WpaSupplicantImpl { public: - // Suppress warning from nsAutoPtr + // Suppress warning from |UniquePtr| virtual ~WpaSupplicantImpl() {} virtual int32_t @@ -94,8 +94,8 @@ public: const nsCString& aInterface); private: - nsAutoPtr mImpl; - nsAutoPtr mWifiHotspotUtils; + UniquePtr mImpl; + UniquePtr mWifiHotspotUtils; uint32_t mSdkVersion; diff --git a/dom/wifi/WifiWorker.js b/dom/wifi/WifiWorker.js index 6be09e50c3..56c0960d30 100755 --- a/dom/wifi/WifiWorker.js +++ b/dom/wifi/WifiWorker.js @@ -1418,6 +1418,14 @@ var WifiManager = (function() { ? wifiCommand.getConnectionInfoICS : wifiCommand.getConnectionInfoGB; + manager.ensureSupplicantDetached = aCallback => { + if (!manager.enabled) { + aCallback(); + return; + } + wifiCommand.closeSupplicantConnection(aCallback); + }; + manager.isHandShakeState = function(state) { switch (state) { case "AUTHENTICATING": @@ -3802,10 +3810,14 @@ WifiWorker.prototype = { break; case "xpcom-shutdown": - let wifiService = Cc["@mozilla.org/wifi/service;1"].getService(Ci.nsIWifiProxyService); - wifiService.shutdown(); - let wifiCertService = Cc["@mozilla.org/wifi/certservice;1"].getService(Ci.nsIWifiCertService); - wifiCertService.shutdown(); + // Ensure the supplicant is detached from B2G to avoid XPCOM shutdown + // blocks forever. + WifiManager.ensureSupplicantDetached(() => { + let wifiService = Cc["@mozilla.org/wifi/service;1"].getService(Ci.nsIWifiProxyService); + wifiService.shutdown(); + let wifiCertService = Cc["@mozilla.org/wifi/certservice;1"].getService(Ci.nsIWifiCertService); + wifiCertService.shutdown(); + }); break; } }, diff --git a/dom/workers/DataStore.cpp b/dom/workers/DataStore.cpp deleted file mode 100644 index 82a9210027..0000000000 --- a/dom/workers/DataStore.cpp +++ /dev/null @@ -1,989 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "DataStore.h" -#include "DataStoreCursor.h" - -#include "mozilla/dom/DataStore.h" -#include "mozilla/dom/DataStoreCursor.h" -#include "mozilla/dom/DataStoreChangeEvent.h" -#include "mozilla/dom/DataStoreBinding.h" -#include "mozilla/dom/DataStoreImplBinding.h" - -#include "mozilla/dom/Promise.h" -#include "mozilla/dom/PromiseWorkerProxy.h" -#include "mozilla/dom/ScriptSettings.h" -#include "mozilla/dom/StructuredCloneHolder.h" -#include "mozilla/ErrorResult.h" - -#include "WorkerPrivate.h" -#include "WorkerRunnable.h" -#include "WorkerScope.h" - -BEGIN_WORKERS_NAMESPACE - -NS_IMPL_ADDREF_INHERITED(WorkerDataStore, DOMEventTargetHelper) -NS_IMPL_RELEASE_INHERITED(WorkerDataStore, DOMEventTargetHelper) - -NS_INTERFACE_MAP_BEGIN(WorkerDataStore) -NS_INTERFACE_MAP_END_INHERITING(DOMEventTargetHelper) - -WorkerDataStore::WorkerDataStore(WorkerGlobalScope* aScope) - : DOMEventTargetHelper(static_cast(aScope)) -{} - -already_AddRefed -WorkerDataStore::Constructor(GlobalObject& aGlobal, ErrorResult& aRv) -{ - // We don't allow Gecko to create WorkerDataStore through JS codes like - // window.DataStore() on the worker, so disable this for now. - NS_NOTREACHED("Cannot use the chrome constructor on the worker!"); - return nullptr; -} - -JSObject* -WorkerDataStore::WrapObject(JSContext* aCx, JS::Handle aGivenProto) -{ - return DataStoreBinding_workers::Wrap(aCx, this, aGivenProto); -} - -// A WorkerMainThreadRunnable which holds a reference to WorkerDataStore. -class DataStoreRunnable : public WorkerMainThreadRunnable -{ -protected: - nsMainThreadPtrHandle mBackingStore; - -public: - DataStoreRunnable(WorkerPrivate* aWorkerPrivate, - const nsMainThreadPtrHandle& aBackingStore) - : WorkerMainThreadRunnable(aWorkerPrivate) - , mBackingStore(aBackingStore) - { - MOZ_ASSERT(aWorkerPrivate); - aWorkerPrivate->AssertIsOnWorkerThread(); - } -}; - -// A DataStoreRunnable to run: -// - DataStore::GetName(...) -// - DataStore::GetOwner(...) -// - DataStore::GetRevisionId(...) -// on the main thread. -class DataStoreGetStringRunnable final : public DataStoreRunnable -{ - typedef void - (DataStore::*FuncType)(nsAString&, ErrorResult&); - - FuncType mFunc; - nsAString& mString; - -public: - DataStoreGetStringRunnable(WorkerPrivate* aWorkerPrivate, - const nsMainThreadPtrHandle& aBackingStore, - FuncType aFunc, - nsAString& aString) - : DataStoreRunnable(aWorkerPrivate, aBackingStore) - , mFunc(aFunc) - , mString(aString) - { - MOZ_ASSERT(aWorkerPrivate); - aWorkerPrivate->AssertIsOnWorkerThread(); - } - -protected: - virtual bool - MainThreadRun() override - { - AssertIsOnMainThread(); - - ErrorResult rv; - nsString string; - (mBackingStore.get()->*mFunc)(string, rv); - mString.Assign(string); - - if (NS_WARN_IF(rv.Failed())) { - rv.SuppressException(); - } - - return true; - } -}; - -// A DataStoreRunnable to run DataStore::GetReadOnly(...) on the main -// thread. -class DataStoreGetReadOnlyRunnable final : public DataStoreRunnable -{ -public: - bool mReadOnly; - - DataStoreGetReadOnlyRunnable(WorkerPrivate* aWorkerPrivate, - const nsMainThreadPtrHandle& aBackingStore) - : DataStoreRunnable(aWorkerPrivate, aBackingStore) - { - MOZ_ASSERT(aWorkerPrivate); - aWorkerPrivate->AssertIsOnWorkerThread(); - } - -protected: - virtual bool - MainThreadRun() override - { - AssertIsOnMainThread(); - - ErrorResult rv; - mReadOnly = mBackingStore->GetReadOnly(rv); - if (NS_WARN_IF(rv.Failed())) { - rv.SuppressException(); - } - - return true; - } -}; - -class DataStoreProxyRunnable : public DataStoreRunnable -{ -public: - DataStoreProxyRunnable(WorkerPrivate* aWorkerPrivate, - const nsMainThreadPtrHandle& aBackingStore, - Promise* aWorkerPromise) - : DataStoreRunnable(aWorkerPrivate, aBackingStore) - , mFailed(false) - { - MOZ_ASSERT(aWorkerPrivate); - aWorkerPrivate->AssertIsOnWorkerThread(); - - mPromiseWorkerProxy = - PromiseWorkerProxy::Create(aWorkerPrivate, aWorkerPromise); - } - - void Dispatch(ErrorResult& aRv) - { - if (mPromiseWorkerProxy) { - DataStoreRunnable::Dispatch(aRv); - } - - // If the creation of mProxyWorkerProxy failed, the worker is terminating. - // In this case we don't want to dispatch the runnable and we should stop - // the promise chain here. - } - - bool Failed() const - { - return mFailed; - } - -protected: - RefPtr mPromiseWorkerProxy; - bool mFailed; -}; - -// A DataStoreRunnable to run DataStore::Get(...) on the main thread. -class DataStoreGetRunnable final : public DataStoreProxyRunnable -{ - Sequence mId; - -public: - DataStoreGetRunnable(WorkerPrivate* aWorkerPrivate, - const nsMainThreadPtrHandle& aBackingStore, - Promise* aWorkerPromise) - : DataStoreProxyRunnable(aWorkerPrivate, aBackingStore, aWorkerPromise) - { - MOZ_ASSERT(aWorkerPrivate); - aWorkerPrivate->AssertIsOnWorkerThread(); - } - - Sequence& Id() - { - return mId; - } - -protected: - virtual bool - MainThreadRun() override - { - AssertIsOnMainThread(); - - ErrorResult rv; - RefPtr promise = mBackingStore->Get(mId, rv); - promise->AppendNativeHandler(mPromiseWorkerProxy); - if (NS_WARN_IF(rv.Failed())) { - rv.SuppressException(); - mFailed = true; - } - - return true; - } -}; - -// A DataStoreRunnable to run DataStore::Put(...) on the main thread. -class DataStorePutRunnable final : public DataStoreProxyRunnable - , public StructuredCloneHolder -{ - const StringOrUnsignedLong& mId; - const nsString mRevisionId; - nsresult mError; - -public: - DataStorePutRunnable(WorkerPrivate* aWorkerPrivate, - const nsMainThreadPtrHandle& aBackingStore, - Promise* aWorkerPromise, - const StringOrUnsignedLong& aId, - const nsAString& aRevisionId) - : DataStoreProxyRunnable(aWorkerPrivate, aBackingStore, aWorkerPromise) - , StructuredCloneHolder(CloningNotSupported, TransferringNotSupported, - SameProcessDifferentThread) - , mId(aId) - , mRevisionId(aRevisionId) - , mError(NS_OK) - { - MOZ_ASSERT(aWorkerPrivate); - aWorkerPrivate->AssertIsOnWorkerThread(); - } - - nsresult ErrorCode() const - { - return mError; - } - -protected: - virtual bool - MainThreadRun() override - { - AssertIsOnMainThread(); - - // Initialise an AutoJSAPI with the target window. - AutoJSAPI jsapi; - if (NS_WARN_IF(!jsapi.Init(mBackingStore->GetParentObject()))) { - mError = NS_ERROR_UNEXPECTED; - return true; - } - JSContext* cx = jsapi.cx(); - - ErrorResult rv; - JS::Rooted value(cx); - Read(mBackingStore->GetParentObject(), cx, &value, rv); - if (NS_WARN_IF(rv.Failed())) { - rv.SuppressException(); - mError = NS_ERROR_DOM_DATA_CLONE_ERR; - return true; - } - - RefPtr promise = mBackingStore->Put(cx, value, mId, - mRevisionId, rv); - if (NS_WARN_IF(rv.Failed())) { - rv.SuppressException(); - mError = NS_ERROR_FAILURE; - return true; - } - - promise->AppendNativeHandler(mPromiseWorkerProxy); - return true; - } -}; - -// A DataStoreRunnable to run DataStore::Add(...) on the main thread. -class DataStoreAddRunnable final : public DataStoreProxyRunnable - , public StructuredCloneHolder -{ - const Optional& mId; - const nsString mRevisionId; - nsresult mResult; - -public: - DataStoreAddRunnable(WorkerPrivate* aWorkerPrivate, - const nsMainThreadPtrHandle& aBackingStore, - Promise* aWorkerPromise, - const Optional& aId, - const nsAString& aRevisionId) - : DataStoreProxyRunnable(aWorkerPrivate, aBackingStore, aWorkerPromise) - , StructuredCloneHolder(CloningNotSupported, TransferringNotSupported, - SameProcessDifferentThread) - , mId(aId) - , mRevisionId(aRevisionId) - , mResult(NS_OK) - { - MOZ_ASSERT(aWorkerPrivate); - aWorkerPrivate->AssertIsOnWorkerThread(); - } - - nsresult ErrorCode() const - { - return mResult; - } - -protected: - virtual bool - MainThreadRun() override - { - AssertIsOnMainThread(); - - // Initialise an AutoJSAPI with the target window. - AutoJSAPI jsapi; - if (NS_WARN_IF(!jsapi.Init(mBackingStore->GetParentObject()))) { - mResult = NS_ERROR_UNEXPECTED; - return true; - } - JSContext* cx = jsapi.cx(); - - ErrorResult rv; - JS::Rooted value(cx); - Read(mBackingStore->GetParentObject(), cx, &value, rv); - if (NS_WARN_IF(rv.Failed())) { - rv.SuppressException(); - mResult = NS_ERROR_DOM_DATA_CLONE_ERR; - return true; - } - - RefPtr promise = mBackingStore->Add(cx, value, mId, - mRevisionId, rv); - if (NS_WARN_IF(rv.Failed())) { - rv.SuppressException(); - mResult = NS_ERROR_FAILURE; - return true; - } - - promise->AppendNativeHandler(mPromiseWorkerProxy); - return true; - } -}; - -// A DataStoreRunnable to run DataStore::Remove(...) on the main -// thread. -class DataStoreRemoveRunnable final : public DataStoreProxyRunnable -{ - const StringOrUnsignedLong& mId; - const nsString mRevisionId; - -public: - DataStoreRemoveRunnable(WorkerPrivate* aWorkerPrivate, - const nsMainThreadPtrHandle& aBackingStore, - Promise* aWorkerPromise, - const StringOrUnsignedLong& aId, - const nsAString& aRevisionId) - : DataStoreProxyRunnable(aWorkerPrivate, aBackingStore, aWorkerPromise) - , mId(aId) - , mRevisionId(aRevisionId) - { - MOZ_ASSERT(aWorkerPrivate); - aWorkerPrivate->AssertIsOnWorkerThread(); - } - -protected: - virtual bool - MainThreadRun() override - { - AssertIsOnMainThread(); - - ErrorResult rv; - RefPtr promise = mBackingStore->Remove(mId, mRevisionId, rv); - if (NS_WARN_IF(rv.Failed())) { - rv.SuppressException(); - mFailed = true; - return true; - } - - promise->AppendNativeHandler(mPromiseWorkerProxy); - return true; - } -}; - -// A DataStoreRunnable to run DataStore::Clear(...) on the main thread. -class DataStoreClearRunnable final : public DataStoreProxyRunnable -{ - const nsString mRevisionId; - -public: - DataStoreClearRunnable(WorkerPrivate* aWorkerPrivate, - const nsMainThreadPtrHandle& aBackingStore, - Promise* aWorkerPromise, - const nsAString& aRevisionId) - : DataStoreProxyRunnable(aWorkerPrivate, aBackingStore, aWorkerPromise) - , mRevisionId(aRevisionId) - { - MOZ_ASSERT(aWorkerPrivate); - aWorkerPrivate->AssertIsOnWorkerThread(); - } - -protected: - virtual bool - MainThreadRun() override - { - AssertIsOnMainThread(); - - ErrorResult rv; - RefPtr promise = mBackingStore->Clear(mRevisionId, rv); - if (NS_WARN_IF(rv.Failed())) { - rv.SuppressException(); - mFailed = true; - return true; - } - - promise->AppendNativeHandler(mPromiseWorkerProxy); - return true; - } -}; - -// A DataStoreRunnable to run DataStore::Sync(...) on the main thread. -class DataStoreSyncStoreRunnable final : public DataStoreRunnable -{ - WorkerDataStoreCursor* mWorkerCursor; - const nsString mRevisionId; - bool mFailed; - -public: - DataStoreSyncStoreRunnable(WorkerPrivate* aWorkerPrivate, - const nsMainThreadPtrHandle& aBackingStore, - WorkerDataStoreCursor* aWorkerCursor, - const nsAString& aRevisionId) - : DataStoreRunnable(aWorkerPrivate, aBackingStore) - , mWorkerCursor(aWorkerCursor) - , mRevisionId(aRevisionId) - , mFailed(false) - { - MOZ_ASSERT(aWorkerPrivate); - aWorkerPrivate->AssertIsOnWorkerThread(); - } - - bool Failed() const - { - return mFailed; - } - -protected: - virtual bool - MainThreadRun() override - { - AssertIsOnMainThread(); - - // Point WorkerDataStoreCursor to DataStoreCursor. - ErrorResult rv; - RefPtr cursor = mBackingStore->Sync(mRevisionId, rv); - if (NS_WARN_IF(rv.Failed())) { - rv.SuppressException(); - mFailed = true; - return true; - } - - nsMainThreadPtrHandle backingCursor( - new nsMainThreadPtrHolder(cursor)); - mWorkerCursor->SetBackingDataStoreCursor(backingCursor); - - return true; - } -}; - -void -WorkerDataStore::GetName(JSContext* aCx, nsAString& aName, ErrorResult& aRv) -{ - WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aCx); - MOZ_ASSERT(workerPrivate); - workerPrivate->AssertIsOnWorkerThread(); - - RefPtr runnable = - new DataStoreGetStringRunnable(workerPrivate, - mBackingStore, - &DataStore::GetName, - aName); - runnable->Dispatch(aRv); -} - -void -WorkerDataStore::GetOwner(JSContext* aCx, nsAString& aOwner, ErrorResult& aRv) -{ - WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aCx); - MOZ_ASSERT(workerPrivate); - workerPrivate->AssertIsOnWorkerThread(); - - RefPtr runnable = - new DataStoreGetStringRunnable(workerPrivate, - mBackingStore, - &DataStore::GetOwner, - aOwner); - runnable->Dispatch(aRv); -} - -bool -WorkerDataStore::GetReadOnly(JSContext* aCx, ErrorResult& aRv) -{ - WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aCx); - MOZ_ASSERT(workerPrivate); - workerPrivate->AssertIsOnWorkerThread(); - - RefPtr runnable = - new DataStoreGetReadOnlyRunnable(workerPrivate, mBackingStore); - runnable->Dispatch(aRv); - if (aRv.Failed()) { - return true; // To be safe, I guess. - } - - return runnable->mReadOnly; -} - -already_AddRefed -WorkerDataStore::Get(JSContext* aCx, - const Sequence& aId, - ErrorResult& aRv) -{ - WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aCx); - MOZ_ASSERT(workerPrivate); - workerPrivate->AssertIsOnWorkerThread(); - - RefPtr promise = Promise::Create(workerPrivate->GlobalScope(), aRv); - if (aRv.Failed()) { - return nullptr; - } - - RefPtr runnable = - new DataStoreGetRunnable(workerPrivate, - mBackingStore, - promise); - - if (!runnable->Id().AppendElements(aId, fallible)) { - aRv.Throw(NS_ERROR_OUT_OF_MEMORY); - return nullptr; - } - - runnable->Dispatch(aRv); - if (aRv.Failed()) { - return nullptr; - } - - if (runnable->Failed()) { - aRv.Throw(NS_ERROR_FAILURE); - return nullptr; - } - - return promise.forget(); -} - -already_AddRefed -WorkerDataStore::Put(JSContext* aCx, - JS::Handle aObj, - const StringOrUnsignedLong& aId, - const nsAString& aRevisionId, - ErrorResult& aRv) -{ - WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aCx); - MOZ_ASSERT(workerPrivate); - workerPrivate->AssertIsOnWorkerThread(); - - RefPtr promise = Promise::Create(workerPrivate->GlobalScope(), aRv); - if (aRv.Failed()) { - return nullptr; - } - - RefPtr runnable = - new DataStorePutRunnable(workerPrivate, - mBackingStore, - promise, - aId, - aRevisionId); - runnable->Write(aCx, aObj, aRv); - if (NS_WARN_IF(aRv.Failed())) { - return nullptr; - } - - runnable->Dispatch(aRv); - if (aRv.Failed()) { - return nullptr; - } - - if (NS_FAILED(runnable->ErrorCode())) { - aRv.Throw(runnable->ErrorCode()); - return nullptr; - } - - return promise.forget(); -} - -already_AddRefed -WorkerDataStore::Add(JSContext* aCx, - JS::Handle aObj, - const Optional& aId, - const nsAString& aRevisionId, - ErrorResult& aRv) -{ - WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aCx); - MOZ_ASSERT(workerPrivate); - workerPrivate->AssertIsOnWorkerThread(); - - RefPtr promise = Promise::Create(workerPrivate->GlobalScope(), aRv); - if (aRv.Failed()) { - return nullptr; - } - - RefPtr runnable = - new DataStoreAddRunnable(workerPrivate, - mBackingStore, - promise, - aId, - aRevisionId); - runnable->Write(aCx, aObj, aRv); - if (NS_WARN_IF(aRv.Failed())) { - return nullptr; - } - - runnable->Dispatch(aRv); - if (aRv.Failed()) { - return nullptr; - } - - if (NS_FAILED(runnable->ErrorCode())) { - aRv.Throw(runnable->ErrorCode()); - return nullptr; - } - - return promise.forget(); -} - -already_AddRefed -WorkerDataStore::Remove(JSContext* aCx, - const StringOrUnsignedLong& aId, - const nsAString& aRevisionId, - ErrorResult& aRv) -{ - WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aCx); - MOZ_ASSERT(workerPrivate); - workerPrivate->AssertIsOnWorkerThread(); - - RefPtr promise = Promise::Create(workerPrivate->GlobalScope(), aRv); - if (aRv.Failed()) { - return nullptr; - } - - RefPtr runnable = - new DataStoreRemoveRunnable(workerPrivate, - mBackingStore, - promise, - aId, - aRevisionId); - runnable->Dispatch(aRv); - if (aRv.Failed()) { - return nullptr; - } - - if (runnable->Failed()) { - aRv.Throw(NS_ERROR_FAILURE); - return nullptr; - } - - return promise.forget(); -} - -already_AddRefed -WorkerDataStore::Clear(JSContext* aCx, - const nsAString& aRevisionId, - ErrorResult& aRv) -{ - WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aCx); - MOZ_ASSERT(workerPrivate); - workerPrivate->AssertIsOnWorkerThread(); - - RefPtr promise = Promise::Create(workerPrivate->GlobalScope(), aRv); - if (aRv.Failed()) { - return nullptr; - } - - RefPtr runnable = - new DataStoreClearRunnable(workerPrivate, - mBackingStore, - promise, - aRevisionId); - runnable->Dispatch(aRv); - if (aRv.Failed()) { - return nullptr; - } - - if (runnable->Failed()) { - aRv.Throw(NS_ERROR_FAILURE); - return nullptr; - } - - return promise.forget(); -} - -void -WorkerDataStore::GetRevisionId(JSContext* aCx, - nsAString& aRevisionId, - ErrorResult& aRv) -{ - WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aCx); - MOZ_ASSERT(workerPrivate); - workerPrivate->AssertIsOnWorkerThread(); - - RefPtr runnable = - new DataStoreGetStringRunnable(workerPrivate, - mBackingStore, - &DataStore::GetRevisionId, - aRevisionId); - runnable->Dispatch(aRv); -} - -// A DataStoreRunnable to run DataStore::GetLength(...) on the main thread. -class DataStoreGetLengthRunnable final : public DataStoreProxyRunnable -{ -public: - DataStoreGetLengthRunnable(WorkerPrivate* aWorkerPrivate, - const nsMainThreadPtrHandle& aBackingStore, - Promise* aWorkerPromise) - : DataStoreProxyRunnable(aWorkerPrivate, aBackingStore, aWorkerPromise) - { - MOZ_ASSERT(aWorkerPrivate); - aWorkerPrivate->AssertIsOnWorkerThread(); - } - -protected: - virtual bool - MainThreadRun() override - { - AssertIsOnMainThread(); - - ErrorResult rv; - RefPtr promise = mBackingStore->GetLength(rv); - promise->AppendNativeHandler(mPromiseWorkerProxy); - if (NS_WARN_IF(rv.Failed())) { - rv.SuppressException(); - mFailed = true; - } - - return true; - } -}; - -already_AddRefed -WorkerDataStore::GetLength(JSContext* aCx, ErrorResult& aRv) -{ - WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aCx); - MOZ_ASSERT(workerPrivate); - workerPrivate->AssertIsOnWorkerThread(); - - RefPtr promise = Promise::Create(workerPrivate->GlobalScope(), aRv); - if (aRv.Failed()) { - return nullptr; - } - - RefPtr runnable = - new DataStoreGetLengthRunnable(workerPrivate, - mBackingStore, - promise); - runnable->Dispatch(aRv); - if (aRv.Failed()) { - return nullptr; - } - - if (runnable->Failed()) { - aRv.Throw(NS_ERROR_FAILURE); - return nullptr; - } - - return promise.forget(); -} - -already_AddRefed -WorkerDataStore::Sync(JSContext* aCx, - const nsAString& aRevisionId, - ErrorResult& aRv) -{ - WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aCx); - MOZ_ASSERT(workerPrivate); - workerPrivate->AssertIsOnWorkerThread(); - - // Create a WorkerDataStoreCursor on the worker. Note that we need to pass - // this WorkerDataStore into the WorkerDataStoreCursor, so that it can keep - // track of which WorkerDataStore owns the WorkerDataStoreCursor. - RefPtr workerCursor = - new WorkerDataStoreCursor(this); - - // DataStoreSyncStoreRunnable will point the WorkerDataStoreCursor to the - // DataStoreCursor created on the main thread. - RefPtr runnable = - new DataStoreSyncStoreRunnable(workerPrivate, - mBackingStore, - workerCursor, - aRevisionId); - runnable->Dispatch(aRv); - if (aRv.Failed()) { - return nullptr; - } - - if (runnable->Failed()) { - aRv.Throw(NS_ERROR_FAILURE); - return nullptr; - } - - return workerCursor.forget(); -} - -void -WorkerDataStore::SetBackingDataStore( - const nsMainThreadPtrHandle& aBackingStore) -{ - mBackingStore = aBackingStore; -} - -void -WorkerDataStore::SetDataStoreChangeEventProxy( - DataStoreChangeEventProxy* aEventProxy) -{ - mEventProxy = aEventProxy; -} - -// A WorkerRunnable to dispatch the DataStoreChangeEvent on the worker thread. -class DispatchDataStoreChangeEventRunnable : public WorkerRunnable -{ -public: - DispatchDataStoreChangeEventRunnable( - DataStoreChangeEventProxy* aDataStoreChangeEventProxy, - DataStoreChangeEvent* aEvent) - : WorkerRunnable(aDataStoreChangeEventProxy->GetWorkerPrivate(), - WorkerThreadUnchangedBusyCount) - , mDataStoreChangeEventProxy(aDataStoreChangeEventProxy) - { - AssertIsOnMainThread(); - MOZ_ASSERT(mDataStoreChangeEventProxy); - - aEvent->GetRevisionId(mRevisionId); - aEvent->GetId(mId); - aEvent->GetOperation(mOperation); - aEvent->GetOwner(mOwner); - } - - virtual bool - WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override - { - MOZ_ASSERT(aWorkerPrivate); - aWorkerPrivate->AssertIsOnWorkerThread(); - MOZ_ASSERT(aWorkerPrivate == mWorkerPrivate); - - MOZ_ASSERT(mDataStoreChangeEventProxy); - - RefPtr workerStore = - mDataStoreChangeEventProxy->GetWorkerStore(); - - DataStoreChangeEventInit eventInit; - eventInit.mBubbles = false; - eventInit.mCancelable = false; - eventInit.mRevisionId = mRevisionId; - eventInit.mId = mId; - eventInit.mOperation = mOperation; - eventInit.mOwner = mOwner; - - RefPtr event = - DataStoreChangeEvent::Constructor(workerStore, - NS_LITERAL_STRING("change"), - eventInit); - - workerStore->DispatchDOMEvent(nullptr, event, nullptr, nullptr); - return true; - } - -protected: - ~DispatchDataStoreChangeEventRunnable() - {} - -private: - RefPtr mDataStoreChangeEventProxy; - - nsString mRevisionId; - Nullable mId; - nsString mOperation; - nsString mOwner; -}; - -DataStoreChangeEventProxy::DataStoreChangeEventProxy( - WorkerPrivate* aWorkerPrivate, - WorkerDataStore* aWorkerStore) - : mWorkerPrivate(aWorkerPrivate) - , mWorkerStore(aWorkerStore) - , mCleanedUp(false) - , mCleanUpLock("cleanUpLock") -{ - MOZ_ASSERT(mWorkerPrivate); - mWorkerPrivate->AssertIsOnWorkerThread(); - MOZ_ASSERT(mWorkerStore); - - // Let the WorkerDataStore keep the DataStoreChangeEventProxy alive to catch - // the coming events until the WorkerDataStore is released. - mWorkerStore->SetDataStoreChangeEventProxy(this); - - // We do this to make sure the worker thread won't shut down before the event - // is dispatched to the WorkerStore on the worker thread. - if (!mWorkerPrivate->AddFeature(this)) { - MOZ_ASSERT(false, "cannot add the worker feature!"); - return; - } -} - -WorkerPrivate* -DataStoreChangeEventProxy::GetWorkerPrivate() const -{ - // It's ok to race on |mCleanedUp|, because it will never cause us to fire - // the assertion when we should not. - MOZ_ASSERT(!mCleanedUp); - - return mWorkerPrivate; -} - -WorkerDataStore* -DataStoreChangeEventProxy::GetWorkerStore() const -{ - return mWorkerStore; -} - -// nsIDOMEventListener implementation. - -NS_IMPL_ISUPPORTS(DataStoreChangeEventProxy, nsIDOMEventListener) - -NS_IMETHODIMP -DataStoreChangeEventProxy::HandleEvent(nsIDOMEvent* aEvent) -{ - AssertIsOnMainThread(); - - MutexAutoLock lock(mCleanUpLock); - // If the worker thread's been cancelled we don't need to dispatch the event. - if (mCleanedUp) { - return NS_OK; - } - - RefPtr event = - static_cast(aEvent); - - RefPtr runnable = - new DispatchDataStoreChangeEventRunnable(this, event); - - runnable->Dispatch(); - - return NS_OK; -} - -// WorkerFeature implementation. - -bool -DataStoreChangeEventProxy::Notify(Status aStatus) -{ - MutexAutoLock lock(mCleanUpLock); - - // |mWorkerPrivate| might not be safe to use anymore if we have already - // cleaned up and RemoveFeature(), so we need to check |mCleanedUp| first. - if (mCleanedUp) { - return true; - } - - MOZ_ASSERT(mWorkerPrivate); - mWorkerPrivate->AssertIsOnWorkerThread(); - - // Release the WorkerStore and remove the DataStoreChangeEventProxy from the - // features of the worker thread since the worker thread has been cancelled. - if (aStatus >= Canceling) { - mWorkerStore = nullptr; - mWorkerPrivate->RemoveFeature(this); - mCleanedUp = true; - } - - return true; -} - -END_WORKERS_NAMESPACE diff --git a/dom/workers/DataStore.h b/dom/workers/DataStore.h deleted file mode 100644 index ead8cd8564..0000000000 --- a/dom/workers/DataStore.h +++ /dev/null @@ -1,138 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_dom_workers_DataStore_h -#define mozilla_dom_workers_DataStore_h - -#include "mozilla/DOMEventTargetHelper.h" -#include "nsProxyRelease.h" - -#include "WorkerFeature.h" - -namespace mozilla { - -class ErrorResult; - -namespace dom { - -class Promise; -class DataStore; -class StringOrUnsignedLong; -class OwningStringOrUnsignedLong; - -namespace workers { - -class DataStoreChangeEventProxy; -class WorkerDataStoreCursor; -class WorkerGlobalScope; - -class WorkerDataStore final : public DOMEventTargetHelper -{ -public: - NS_DECL_ISUPPORTS_INHERITED - - explicit WorkerDataStore(WorkerGlobalScope* aScope); - - // WebIDL (internal functions) - - static already_AddRefed Constructor(GlobalObject& aGlobal, - ErrorResult& aRv); - - virtual JSObject* WrapObject(JSContext *aCx, JS::Handle aGivenProto) override; - - // WebIDL (public APIs) - - void GetName(JSContext* aCx, nsAString& aName, ErrorResult& aRv); - - void GetOwner(JSContext* aCx, nsAString& aOwner, ErrorResult& aRv); - - bool GetReadOnly(JSContext* aCx, ErrorResult& aRv); - - already_AddRefed Get(JSContext* aCx, - const Sequence& aId, - ErrorResult& aRv); - - already_AddRefed Put(JSContext* aCx, - JS::Handle aObj, - const StringOrUnsignedLong& aId, - const nsAString& aRevisionId, - ErrorResult& aRv); - - already_AddRefed Add(JSContext* aCx, - JS::Handle aObj, - const Optional& aId, - const nsAString& aRevisionId, - ErrorResult& aRv); - - already_AddRefed Remove(JSContext* aCx, - const StringOrUnsignedLong& aId, - const nsAString& aRevisionId, - ErrorResult& aRv); - - already_AddRefed Clear(JSContext* aCx, - const nsAString& aRevisionId, - ErrorResult& aRv); - - void GetRevisionId(JSContext* aCx, nsAString& aRevisionId, ErrorResult& aRv); - - already_AddRefed GetLength(JSContext* aCx, ErrorResult& aRv); - - already_AddRefed Sync(JSContext* aCx, - const nsAString& aRevisionId, - ErrorResult& aRv); - - IMPL_EVENT_HANDLER(change) - - void SetBackingDataStore( - const nsMainThreadPtrHandle& aBackingStore); - - void SetDataStoreChangeEventProxy(DataStoreChangeEventProxy* aEventProxy); - -protected: - virtual ~WorkerDataStore() {} - -private: - nsMainThreadPtrHandle mBackingStore; - RefPtr mEventProxy; -}; - -class DataStoreChangeEventProxy final : public nsIDOMEventListener - , public WorkerFeature -{ -public: - NS_DECL_THREADSAFE_ISUPPORTS - NS_DECL_NSIDOMEVENTLISTENER - - DataStoreChangeEventProxy(WorkerPrivate* aWorkerPrivate, - WorkerDataStore* aWorkerStore); - - WorkerPrivate* GetWorkerPrivate() const; - - WorkerDataStore* GetWorkerStore() const; - -protected: - // WorkerFeature implementation. - - bool Notify(Status aStatus) override; - -private: - ~DataStoreChangeEventProxy() {}; - - WorkerPrivate* mWorkerPrivate; - - RefPtr mWorkerStore; - - bool mCleanedUp; // To specify if the worker has been cancelled. - - // Ensure the worker and the main thread won't race to access |mCleanedUp|. - Mutex mCleanUpLock; -}; - -} //namespace workers -} //namespace dom -} //namespace mozilla - -#endif diff --git a/dom/workers/DataStoreCursor.cpp b/dom/workers/DataStoreCursor.cpp deleted file mode 100644 index b6c0fa0c98..0000000000 --- a/dom/workers/DataStoreCursor.cpp +++ /dev/null @@ -1,202 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "DataStore.h" -#include "DataStoreCursor.h" - -#include "mozilla/dom/DataStore.h" -#include "mozilla/dom/DataStoreCursor.h" -#include "mozilla/dom/DataStoreBinding.h" -#include "mozilla/dom/DataStoreImplBinding.h" - -#include "mozilla/dom/Promise.h" -#include "mozilla/dom/PromiseWorkerProxy.h" -#include "mozilla/ErrorResult.h" - -#include "WorkerPrivate.h" -#include "WorkerRunnable.h" -#include "WorkerScope.h" - -BEGIN_WORKERS_NAMESPACE - -NS_IMPL_CYCLE_COLLECTION_ROOT_NATIVE(WorkerDataStoreCursor, AddRef) -NS_IMPL_CYCLE_COLLECTION_UNROOT_NATIVE(WorkerDataStoreCursor, Release) - -NS_IMPL_CYCLE_COLLECTION(WorkerDataStoreCursor, mWorkerStore) - -WorkerDataStoreCursor::WorkerDataStoreCursor(WorkerDataStore* aWorkerStore) - : mWorkerStore(aWorkerStore) -{ - MOZ_ASSERT(!NS_IsMainThread()); -} - -already_AddRefed -WorkerDataStoreCursor::Constructor(GlobalObject& aGlobal, ErrorResult& aRv) -{ - // We don't allow Gecko to create WorkerDataStoreCursor through JS codes like - // window.DataStoreCursor() on the worker, so disable this for now. - NS_NOTREACHED("Cannot use the chrome constructor on the worker!"); - return nullptr; -} - -bool -WorkerDataStoreCursor::WrapObject(JSContext* aCx, - JS::Handle aGivenProto, - JS::MutableHandle aReflector) -{ - return DataStoreCursorBinding_workers::Wrap(aCx, this, aGivenProto, aReflector); -} - -// A WorkerMainThreadRunnable which holds a reference to DataStoreCursor. -class DataStoreCursorRunnable : public WorkerMainThreadRunnable -{ -protected: - nsMainThreadPtrHandle mBackingCursor; - -public: - DataStoreCursorRunnable(WorkerPrivate* aWorkerPrivate, - const nsMainThreadPtrHandle& aBackingCursor) - : WorkerMainThreadRunnable(aWorkerPrivate) - , mBackingCursor(aBackingCursor) - { - MOZ_ASSERT(aWorkerPrivate); - aWorkerPrivate->AssertIsOnWorkerThread(); - } -}; - -// A DataStoreCursorRunnable to run DataStoreCursor::Next(...) on the main -// thread. -class DataStoreCursorNextRunnable final : public DataStoreCursorRunnable -{ - RefPtr mPromiseWorkerProxy; - ErrorResult& mRv; - -public: - DataStoreCursorNextRunnable(WorkerPrivate* aWorkerPrivate, - const nsMainThreadPtrHandle& aBackingCursor, - Promise* aWorkerPromise, - ErrorResult& aRv) - : DataStoreCursorRunnable(aWorkerPrivate, aBackingCursor) - , mRv(aRv) - { - MOZ_ASSERT(aWorkerPrivate); - aWorkerPrivate->AssertIsOnWorkerThread(); - - mPromiseWorkerProxy = - PromiseWorkerProxy::Create(aWorkerPrivate, aWorkerPromise); - } - - void Dispatch(ErrorResult& aRv) - { - if (mPromiseWorkerProxy) { - DataStoreCursorRunnable::Dispatch(aRv); - } - - // If the creation of mProxyWorkerProxy failed, the worker is terminating. - // In this case we don't want to dispatch the runnable and we should stop - // the promise chain here. - } - -protected: - virtual bool - MainThreadRun() override - { - AssertIsOnMainThread(); - - RefPtr promise = mBackingCursor->Next(mRv); - promise->AppendNativeHandler(mPromiseWorkerProxy); - return true; - } -}; - -// A DataStoreCursorRunnable to run DataStoreCursor::Close(...) on the main -// thread. -class DataStoreCursorCloseRunnable final : public DataStoreCursorRunnable -{ - ErrorResult& mRv; - -public: - DataStoreCursorCloseRunnable(WorkerPrivate* aWorkerPrivate, - const nsMainThreadPtrHandle& aBackingCursor, - ErrorResult& aRv) - : DataStoreCursorRunnable(aWorkerPrivate, aBackingCursor) - , mRv(aRv) - { - MOZ_ASSERT(aWorkerPrivate); - aWorkerPrivate->AssertIsOnWorkerThread(); - } - -protected: - virtual bool - MainThreadRun() override - { - AssertIsOnMainThread(); - - mBackingCursor->Close(mRv); - return true; - } -}; - -already_AddRefed -WorkerDataStoreCursor::GetStore(JSContext* aCx, ErrorResult& aRv) -{ - WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aCx); - MOZ_ASSERT(workerPrivate); - workerPrivate->AssertIsOnWorkerThread(); - - // We should direcly return the existing WorkerDataStore which owns this - // WorkerDataStoreCursor, so that the WorkerDataStoreCursor.store can be - // tested as equal to the WorkerDataStore owning this WorkerDataStoreCursor. - MOZ_ASSERT(mWorkerStore); - RefPtr workerStore = mWorkerStore; - return workerStore.forget(); -} - -already_AddRefed -WorkerDataStoreCursor::Next(JSContext* aCx, ErrorResult& aRv) -{ - WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aCx); - MOZ_ASSERT(workerPrivate); - workerPrivate->AssertIsOnWorkerThread(); - - RefPtr promise = Promise::Create(workerPrivate->GlobalScope(), aRv); - if (aRv.Failed()) { - return nullptr; - } - - RefPtr runnable = - new DataStoreCursorNextRunnable(workerPrivate, - mBackingCursor, - promise, - aRv); - runnable->Dispatch(aRv); - if (aRv.Failed()) { - return nullptr; - } - - return promise.forget(); -} - -void -WorkerDataStoreCursor::Close(JSContext* aCx, ErrorResult& aRv) -{ - WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aCx); - MOZ_ASSERT(workerPrivate); - workerPrivate->AssertIsOnWorkerThread(); - - RefPtr runnable = - new DataStoreCursorCloseRunnable(workerPrivate, mBackingCursor, aRv); - runnable->Dispatch(aRv); -} - -void -WorkerDataStoreCursor::SetBackingDataStoreCursor( - const nsMainThreadPtrHandle& aBackingCursor) -{ - mBackingCursor = aBackingCursor; -} - -END_WORKERS_NAMESPACE diff --git a/dom/workers/DataStoreCursor.h b/dom/workers/DataStoreCursor.h deleted file mode 100644 index 3c9d1178c4..0000000000 --- a/dom/workers/DataStoreCursor.h +++ /dev/null @@ -1,66 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef mozilla_dom_workers_DataStoreCursor_h -#define mozilla_dom_workers_DataStoreCursor_h - -#include "nsProxyRelease.h" - -namespace mozilla { - -class ErrorResult; - -namespace dom { - -class Promise; -class GlobalObject; -class DataStoreCursor; - -namespace workers { - -class WorkerDataStore; - -class WorkerDataStoreCursor final -{ -public: - NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(WorkerDataStoreCursor) - NS_DECL_CYCLE_COLLECTION_NATIVE_CLASS(WorkerDataStoreCursor) - - explicit WorkerDataStoreCursor(WorkerDataStore* aWorkerStore); - - // WebIDL (internal functions) - - static already_AddRefed Constructor(GlobalObject& aGlobal, - ErrorResult& aRv); - - bool WrapObject(JSContext *aCx, JS::Handle aGivenProto, JS::MutableHandle aReflector); - - // WebIDL (public APIs) - - already_AddRefed GetStore(JSContext *aCx, ErrorResult& aRv); - - already_AddRefed Next(JSContext *aCx, ErrorResult& aRv); - - void Close(JSContext *aCx, ErrorResult& aRv); - - void SetBackingDataStoreCursor( - const nsMainThreadPtrHandle& aBackingCursor); - -protected: - virtual ~WorkerDataStoreCursor() {} - -private: - nsMainThreadPtrHandle mBackingCursor; - - // Keep track of the WorkerDataStore which owns this WorkerDataStoreCursor. - RefPtr mWorkerStore; -}; - -} //namespace workers -} //namespace dom -} //namespace mozilla - -#endif diff --git a/dom/workers/ServiceWorkerEvents.cpp b/dom/workers/ServiceWorkerEvents.cpp index 72aab12b26..2be5e3df1d 100644 --- a/dom/workers/ServiceWorkerEvents.cpp +++ b/dom/workers/ServiceWorkerEvents.cpp @@ -45,6 +45,7 @@ #include "mozilla/dom/BodyUtil.h" #include "mozilla/dom/EncodingUtils.h" +#include "mozilla/dom/PushUtil.h" #include "mozilla/dom/TypedArray.h" #endif @@ -100,8 +101,10 @@ AsyncLog(nsIInterceptedChannel* aInterceptedChannel, BEGIN_WORKERS_NAMESPACE CancelChannelRunnable::CancelChannelRunnable(nsMainThreadPtrHandle& aChannel, + nsMainThreadPtrHandle& aRegistration, nsresult aStatus) : mChannel(aChannel) + , mRegistration(aRegistration) , mStatus(aStatus) { } @@ -110,8 +113,8 @@ NS_IMETHODIMP CancelChannelRunnable::Run() { MOZ_ASSERT(NS_IsMainThread()); - nsresult rv = mChannel->Cancel(mStatus); - NS_ENSURE_SUCCESS(rv, rv); + mChannel->Cancel(mStatus); + mRegistration->MaybeScheduleUpdate(); return NS_OK; } @@ -130,9 +133,11 @@ FetchEvent::~FetchEvent() void FetchEvent::PostInit(nsMainThreadPtrHandle& aChannel, + nsMainThreadPtrHandle& aRegistration, const nsACString& aScriptSpec) { mChannel = aChannel; + mRegistration = aRegistration; mScriptSpec.Assign(aScriptSpec); } @@ -266,9 +271,10 @@ public: class RespondWithHandler final : public PromiseNativeHandler { nsMainThreadPtrHandle mInterceptedChannel; + nsMainThreadPtrHandle mRegistration; const RequestMode mRequestMode; + const RequestRedirect mRequestRedirectMode; const DebugOnly mIsClientRequest; - const bool mIsNavigationRequest; const nsCString mScriptSpec; const nsString mRequestURL; const nsCString mRespondWithScriptSpec; @@ -279,17 +285,19 @@ public: NS_DECL_ISUPPORTS RespondWithHandler(nsMainThreadPtrHandle& aChannel, + nsMainThreadPtrHandle& aRegistration, RequestMode aRequestMode, bool aIsClientRequest, - bool aIsNavigationRequest, + RequestRedirect aRedirectMode, const nsACString& aScriptSpec, const nsAString& aRequestURL, const nsACString& aRespondWithScriptSpec, uint32_t aRespondWithLineNumber, uint32_t aRespondWithColumnNumber) : mInterceptedChannel(aChannel) + , mRegistration(aRegistration) , mRequestMode(aRequestMode) + , mRequestRedirectMode(aRedirectMode) , mIsClientRequest(aIsClientRequest) - , mIsNavigationRequest(aIsNavigationRequest) , mScriptSpec(aScriptSpec) , mRequestURL(aRequestURL) , mRespondWithScriptSpec(aRespondWithScriptSpec) @@ -333,6 +341,7 @@ private: struct RespondWithClosure { nsMainThreadPtrHandle mInterceptedChannel; + nsMainThreadPtrHandle mRegistration; RefPtr mInternalResponse; ChannelInfo mWorkerChannelInfo; const nsCString mScriptSpec; @@ -343,6 +352,7 @@ struct RespondWithClosure const uint32_t mRespondWithColumnNumber; RespondWithClosure(nsMainThreadPtrHandle& aChannel, + nsMainThreadPtrHandle& aRegistration, InternalResponse* aInternalResponse, const ChannelInfo& aWorkerChannelInfo, const nsCString& aScriptSpec, @@ -352,6 +362,7 @@ struct RespondWithClosure uint32_t aRespondWithLineNumber, uint32_t aRespondWithColumnNumber) : mInterceptedChannel(aChannel) + , mRegistration(aRegistration) , mInternalResponse(aInternalResponse) , mWorkerChannelInfo(aWorkerChannelInfo) , mScriptSpec(aScriptSpec) @@ -374,6 +385,7 @@ void RespondWithCopyComplete(void* aClosure, nsresult aStatus) NS_LITERAL_CSTRING("InterceptionFailedWithURL"), data->mRequestURL); event = new CancelChannelRunnable(data->mInterceptedChannel, + data->mRegistration, NS_ERROR_INTERCEPTION_FAILED); } else { event = new FinishResponse(data->mInterceptedChannel, @@ -565,11 +577,11 @@ RespondWithHandler::ResolvedCallback(JSContext* aCx, JS::Handle aValu MOZ_ASSERT(worker); worker->AssertIsOnWorkerThread(); - // Section "HTTP Fetch", step 2.2: + // Section "HTTP Fetch", step 3.3: // If one of the following conditions is true, return a network error: // * response's type is "error". // * request's mode is not "no-cors" and response's type is "opaque". - // * request is not a navigation request and response's type is + // * request's redirect mode is not "manual" and response's type is // "opaqueredirect". if (response->Type() == ResponseType::Error) { @@ -592,7 +604,8 @@ RespondWithHandler::ResolvedCallback(JSContext* aCx, JS::Handle aValu return; } - if (!mIsNavigationRequest && response->Type() == ResponseType::Opaqueredirect) { + if (mRequestRedirectMode != RequestRedirect::Manual && + response->Type() == ResponseType::Opaqueredirect) { autoCancel.SetCancelMessage( NS_LITERAL_CSTRING("BadOpaqueRedirectInterceptionWithURL"), mRequestURL); return; @@ -620,7 +633,8 @@ RespondWithHandler::ResolvedCallback(JSContext* aCx, JS::Handle aValu } } - nsAutoPtr closure(new RespondWithClosure(mInterceptedChannel, ir, + nsAutoPtr closure(new RespondWithClosure(mInterceptedChannel, + mRegistration, ir, worker->GetChannelInfo(), mScriptSpec, responseURL, @@ -701,7 +715,7 @@ void RespondWithHandler::CancelRequest(nsresult aStatus) { nsCOMPtr runnable = - new CancelChannelRunnable(mInterceptedChannel, aStatus); + new CancelChannelRunnable(mInterceptedChannel, mRegistration, aStatus); NS_DispatchToMainThread(runnable); mRequestWasHandled = true; } @@ -733,9 +747,9 @@ FetchEvent::RespondWith(JSContext* aCx, Promise& aArg, ErrorResult& aRv) StopImmediatePropagation(); mWaitToRespond = true; RefPtr handler = - new RespondWithHandler(mChannel, mRequest->Mode(), ir->IsClientRequest(), - ir->IsNavigationRequest(), mScriptSpec, - NS_ConvertUTF8toUTF16(requestURL), + new RespondWithHandler(mChannel, mRegistration, mRequest->Mode(), + ir->IsClientRequest(), mRequest->Redirect(), + mScriptSpec, NS_ConvertUTF8toUTF16(requestURL), spec, line, column); aArg.AppendNativeHandler(handler); @@ -939,30 +953,12 @@ NS_IMPL_CYCLE_COLLECTION_INHERITED(ExtendableEvent, Event, mPromises) #ifndef MOZ_SIMPLEPUSH namespace { -nsresult -ExtractBytesFromArrayBufferView(const ArrayBufferView& aView, nsTArray& aBytes) -{ - MOZ_ASSERT(aBytes.IsEmpty()); - aView.ComputeLengthAndData(); - aBytes.InsertElementsAt(0, aView.Data(), aView.Length()); - return NS_OK; -} - -nsresult -ExtractBytesFromArrayBuffer(const ArrayBuffer& aBuffer, nsTArray& aBytes) -{ - MOZ_ASSERT(aBytes.IsEmpty()); - aBuffer.ComputeLengthAndData(); - aBytes.InsertElementsAt(0, aBuffer.Data(), aBuffer.Length()); - return NS_OK; -} - nsresult ExtractBytesFromUSVString(const nsAString& aStr, nsTArray& aBytes) { MOZ_ASSERT(aBytes.IsEmpty()); nsCOMPtr encoder = EncodingUtils::EncoderForEncoding("UTF-8"); - if (!encoder) { + if (NS_WARN_IF(!encoder)) { return NS_ERROR_OUT_OF_MEMORY; } @@ -973,17 +969,19 @@ ExtractBytesFromUSVString(const nsAString& aStr, nsTArray& aBytes) return rv; } - aBytes.SetLength(destBufferLen); + if (NS_WARN_IF(!aBytes.SetLength(destBufferLen, fallible))) { + return NS_ERROR_OUT_OF_MEMORY; + } char* destBuffer = reinterpret_cast(aBytes.Elements()); int32_t outLen = destBufferLen; rv = encoder->Convert(aStr.BeginReading(), &srcLen, destBuffer, &outLen); if (NS_WARN_IF(NS_FAILED(rv))) { + aBytes.Clear(); return rv; } - MOZ_ASSERT(outLen <= destBufferLen); - aBytes.SetLength(outLen); + aBytes.TruncateLength(outLen); return NS_OK; } @@ -993,11 +991,19 @@ ExtractBytesFromData(const OwningArrayBufferViewOrArrayBufferOrUSVString& aDataI { if (aDataInit.IsArrayBufferView()) { const ArrayBufferView& view = aDataInit.GetAsArrayBufferView(); - return ExtractBytesFromArrayBufferView(view, aBytes); - } else if (aDataInit.IsArrayBuffer()) { + if (NS_WARN_IF(!PushUtil::CopyArrayBufferViewToArray(view, aBytes))) { + return NS_ERROR_OUT_OF_MEMORY; + } + return NS_OK; + } + if (aDataInit.IsArrayBuffer()) { const ArrayBuffer& buffer = aDataInit.GetAsArrayBuffer(); - return ExtractBytesFromArrayBuffer(buffer, aBytes); - } else if (aDataInit.IsUSVString()) { + if (NS_WARN_IF(!PushUtil::CopyArrayBufferToArray(buffer, aBytes))) { + return NS_ERROR_OUT_OF_MEMORY; + } + return NS_OK; + } + if (aDataInit.IsUSVString()) { return ExtractBytesFromUSVString(aDataInit.GetAsUSVString(), aBytes); } NS_NOTREACHED("Unexpected push message data"); @@ -1006,8 +1012,8 @@ ExtractBytesFromData(const OwningArrayBufferViewOrArrayBufferOrUSVString& aDataI } PushMessageData::PushMessageData(nsISupports* aOwner, - const nsTArray& aBytes) - : mOwner(aOwner), mBytes(aBytes) {} + nsTArray&& aBytes) + : mOwner(aOwner), mBytes(Move(aBytes)) {} PushMessageData::~PushMessageData() { @@ -1125,7 +1131,7 @@ PushEvent::Constructor(mozilla::dom::EventTarget* aOwner, aRv.Throw(rv); return nullptr; } - e->mData = new PushMessageData(aOwner, bytes); + e->mData = new PushMessageData(aOwner, Move(bytes)); } return e.forget(); } diff --git a/dom/workers/ServiceWorkerEvents.h b/dom/workers/ServiceWorkerEvents.h index 09e00237d8..a0a84dc8b3 100644 --- a/dom/workers/ServiceWorkerEvents.h +++ b/dom/workers/ServiceWorkerEvents.h @@ -38,12 +38,16 @@ struct PushEventInit; BEGIN_WORKERS_NAMESPACE +class ServiceWorkerRegistrationInfo; + class CancelChannelRunnable final : public Runnable { nsMainThreadPtrHandle mChannel; + nsMainThreadPtrHandle mRegistration; const nsresult mStatus; public: CancelChannelRunnable(nsMainThreadPtrHandle& aChannel, + nsMainThreadPtrHandle& aRegistration, nsresult aStatus); NS_IMETHOD Run() override; @@ -104,6 +108,7 @@ public: class FetchEvent final : public ExtendableEvent { nsMainThreadPtrHandle mChannel; + nsMainThreadPtrHandle mRegistration; RefPtr mRequest; nsCString mScriptSpec; nsCString mPreventDefaultScriptSpec; @@ -130,6 +135,7 @@ public: } void PostInit(nsMainThreadPtrHandle& aChannel, + nsMainThreadPtrHandle& aRegistration, const nsACString& aScriptSpec); static already_AddRefed @@ -201,7 +207,7 @@ public: ErrorResult& aRv); already_AddRefed Blob(ErrorResult& aRv); - PushMessageData(nsISupports* aOwner, const nsTArray& aBytes); + PushMessageData(nsISupports* aOwner, nsTArray&& aBytes); private: nsCOMPtr mOwner; nsTArray mBytes; diff --git a/dom/workers/ServiceWorkerManager.cpp b/dom/workers/ServiceWorkerManager.cpp index 1715fed700..0762ecd9f9 100644 --- a/dom/workers/ServiceWorkerManager.cpp +++ b/dom/workers/ServiceWorkerManager.cpp @@ -55,7 +55,6 @@ #include "nsContentUtils.h" #include "nsGlobalWindow.h" #include "nsNetUtil.h" -#include "nsIURL.h" #include "nsProxyRelease.h" #include "nsQueryObject.h" #include "nsTArray.h" @@ -273,35 +272,6 @@ ServiceWorkerManager::Init() } } -class ContinueActivateRunnable final : public LifeCycleEventCallback -{ - nsMainThreadPtrHandle mRegistration; - bool mSuccess; - -public: - explicit ContinueActivateRunnable(const nsMainThreadPtrHandle& aRegistration) - : mRegistration(aRegistration) - , mSuccess(false) - { - AssertIsOnMainThread(); - } - - void - SetResult(bool aResult) override - { - mSuccess = aResult; - } - - NS_IMETHOD - Run() override - { - AssertIsOnMainThread(); - mRegistration->FinishActivate(mSuccess); - mRegistration = nullptr; - return NS_OK; - } -}; - class ServiceWorkerResolveWindowPromiseOnRegisterCallback final : public ServiceWorkerJob::Callback { RefPtr mWindow; @@ -345,66 +315,6 @@ public: namespace { -/** - * The spec mandates slightly different behaviors for computing the scope - * prefix string in case a Service-Worker-Allowed header is specified versus - * when it's not available. - * - * With the header: - * "Set maxScopeString to "/" concatenated with the strings in maxScope's - * path (including empty strings), separated from each other by "/"." - * Without the header: - * "Set maxScopeString to "/" concatenated with the strings, except the last - * string that denotes the script's file name, in registration's registering - * script url's path (including empty strings), separated from each other by - * "/"." - * - * In simpler terms, if the header is not present, we should only use the - * "directory" part of the pathname, and otherwise the entire pathname should be - * used. ScopeStringPrefixMode allows the caller to specify the desired - * behavior. - */ -enum ScopeStringPrefixMode { - eUseDirectory, - eUsePath -}; - -nsresult -GetRequiredScopeStringPrefix(nsIURI* aScriptURI, nsACString& aPrefix, - ScopeStringPrefixMode aPrefixMode) -{ - nsresult rv = aScriptURI->GetPrePath(aPrefix); - if (NS_WARN_IF(NS_FAILED(rv))) { - return rv; - } - - if (aPrefixMode == eUseDirectory) { - nsCOMPtr scriptURL(do_QueryInterface(aScriptURI)); - if (NS_WARN_IF(!scriptURL)) { - return NS_ERROR_FAILURE; - } - - nsAutoCString dir; - rv = scriptURL->GetDirectory(dir); - if (NS_WARN_IF(NS_FAILED(rv))) { - return rv; - } - - aPrefix.Append(dir); - } else if (aPrefixMode == eUsePath) { - nsAutoCString path; - rv = aScriptURI->GetPath(path); - if (NS_WARN_IF(NS_FAILED(rv))) { - return rv; - } - - aPrefix.Append(path); - } else { - MOZ_ASSERT_UNREACHABLE("Invalid value for aPrefixMode"); - } - return NS_OK; -} - class PropagateSoftUpdateRunnable final : public Runnable { public: diff --git a/dom/workers/ServiceWorkerPrivate.cpp b/dom/workers/ServiceWorkerPrivate.cpp index f03266cf02..4866ff1c65 100644 --- a/dom/workers/ServiceWorkerPrivate.cpp +++ b/dom/workers/ServiceWorkerPrivate.cpp @@ -1089,6 +1089,7 @@ class FetchEventRunnable : public ExtendableFunctionalEventWorkerRunnable , public nsIHttpHeaderVisitor { nsMainThreadPtrHandle mInterceptedChannel; const nsCString mScriptSpec; + nsMainThreadPtrHandle mRegistration; nsTArray mHeaderNames; nsTArray mHeaderValues; nsCString mSpec; @@ -1117,6 +1118,7 @@ public: aWorkerPrivate, aKeepAliveToken, aRegistration) , mInterceptedChannel(aChannel) , mScriptSpec(aScriptSpec) + , mRegistration(aRegistration) , mClientId(aDocumentId) , mIsReload(aIsReload) , mCacheMode(RequestCache::Default) @@ -1353,7 +1355,7 @@ private: return false; } - event->PostInit(mInterceptedChannel, mScriptSpec); + event->PostInit(mInterceptedChannel, mRegistration, mScriptSpec); event->SetTrusted(true); RefPtr target = do_QueryObject(aWorkerPrivate->GlobalScope()); @@ -1369,11 +1371,8 @@ private: } if (!runnable) { - nsCOMPtr updateRunnable = - new RegistrationUpdateRunnable(mRegistration, false /* time check */); - NS_DispatchToMainThread(runnable.forget()); - runnable = new CancelChannelRunnable(mInterceptedChannel, + mRegistration, NS_ERROR_INTERCEPTION_FAILED); } diff --git a/dom/workers/ServiceWorkerRegistrationInfo.cpp b/dom/workers/ServiceWorkerRegistrationInfo.cpp index 2560717513..cebafca6c6 100644 --- a/dom/workers/ServiceWorkerRegistrationInfo.cpp +++ b/dom/workers/ServiceWorkerRegistrationInfo.cpp @@ -8,6 +8,39 @@ BEGIN_WORKERS_NAMESPACE +namespace { + +class ContinueActivateRunnable final : public LifeCycleEventCallback +{ + nsMainThreadPtrHandle mRegistration; + bool mSuccess; + +public: + explicit ContinueActivateRunnable(const nsMainThreadPtrHandle& aRegistration) + : mRegistration(aRegistration) + , mSuccess(false) + { + AssertIsOnMainThread(); + } + + void + SetResult(bool aResult) override + { + mSuccess = aResult; + } + + NS_IMETHOD + Run() override + { + AssertIsOnMainThread(); + mRegistration->FinishActivate(mSuccess); + mRegistration = nullptr; + return NS_OK; + } +}; + +} // anonymous namespace + void ServiceWorkerRegistrationInfo::Clear() { diff --git a/dom/workers/ServiceWorkerUpdateJob.cpp b/dom/workers/ServiceWorkerUpdateJob.cpp index 22b7d85002..d1f20a3452 100644 --- a/dom/workers/ServiceWorkerUpdateJob.cpp +++ b/dom/workers/ServiceWorkerUpdateJob.cpp @@ -6,6 +6,8 @@ #include "ServiceWorkerUpdateJob.h" +#include "nsIScriptError.h" +#include "nsIURL.h" #include "ServiceWorkerScriptCache.h" #include "Workers.h" @@ -13,6 +15,70 @@ namespace mozilla { namespace dom { namespace workers { +namespace { + +/** + * The spec mandates slightly different behaviors for computing the scope + * prefix string in case a Service-Worker-Allowed header is specified versus + * when it's not available. + * + * With the header: + * "Set maxScopeString to "/" concatenated with the strings in maxScope's + * path (including empty strings), separated from each other by "/"." + * Without the header: + * "Set maxScopeString to "/" concatenated with the strings, except the last + * string that denotes the script's file name, in registration's registering + * script url's path (including empty strings), separated from each other by + * "/"." + * + * In simpler terms, if the header is not present, we should only use the + * "directory" part of the pathname, and otherwise the entire pathname should be + * used. ScopeStringPrefixMode allows the caller to specify the desired + * behavior. + */ +enum ScopeStringPrefixMode { + eUseDirectory, + eUsePath +}; + +nsresult +GetRequiredScopeStringPrefix(nsIURI* aScriptURI, nsACString& aPrefix, + ScopeStringPrefixMode aPrefixMode) +{ + nsresult rv = aScriptURI->GetPrePath(aPrefix); + if (NS_WARN_IF(NS_FAILED(rv))) { + return rv; + } + + if (aPrefixMode == eUseDirectory) { + nsCOMPtr scriptURL(do_QueryInterface(aScriptURI)); + if (NS_WARN_IF(!scriptURL)) { + return NS_ERROR_FAILURE; + } + + nsAutoCString dir; + rv = scriptURL->GetDirectory(dir); + if (NS_WARN_IF(NS_FAILED(rv))) { + return rv; + } + + aPrefix.Append(dir); + } else if (aPrefixMode == eUsePath) { + nsAutoCString path; + rv = aScriptURI->GetPath(path); + if (NS_WARN_IF(NS_FAILED(rv))) { + return rv; + } + + aPrefix.Append(path); + } else { + MOZ_ASSERT_UNREACHABLE("Invalid value for aPrefixMode"); + } + return NS_OK; +} + +} // anonymous namespace + class ServiceWorkerUpdateJob::CompareCallback final : public serviceWorkerScriptCache::CompareCallback { RefPtr mJob; diff --git a/dom/workers/WorkerNavigator.cpp b/dom/workers/WorkerNavigator.cpp index 75156501f7..ef84e10d2b 100644 --- a/dom/workers/WorkerNavigator.cpp +++ b/dom/workers/WorkerNavigator.cpp @@ -4,11 +4,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#include "DataStore.h" - #include "mozilla/dom/BindingUtils.h" -#include "mozilla/dom/DataStore.h" -#include "mozilla/dom/DataStoreBinding.h" #include "mozilla/dom/Promise.h" #include "mozilla/dom/PromiseWorkerProxy.h" #include "mozilla/dom/WorkerNavigator.h" @@ -23,6 +19,8 @@ #include "WorkerRunnable.h" #include "WorkerScope.h" +#include "mozilla/dom/Navigator.h" + namespace mozilla { namespace dom { @@ -54,252 +52,6 @@ WorkerNavigator::WrapObject(JSContext* aCx, JS::Handle aGivenProto) return WorkerNavigatorBinding::Wrap(aCx, this, aGivenProto); } -// A WorkerMainThreadRunnable to synchronously add DataStoreChangeEventProxy on -// the main thread. We need this because we have to access |mBackingStore| on -// the main thread. -class DataStoreAddEventListenerRunnable : public WorkerMainThreadRunnable -{ - nsMainThreadPtrHandle mBackingStore; - DataStoreChangeEventProxy* mEventProxy; - -protected: - virtual bool - MainThreadRun() override - { - AssertIsOnMainThread(); - - // Add |mEventProxy| as an event listner to DataStore. - if (NS_FAILED(mBackingStore->AddEventListener(NS_LITERAL_STRING("change"), - mEventProxy, - false, - false, - 2))) { - MOZ_ASSERT(false, "failed to add event listener!"); - return false; - } - - return true; - } - -public: - DataStoreAddEventListenerRunnable( - WorkerPrivate* aWorkerPrivate, - const nsMainThreadPtrHandle& aBackingStore, - DataStoreChangeEventProxy* aEventProxy) - : WorkerMainThreadRunnable(aWorkerPrivate) - , mBackingStore(aBackingStore) - , mEventProxy(aEventProxy) - { - MOZ_ASSERT(aWorkerPrivate); - aWorkerPrivate->AssertIsOnWorkerThread(); - } -}; - -#define WORKER_DATA_STORES_TAG JS_SCTAG_USER_MIN - -static JSObject* -GetDataStoresProxyCloneCallbacksRead(JSContext* aCx, - JSStructuredCloneReader* aReader, - const PromiseWorkerProxy* aProxy, - uint32_t aTag, - uint32_t aData) -{ - WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aCx); - MOZ_ASSERT(workerPrivate); - workerPrivate->AssertIsOnWorkerThread(); - - if (aTag != WORKER_DATA_STORES_TAG) { - MOZ_ASSERT(false, "aTag must be WORKER_DATA_STORES_TAG!"); - return nullptr; - } - - NS_ASSERTION(!aData, "aData should be empty"); - - // Read the holder from the buffer, which points to the data store. - nsMainThreadPtrHolder* dataStoreholder; - if (!JS_ReadBytes(aReader, &dataStoreholder, sizeof(dataStoreholder))) { - MOZ_ASSERT(false, "cannot read bytes for dataStoreholder!"); - return nullptr; - } - - // Protect workerStoreObj from moving GC during ~nsRefPtr. - JS::Rooted workerStoreObj(aCx, nullptr); - { - RefPtr workerStore = - new WorkerDataStore(workerPrivate->GlobalScope()); - nsMainThreadPtrHandle backingStore(dataStoreholder); - - // When we're on the worker thread, prepare a DataStoreChangeEventProxy. - RefPtr eventProxy = - new DataStoreChangeEventProxy(workerPrivate, workerStore); - - // Add the DataStoreChangeEventProxy as an event listener on the main thread. - RefPtr runnable = - new DataStoreAddEventListenerRunnable(workerPrivate, - backingStore, - eventProxy); - ErrorResult rv; - runnable->Dispatch(rv); - if (rv.MaybeSetPendingException(aCx)) { - return nullptr; - } - - // Point WorkerDataStore to DataStore. - workerStore->SetBackingDataStore(backingStore); - - JS::Rooted global(aCx, JS::CurrentGlobalOrNull(aCx)); - if (!global) { - MOZ_ASSERT(false, "cannot get global!"); - } else { - workerStoreObj = workerStore->WrapObject(aCx, nullptr); - if (!JS_WrapObject(aCx, &workerStoreObj)) { - MOZ_ASSERT(false, "cannot wrap object for workerStoreObj!"); - workerStoreObj = nullptr; - } - } - } - - return workerStoreObj; -} - -static bool -GetDataStoresProxyCloneCallbacksWrite(JSContext* aCx, - JSStructuredCloneWriter* aWriter, - PromiseWorkerProxy* aProxy, - JS::Handle aObj) -{ - AssertIsOnMainThread(); - - if (!JS_WriteUint32Pair(aWriter, WORKER_DATA_STORES_TAG, 0)) { - MOZ_ASSERT(false, "cannot write pair for WORKER_DATA_STORES_TAG!"); - return false; - } - - JS::Rooted storeObj(aCx, aObj); - - DataStore* store = nullptr; - nsresult rv = UNWRAP_OBJECT(DataStore, storeObj, store); - if (NS_FAILED(rv)) { - MOZ_ASSERT(false, "cannot unwrap the DataStore object!"); - return false; - } - - // We keep the data store alive here. - aProxy->StoreISupports(store); - - // Construct the nsMainThreadPtrHolder pointing to the data store. - nsMainThreadPtrHolder* dataStoreholder = - new nsMainThreadPtrHolder(store); - - // And write the dataStoreholder into the buffer. - if (!JS_WriteBytes(aWriter, &dataStoreholder, sizeof(dataStoreholder))) { - MOZ_ASSERT(false, "cannot write bytes for dataStoreholder!"); - return false; - } - - return true; -} - -static const PromiseWorkerProxy::PromiseWorkerProxyStructuredCloneCallbacks -kGetDataStoresCloneCallbacks= { - GetDataStoresProxyCloneCallbacksRead, - GetDataStoresProxyCloneCallbacksWrite -}; - -// A WorkerMainThreadRunnable to run WorkerNavigator::GetDataStores(...) on the -// main thread. -class NavigatorGetDataStoresRunnable final : public WorkerMainThreadRunnable -{ - RefPtr mPromiseWorkerProxy; - const nsString mName; - const nsString mOwner; - ErrorResult& mRv; - -public: - NavigatorGetDataStoresRunnable(WorkerPrivate* aWorkerPrivate, - Promise* aWorkerPromise, - const nsAString& aName, - const nsAString& aOwner, - ErrorResult& aRv) - : WorkerMainThreadRunnable(aWorkerPrivate) - , mName(aName) - , mOwner(aOwner) - , mRv(aRv) - { - MOZ_ASSERT(aWorkerPrivate); - aWorkerPrivate->AssertIsOnWorkerThread(); - - // this might return null if the worker has started the close handler. - mPromiseWorkerProxy = - PromiseWorkerProxy::Create(aWorkerPrivate, - aWorkerPromise, - &kGetDataStoresCloneCallbacks); - } - - void Dispatch(ErrorResult& aRv) - { - if (mPromiseWorkerProxy) { - WorkerMainThreadRunnable::Dispatch(aRv); - } - - // If the creation of mProxyWorkerProxy failed, the worker is terminating. - // In this case we don't want to dispatch the runnable and we should stop - // the promise chain here. - } - - -protected: - virtual bool - MainThreadRun() override - { - AssertIsOnMainThread(); - - // Walk up to the containing window. - WorkerPrivate* wp = mWorkerPrivate; - while (wp->GetParent()) { - wp = wp->GetParent(); - } - nsPIDOMWindow* window = wp->GetWindow(); - - // TODO SharedWorker has null window. Don't need to worry about at this - // point, though. - if (!window) { - mRv.Throw(NS_ERROR_FAILURE); - return false; - } - - RefPtr promise = - Navigator::GetDataStores(window, mName, mOwner, mRv); - promise->AppendNativeHandler(mPromiseWorkerProxy); - return true; - } -}; - -already_AddRefed -WorkerNavigator::GetDataStores(JSContext* aCx, - const nsAString& aName, - const nsAString& aOwner, - ErrorResult& aRv) -{ - WorkerPrivate* workerPrivate = GetWorkerPrivateFromContext(aCx); - MOZ_ASSERT(workerPrivate); - workerPrivate->AssertIsOnWorkerThread(); - - RefPtr promise = Promise::Create(workerPrivate->GlobalScope(), aRv); - if (aRv.Failed()) { - return nullptr; - } - - RefPtr runnable = - new NavigatorGetDataStoresRunnable(workerPrivate, promise, aName, aOwner, aRv); - runnable->Dispatch(aRv); - if (aRv.Failed()) { - return nullptr; - } - - return promise.forget(); -} - void WorkerNavigator::SetLanguages(const nsTArray& aLanguages) { diff --git a/dom/workers/WorkerNavigator.h b/dom/workers/WorkerNavigator.h index b0ba074550..bca77e19cf 100644 --- a/dom/workers/WorkerNavigator.h +++ b/dom/workers/WorkerNavigator.h @@ -12,10 +12,6 @@ #include "nsString.h" #include "nsWrapperCache.h" -// Need this to use Navigator::HasDataStoreSupport() in -// WorkerNavigatorBinding.cpp -#include "mozilla/dom/Navigator.h" - namespace mozilla { namespace dom { class Promise; @@ -104,11 +100,6 @@ public: void SetLanguages(const nsTArray& aLanguages); - already_AddRefed GetDataStores(JSContext* aCx, - const nsAString& aName, - const nsAString& aOwner, - ErrorResult& aRv); - uint64_t HardwareConcurrency() const; }; diff --git a/dom/workers/moz.build b/dom/workers/moz.build index 872e18ac48..f4a4522240 100644 --- a/dom/workers/moz.build +++ b/dom/workers/moz.build @@ -32,8 +32,6 @@ EXPORTS.mozilla.dom.workers += [ # Stuff needed for the bindings, not really public though. EXPORTS.mozilla.dom.workers.bindings += [ - 'DataStore.h', - 'DataStoreCursor.h', 'Performance.h', 'ServiceWorker.h', 'ServiceWorkerClient.h', @@ -55,8 +53,6 @@ XPIDL_SOURCES += [ UNIFIED_SOURCES += [ 'ChromeWorkerScope.cpp', - 'DataStore.cpp', - 'DataStoreCursor.cpp', 'FileReaderSync.cpp', 'Performance.cpp', 'Principal.cpp', diff --git a/dom/workers/test/navigator_worker.js b/dom/workers/test/navigator_worker.js index 3b7385b375..35941f8332 100644 --- a/dom/workers/test/navigator_worker.js +++ b/dom/workers/test/navigator_worker.js @@ -8,10 +8,8 @@ var supportedProps = [ "appCodeName", "appName", "appVersion", - { name: "getDataStores", b2g: true }, "platform", "product", - "taintEnabled", "userAgent", "onLine", "language", @@ -66,14 +64,7 @@ function startTest(isB2G) { } obj = { name: prop }; - - if (prop === "taintEnabled") { - obj.value = navigator[prop](); - } else if (prop === "getDataStores") { - obj.value = typeof navigator[prop]; - } else { - obj.value = navigator[prop]; - } + obj.value = navigator[prop]; postMessage(JSON.stringify(obj)); } diff --git a/dom/workers/test/serviceworkers/test_serviceworker_interfaces.js b/dom/workers/test/serviceworkers/test_serviceworker_interfaces.js index c3bdda40cb..6427a550fb 100644 --- a/dom/workers/test/serviceworkers/test_serviceworker_interfaces.js +++ b/dom/workers/test/serviceworkers/test_serviceworker_interfaces.js @@ -90,10 +90,6 @@ var interfaceNamesInGlobalScope = "Clients", // IMPORTANT: Do not change this list without review from a DOM peer! "CustomEvent", -// IMPORTANT: Do not change this list without review from a DOM peer! - { name: "DataStore", b2g: true }, -// IMPORTANT: Do not change this list without review from a DOM peer! - { name: "DataStoreCursor", b2g: true }, // IMPORTANT: Do not change this list without review from a DOM peer! "Directory", // IMPORTANT: Do not change this list without review from a DOM peer! diff --git a/dom/workers/test/test_navigator.html b/dom/workers/test/test_navigator.html index d54152778a..6fdf3bbf79 100644 --- a/dom/workers/test/test_navigator.html +++ b/dom/workers/test/test_navigator.html @@ -40,12 +40,6 @@ Tests of DOM Worker Navigator return; } - if (args.name === "getDataStores") { - var type = typeof navigator[args.name]; - is(type, args.value, "getDataStores() exists and it's a function."); - return; - } - if (args.name === "languages") { is(navigator.languages.toString(), args.value.toString(), "languages matches"); return; diff --git a/dom/workers/test/test_worker_interfaces.js b/dom/workers/test/test_worker_interfaces.js index a577b6ef7f..5c7b9ba924 100644 --- a/dom/workers/test/test_worker_interfaces.js +++ b/dom/workers/test/test_worker_interfaces.js @@ -88,10 +88,6 @@ var interfaceNamesInGlobalScope = "CustomEvent", // IMPORTANT: Do not change this list without review from a DOM peer! "DedicatedWorkerGlobalScope", -// IMPORTANT: Do not change this list without review from a DOM peer! - { name: "DataStore", b2g: true }, -// IMPORTANT: Do not change this list without review from a DOM peer! - { name: "DataStoreCursor", b2g: true }, // IMPORTANT: Do not change this list without review from a DOM peer! "Directory", // IMPORTANT: Do not change this list without review from a DOM peer! diff --git a/hal/gonk/GonkDiskSpaceWatcher.cpp b/hal/gonk/GonkDiskSpaceWatcher.cpp index ef3359525e..777619bc9f 100644 --- a/hal/gonk/GonkDiskSpaceWatcher.cpp +++ b/hal/gonk/GonkDiskSpaceWatcher.cpp @@ -120,7 +120,7 @@ static GonkDiskSpaceWatcher* gHalDiskSpaceWatcher = nullptr; static const char kWatchedPath[] = "/data"; // Helper class to dispatch calls to xpcom on the main thread. -class DiskSpaceNotifier : public nsRunnable +class DiskSpaceNotifier : public Runnable { public: DiskSpaceNotifier(const bool aIsDiskFull, const uint64_t aFreeSpace) : @@ -140,7 +140,7 @@ private: }; // Helper runnable to delete the watcher on the main thread. -class DiskSpaceCleaner : public nsRunnable +class DiskSpaceCleaner : public Runnable { public: NS_IMETHOD Run() @@ -310,7 +310,6 @@ StartDiskSpaceWatcher() gHalDiskSpaceWatcher = new GonkDiskSpaceWatcher(); XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableMethod(gHalDiskSpaceWatcher, &GonkDiskSpaceWatcher::DoStart)); } @@ -323,7 +322,6 @@ StopDiskSpaceWatcher() } XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableMethod(gHalDiskSpaceWatcher, &GonkDiskSpaceWatcher::DoStop)); } diff --git a/hal/gonk/GonkFMRadio.cpp b/hal/gonk/GonkFMRadio.cpp index a88d544f60..d33c38faee 100644 --- a/hal/gonk/GonkFMRadio.cpp +++ b/hal/gonk/GonkFMRadio.cpp @@ -84,7 +84,7 @@ setControl(uint32_t id, int32_t value) return ioctl(sRadioFD, VIDIOC_S_CTRL, &control); } -class RadioUpdate : public nsRunnable { +class RadioUpdate : public Runnable { hal::FMRadioOperation mOp; hal::FMRadioOperationStatus mStatus; public: diff --git a/hal/gonk/GonkHal.cpp b/hal/gonk/GonkHal.cpp index a328b40509..05fe4a6c14 100644 --- a/hal/gonk/GonkHal.cpp +++ b/hal/gonk/GonkHal.cpp @@ -423,7 +423,7 @@ CancelVibrate(const hal::WindowIdentifier &) namespace { -class BatteryUpdater : public nsRunnable { +class BatteryUpdater : public Runnable { public: NS_IMETHOD Run() { @@ -525,7 +525,6 @@ void EnableBatteryNotifications() { XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(RegisterBatteryObserverIOThread)); } @@ -543,7 +542,6 @@ void DisableBatteryNotifications() { XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(UnregisterBatteryObserverIOThread)); } @@ -1043,7 +1041,7 @@ int AlarmData::sNextGeneration = 0; AlarmData* sAlarmData = nullptr; -class AlarmFiredEvent : public nsRunnable { +class AlarmFiredEvent : public Runnable { public: AlarmFiredEvent(int aGeneration) : mGeneration(aGeneration) {} @@ -1976,7 +1974,7 @@ namespace { * We have to run this from the main thread since preferences can only be read on * main thread. */ -class SetThreadPriorityRunnable : public nsRunnable +class SetThreadPriorityRunnable : public Runnable { public: SetThreadPriorityRunnable(pid_t aThreadId, hal::ThreadPriority aThreadPriority) diff --git a/hal/gonk/GonkSensor.cpp b/hal/gonk/GonkSensor.cpp index f361e064be..3d2135dc9e 100644 --- a/hal/gonk/GonkSensor.cpp +++ b/hal/gonk/GonkSensor.cpp @@ -126,7 +126,7 @@ SensorseventStatus(const sensors_event_t& data) return SENSOR_STATUS_UNRELIABLE; } -class SensorRunnable : public nsRunnable +class SensorRunnable : public Runnable { public: SensorRunnable(const sensors_event_t& data, const sensor_t* sensors, ssize_t size) @@ -323,8 +323,8 @@ EnableSensorNotificationsInternal(SensorType aSensor) MOZ_ASSERT(sPollingThread); // sPollingThread never terminates because poll may never return sPollingThread->Start(); - sPollingThread->message_loop()->PostTask(FROM_HERE, - NewRunnableFunction(PollSensors)); + sPollingThread->message_loop()->PostTask( + NewRunnableFunction(PollSensors)); } SetSensorState(aSensor, true); diff --git a/hal/gonk/GonkSwitch.cpp b/hal/gonk/GonkSwitch.cpp index 1e8ee81f71..9aaa80cad5 100644 --- a/hal/gonk/GonkSwitch.cpp +++ b/hal/gonk/GonkSwitch.cpp @@ -67,13 +67,13 @@ public: strcmp(mDevPath, aEvent->findParam("DEVPATH"))) { return false; } - + mState = ConvertState(GetStateString(aEvent)); return mState != SWITCH_STATE_UNKNOWN; } SwitchState GetState() - { + { return mState; } @@ -115,7 +115,7 @@ protected: if (state[bytesRead - 1] == '\n') { bytesRead--; } - + state[bytesRead] = '\0'; mState = ConvertState(state); } @@ -212,7 +212,7 @@ protected: typedef nsTArray > SwitchHandlerArray; -class SwitchEventRunnable : public nsRunnable +class SwitchEventRunnable : public Runnable { public: SwitchEventRunnable(SwitchEvent& aEvent) : mEvent(aEvent) @@ -264,10 +264,10 @@ public: void Notify(const NetlinkEvent& aEvent) { SwitchState currState; - + SwitchDevice device = GetEventInfo(aEvent, currState); if (device == SWITCH_DEVICE_UNKNOWN) { - return; + return; } EventInfo& info = mEventInfo[device]; @@ -372,7 +372,7 @@ private: { //working around the android code not being const-correct NetlinkEvent *e = const_cast(&aEvent); - + for (size_t i = 0; i < mHandler.Length(); i++) { if (mHandler[i]->CheckEvent(e)) { aState = mHandler[i]->GetState(); @@ -413,7 +413,7 @@ EnableSwitchNotificationsIOThread(SwitchDevice aDevice, Monitor *aMonitor) lock.Notify(); } - // Notify the latest state if IO thread has the information. + // Notify the latest state if IO thread has the information. if (sSwitchObserver->GetEnableCount() > 1) { sSwitchObserver->NotifyAnEvent(aDevice); } @@ -426,7 +426,6 @@ EnableSwitchNotifications(SwitchDevice aDevice) { MonitorAutoLock lock(monitor); XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(EnableSwitchNotificationsIOThread, aDevice, &monitor)); lock.Wait(); } @@ -444,7 +443,6 @@ void DisableSwitchNotifications(SwitchDevice aDevice) { XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(DisableSwitchNotificationsIOThread, aDevice)); } @@ -465,7 +463,6 @@ NotifySwitchStateIOThread(SwitchDevice aDevice, SwitchState aState) void NotifySwitchStateFromInputDevice(SwitchDevice aDevice, SwitchState aState) { XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(NotifySwitchStateIOThread, aDevice, aState)); } diff --git a/hal/gonk/UeventPoller.cpp b/hal/gonk/UeventPoller.cpp index 8391df9d91..447c998df0 100644 --- a/hal/gonk/UeventPoller.cpp +++ b/hal/gonk/UeventPoller.cpp @@ -161,17 +161,19 @@ NetlinkPoller::OpenSocket() static StaticAutoPtr sPoller; -class UeventInitTask : public Task +class UeventInitTask : public Runnable { - virtual void Run() + NS_IMETHOD Run() override { if (!sPoller) { - return; + return NS_OK; } if (sPoller->OpenSocket()) { - return; + return NS_OK; } - sPoller->GetIOLoop()->PostDelayedTask(FROM_HERE, new UeventInitTask(), 1000); + sPoller->GetIOLoop()->PostDelayedTask(MakeAndAddRef(), + 1000); + return NS_OK; } }; @@ -217,7 +219,6 @@ public: MonitorAutoLock lock(*sMonitor); XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(ShutdownUeventIOThread)); while (!sShutdown) { @@ -267,7 +268,7 @@ InitializeUevent() { MOZ_ASSERT(!sPoller); sPoller = new NetlinkPoller(); - sPoller->GetIOLoop()->PostTask(FROM_HERE, new UeventInitTask()); + sPoller->GetIOLoop()->PostTask(MakeAndAddRef()); ShutdownNetlinkPoller::MaybeInit(); } diff --git a/ipc/glue/ProcessUtils_linux.cpp b/ipc/glue/ProcessUtils_linux.cpp index b82f508458..2f84d5d779 100644 --- a/ipc/glue/ProcessUtils_linux.cpp +++ b/ipc/glue/ProcessUtils_linux.cpp @@ -250,8 +250,7 @@ ProcLoaderClientDeinit() sProcLoaderLoop = nullptr; MessageLoop::current()-> - PostTask(FROM_HERE, - NewRunnableFunction(&_ProcLoaderParentDestroy, + PostTask(NewRunnableFunction(&_ProcLoaderParentDestroy, procLoaderParent)); } @@ -314,8 +313,7 @@ ProcLoaderLoad(const char *aArgv[], *aProcessHandle = sProcLoaderPid; sProcLoaderPid = 0; - sProcLoaderLoop->PostTask(FROM_HERE, - NewRunnableFunction(AsyncSendLoad, load)); + sProcLoaderLoop->PostTask(NewRunnableFunction(AsyncSendLoad, load)); return true; } @@ -491,9 +489,8 @@ ProcLoaderChild::RecvLoad(InfallibleTArray&& aArgv, SendLoadComplete(mPeerPid, aCookie); - MessageLoop::current()->PostTask(FROM_HERE, - NewRunnableFunction(_ProcLoaderChildDestroy, - this)); + MessageLoop::current()->PostTask( + NewRunnableFunction(_ProcLoaderChildDestroy, this)); return true; } @@ -510,9 +507,8 @@ ProcLoaderChild::OnChannelError() MOZ_ASSERT(sProcLoaderDispatchedTask == nullptr); sProcLoaderDispatchedTask = new ProcLoaderNoopRunner(); - MessageLoop::current()->PostTask(FROM_HERE, - NewRunnableFunction(_ProcLoaderChildDestroy, - this)); + MessageLoop::current()->PostTask( + NewRunnableFunction(_ProcLoaderChildDestroy, this)); } /** diff --git a/ipc/hal/DaemonRunnables.h b/ipc/hal/DaemonRunnables.h index d649ce303b..ae55838cfb 100644 --- a/ipc/hal/DaemonRunnables.h +++ b/ipc/hal/DaemonRunnables.h @@ -16,7 +16,7 @@ namespace ipc { namespace details { -class DaemonRunnable : public nsRunnable +class DaemonRunnable : public Runnable { protected: DaemonRunnable() = default; diff --git a/ipc/hal/DaemonSocket.cpp b/ipc/hal/DaemonSocket.cpp index 86c625fd3c..94c36b9551 100644 --- a/ipc/hal/DaemonSocket.cpp +++ b/ipc/hal/DaemonSocket.cpp @@ -218,8 +218,8 @@ DaemonSocket::SendSocketData(UnixSocketIOBuffer* aBuffer) MOZ_ASSERT(mIO->IsConsumerThread()); mIO->GetIOLoop()->PostTask( - FROM_HERE, - new SocketIOSendTask(mIO, aBuffer)); + MakeAndAddRef>( + mIO, aBuffer)); } // |SocketBase| @@ -235,7 +235,7 @@ DaemonSocket::Close() MOZ_ASSERT(mIO->IsConsumerThread()); mIO->ShutdownOnConsumerThread(); - mIO->GetIOLoop()->PostTask(FROM_HERE, new SocketIOShutdownTask(mIO)); + mIO->GetIOLoop()->PostTask(MakeAndAddRef(mIO)); mIO = nullptr; NotifyDisconnect(); diff --git a/ipc/netd/Netd.cpp b/ipc/netd/Netd.cpp index 85afc72056..c8add38ac5 100644 --- a/ipc/netd/Netd.cpp +++ b/ipc/netd/Netd.cpp @@ -31,7 +31,7 @@ namespace { RefPtr gNetdClient; RefPtr gNetdConsumer; -class StopNetdConsumer : public nsRunnable { +class StopNetdConsumer : public mozilla::Runnable { public: NS_IMETHOD Run() { @@ -217,8 +217,7 @@ NetdClient::Start() } MessageLoopForIO::current()-> - PostDelayedTask(FROM_HERE, - NewRunnableFunction(NetdClient::Start), + PostDelayedTask(NewRunnableFunction(NetdClient::Start), 1000); return; } @@ -334,7 +333,6 @@ StartNetd(NetdConsumer* aNetdConsumer) gNetdConsumer = aNetdConsumer; XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(InitNetdIOThread)); } @@ -347,7 +345,6 @@ StopNetd() NS_ASSERTION(currentThread, "This should never be null!"); XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(ShutdownNetdIOThread)); while (gNetdConsumer) { @@ -370,7 +367,6 @@ SendNetdCommand(NetdCommand* aMessage) MOZ_ASSERT(aMessage); XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, NewRunnableFunction(NetdClient::SendNetdCommandIOThread, aMessage)); } diff --git a/ipc/netd/Netd.h b/ipc/netd/Netd.h index 31d0dc03cc..e4e20d2a86 100644 --- a/ipc/netd/Netd.h +++ b/ipc/netd/Netd.h @@ -37,9 +37,9 @@ public: virtual void MessageReceived(NetdCommand* aMessage) = 0; }; -class NetdWriteTask : public Task +class NetdWriteTask : public Runnable { - virtual void Run(); + NS_IMETHOD Run(); }; class NetdClient : public MessageLoopForIO::LineWatcher diff --git a/ipc/ril/RilSocket.cpp b/ipc/ril/RilSocket.cpp index 6056a97236..6b86e31bee 100644 --- a/ipc/ril/RilSocket.cpp +++ b/ipc/ril/RilSocket.cpp @@ -44,7 +44,7 @@ public: // Delayed-task handling // - void SetDelayedConnectTask(CancelableTask* aTask); + void SetDelayedConnectTask(CancelableRunnable* aTask); void ClearDelayedConnectTask(); void CancelDelayedConnectTask(); @@ -88,7 +88,7 @@ private: * Task member for delayed connect task. Should only be access on consumer * thread. */ - CancelableTask* mDelayedConnectTask; + CancelableRunnable* mDelayedConnectTask; /** * I/O buffer for received data @@ -134,7 +134,7 @@ RilSocketIO::GetDataSocket() } void -RilSocketIO::SetDelayedConnectTask(CancelableTask* aTask) +RilSocketIO::SetDelayedConnectTask(CancelableRunnable* aTask) { MOZ_ASSERT(IsConsumerThread()); @@ -281,12 +281,14 @@ public: : SocketIOTask(aIO) { } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(!GetIO()->IsConsumerThread()); MOZ_ASSERT(!IsCanceled()); GetIO()->Connect(); + + return NS_OK; } }; @@ -298,21 +300,23 @@ public: : SocketIOTask(aIO) { } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(GetIO()->IsConsumerThread()); if (IsCanceled()) { - return; + return NS_OK; } RilSocketIO* io = GetIO(); if (io->IsShutdownOnConsumerThread()) { - return; + return NS_OK; } io->ClearDelayedConnectTask(); - io->GetIOLoop()->PostTask(FROM_HERE, new ConnectTask(io)); + io->GetIOLoop()->PostTask(MakeAndAddRef(io)); + + return NS_OK; } }; @@ -357,12 +361,12 @@ RilSocket::Connect(UnixSocketConnector* aConnector, int aDelayMs, SetConnectionStatus(SOCKET_CONNECTING); if (aDelayMs > 0) { - RilSocketIO::DelayedConnectTask* connectTask = - new RilSocketIO::DelayedConnectTask(mIO); + RefPtr connectTask = + MakeAndAddRef(mIO); mIO->SetDelayedConnectTask(connectTask); - MessageLoop::current()->PostDelayedTask(FROM_HERE, connectTask, aDelayMs); + MessageLoop::current()->PostDelayedTask(connectTask.forget(), aDelayMs); } else { - aIOLoop->PostTask(FROM_HERE, new RilSocketIO::ConnectTask(mIO)); + aIOLoop->PostTask(MakeAndAddRef(mIO)); } return NS_OK; @@ -396,8 +400,7 @@ RilSocket::SendSocketData(UnixSocketIOBuffer* aBuffer) MOZ_ASSERT(!mIO->IsShutdownOnConsumerThread()); mIO->GetIOLoop()->PostTask( - FROM_HERE, - new SocketIOSendTask(mIO, aBuffer)); + MakeAndAddRef>(mIO, aBuffer)); } // |SocketBase| @@ -414,7 +417,7 @@ RilSocket::Close() // the relationship here so any future calls to |Connect| will create // a new I/O object. mIO->ShutdownOnConsumerThread(); - mIO->GetIOLoop()->PostTask(FROM_HERE, new SocketIOShutdownTask(mIO)); + mIO->GetIOLoop()->PostTask(MakeAndAddRef(mIO)); mIO = nullptr; NotifyDisconnect(); diff --git a/ipc/unixsocket/ConnectionOrientedSocket.cpp b/ipc/unixsocket/ConnectionOrientedSocket.cpp index 983a33767f..abcfd17345 100644 --- a/ipc/unixsocket/ConnectionOrientedSocket.cpp +++ b/ipc/unixsocket/ConnectionOrientedSocket.cpp @@ -86,7 +86,7 @@ ConnectionOrientedSocketIO::Connect() if (NS_FAILED(rv)) { // Tell the consumer thread we've errored GetConsumerThread()->PostTask( - FROM_HERE, new SocketEventTask(this, SocketEventTask::CONNECT_ERROR)); + MakeAndAddRef(this, SocketEventTask::CONNECT_ERROR)); return NS_ERROR_FAILURE; } @@ -153,7 +153,7 @@ ConnectionOrientedSocketIO::OnConnected() MOZ_ASSERT(GetConnectionStatus() == SOCKET_IS_CONNECTED); GetConsumerThread()->PostTask( - FROM_HERE, new SocketEventTask(this, SocketEventTask::CONNECT_SUCCESS)); + MakeAndAddRef(this, SocketEventTask::CONNECT_SUCCESS)); AddWatchers(READ_WATCHER, true); if (HasPendingData()) { @@ -181,7 +181,7 @@ ConnectionOrientedSocketIO::OnError(const char* aFunction, int aErrno) // Tell the consumer thread we've errored GetConsumerThread()->PostTask( - FROM_HERE, new SocketEventTask(this, SocketEventTask::CONNECT_ERROR)); + MakeAndAddRef(this, SocketEventTask::CONNECT_ERROR)); } // diff --git a/ipc/unixsocket/DataSocket.cpp b/ipc/unixsocket/DataSocket.cpp index f093d42bf6..057c59203f 100644 --- a/ipc/unixsocket/DataSocket.cpp +++ b/ipc/unixsocket/DataSocket.cpp @@ -53,8 +53,8 @@ DataSocketIO::ReceiveData(int aFd) nsresult rv = QueryReceiveBuffer(&incoming); if (NS_FAILED(rv)) { /* an error occured */ - GetConsumerThread()->PostTask(FROM_HERE, - new SocketRequestClosingTask(this)); + GetConsumerThread()->PostTask( + MakeAndAddRef(this)); return -1; } @@ -62,14 +62,14 @@ DataSocketIO::ReceiveData(int aFd) if (res < 0) { /* an I/O error occured */ DiscardBuffer(); - GetConsumerThread()->PostTask(FROM_HERE, - new SocketRequestClosingTask(this)); + GetConsumerThread()->PostTask( + MakeAndAddRef(this)); return -1; } else if (!res) { /* EOF or peer shut down sending */ DiscardBuffer(); - GetConsumerThread()->PostTask(FROM_HERE, - new SocketRequestClosingTask(this)); + GetConsumerThread()->PostTask( + MakeAndAddRef(this)); return 0; } @@ -96,8 +96,8 @@ DataSocketIO::SendPendingData(int aFd) ssize_t res = outgoing->Send(aFd); if (res < 0) { /* an I/O error occured */ - GetConsumerThread()->PostTask(FROM_HERE, - new SocketRequestClosingTask(this)); + GetConsumerThread()->PostTask( + MakeAndAddRef(this)); return NS_ERROR_FAILURE; } else if (!res && outgoing->GetSize()) { /* I/O is currently blocked; try again later */ diff --git a/ipc/unixsocket/DataSocket.h b/ipc/unixsocket/DataSocket.h index 7e17412421..4543334613 100644 --- a/ipc/unixsocket/DataSocket.h +++ b/ipc/unixsocket/DataSocket.h @@ -122,7 +122,7 @@ public: MOZ_ASSERT(aData); } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(!SocketIOTask::IsCanceled()); @@ -131,6 +131,8 @@ public: MOZ_ASSERT(!io->IsShutdownOnIOThread()); io->Send(mData); + + return NS_OK; } private: diff --git a/ipc/unixsocket/ListenSocket.cpp b/ipc/unixsocket/ListenSocket.cpp index 871c70404c..a9e2a99a8f 100644 --- a/ipc/unixsocket/ListenSocket.cpp +++ b/ipc/unixsocket/ListenSocket.cpp @@ -175,7 +175,7 @@ ListenSocketIO::OnListening() /* We signal a successful 'connection' to a local address for listening. */ GetConsumerThread()->PostTask( - FROM_HERE, new SocketEventTask(this, SocketEventTask::CONNECT_SUCCESS)); + MakeAndAddRef(this, SocketEventTask::CONNECT_SUCCESS)); } void @@ -197,7 +197,7 @@ ListenSocketIO::FireSocketError() // Tell the consumer thread we've errored GetConsumerThread()->PostTask( - FROM_HERE, new SocketEventTask(this, SocketEventTask::CONNECT_ERROR)); + MakeAndAddRef(this, SocketEventTask::CONNECT_ERROR)); } void @@ -289,13 +289,14 @@ public: MOZ_COUNT_DTOR(ListenTask); } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(!GetIO()->IsConsumerThread()); if (!IsCanceled()) { GetIO()->Listen(mCOSocketIO); } + return NS_OK; } private: @@ -382,7 +383,7 @@ ListenSocket::Listen(ConnectionOrientedSocket* aCOSocket) SetConnectionStatus(SOCKET_LISTENING); mIO->GetIOLoop()->PostTask( - FROM_HERE, new ListenSocketIO::ListenTask(mIO, io)); + MakeAndAddRef(mIO, io)); return NS_OK; } @@ -402,7 +403,7 @@ ListenSocket::Close() // the relationship here so any future calls to listen or connect // will create a new implementation. mIO->ShutdownOnConsumerThread(); - mIO->GetIOLoop()->PostTask(FROM_HERE, new SocketIOShutdownTask(mIO)); + mIO->GetIOLoop()->PostTask(MakeAndAddRef(mIO)); mIO = nullptr; NotifyDisconnect(); diff --git a/ipc/unixsocket/SocketBase.cpp b/ipc/unixsocket/SocketBase.cpp index c7a47bdd2e..b11729652d 100644 --- a/ipc/unixsocket/SocketBase.cpp +++ b/ipc/unixsocket/SocketBase.cpp @@ -326,7 +326,7 @@ SocketEventTask::~SocketEventTask() MOZ_COUNT_DTOR(SocketEventTask); } -void +NS_IMETHODIMP SocketEventTask::Run() { SocketIOBase* io = SocketTask::GetIO(); @@ -336,7 +336,7 @@ SocketEventTask::Run() if (NS_WARN_IF(io->IsShutdownOnConsumerThread())) { // Since we've already explicitly closed and the close // happened before this, this isn't really an error. - return; + return NS_OK; } SocketBase* socketBase = io->GetSocketBase(); @@ -349,6 +349,8 @@ SocketEventTask::Run() } else if (mEvent == DISCONNECT) { socketBase->NotifyDisconnect(); } + + return NS_OK; } // @@ -366,7 +368,7 @@ SocketRequestClosingTask::~SocketRequestClosingTask() MOZ_COUNT_DTOR(SocketRequestClosingTask); } -void +NS_IMETHODIMP SocketRequestClosingTask::Run() { SocketIOBase* io = SocketTask::GetIO(); @@ -376,13 +378,15 @@ SocketRequestClosingTask::Run() if (NS_WARN_IF(io->IsShutdownOnConsumerThread())) { // Since we've already explicitly closed and the close // happened before this, this isn't really an error. - return; + return NS_OK; } SocketBase* socketBase = io->GetSocketBase(); MOZ_ASSERT(socketBase); socketBase->Close(); + + return NS_OK; } // @@ -400,10 +404,11 @@ SocketDeleteInstanceTask::~SocketDeleteInstanceTask() MOZ_COUNT_DTOR(SocketDeleteInstanceTask); } -void +NS_IMETHODIMP SocketDeleteInstanceTask::Run() { mIO.reset(); // delete instance + return NS_OK; } // @@ -421,7 +426,7 @@ SocketIOShutdownTask::~SocketIOShutdownTask() MOZ_COUNT_DTOR(SocketIOShutdownTask); } -void +NS_IMETHODIMP SocketIOShutdownTask::Run() { SocketIOBase* io = SocketIOTask::GetIO(); @@ -435,8 +440,9 @@ SocketIOShutdownTask::Run() // shut down, so we can send a message to the consumer thread to // delete |io| safely knowing that it's not reference any longer. io->ShutdownOnIOThread(); - io->GetConsumerThread()->PostTask(FROM_HERE, - new SocketDeleteInstanceTask(io)); + io->GetConsumerThread()->PostTask( + MakeAndAddRef(io)); + return NS_OK; } } diff --git a/ipc/unixsocket/SocketBase.h b/ipc/unixsocket/SocketBase.h index c023313283..d7a74d1f11 100644 --- a/ipc/unixsocket/SocketBase.h +++ b/ipc/unixsocket/SocketBase.h @@ -453,7 +453,7 @@ private: * the I/O thread to the consumer thread. */ template -class SocketTask : public Task +class SocketTask : public Runnable { public: virtual ~SocketTask() @@ -491,7 +491,7 @@ public: SocketEventTask(SocketIOBase* aIO, SocketEvent aEvent); ~SocketEventTask(); - void Run() override; + NS_IMETHOD Run() override; private: SocketEvent mEvent; @@ -507,19 +507,19 @@ public: SocketRequestClosingTask(SocketIOBase* aIO); ~SocketRequestClosingTask(); - void Run() override; + NS_IMETHOD Run() override; }; /** * |SocketDeleteInstanceTask| deletes an object on the consumer thread. */ -class SocketDeleteInstanceTask final : public Task +class SocketDeleteInstanceTask final : public Runnable { public: SocketDeleteInstanceTask(SocketIOBase* aIO); ~SocketDeleteInstanceTask(); - void Run() override; + NS_IMETHOD Run() override; private: UniquePtr mIO; @@ -533,7 +533,7 @@ private: * supposed to run on the I/O thread. */ template -class SocketIOTask : public CancelableTask +class SocketIOTask : public CancelableRunnable { public: virtual ~SocketIOTask() @@ -544,9 +544,10 @@ public: return mIO; } - void Cancel() override + nsresult Cancel() override { mIO = nullptr; + return NS_OK; } bool IsCanceled() const @@ -575,7 +576,7 @@ public: SocketIOShutdownTask(SocketIOBase* aIO); ~SocketIOShutdownTask(); - void Run() override; + NS_IMETHOD Run() override; }; } diff --git a/ipc/unixsocket/StreamSocket.cpp b/ipc/unixsocket/StreamSocket.cpp index 7cce769aab..04c37e5545 100644 --- a/ipc/unixsocket/StreamSocket.cpp +++ b/ipc/unixsocket/StreamSocket.cpp @@ -45,7 +45,7 @@ public: // Delayed-task handling // - void SetDelayedConnectTask(CancelableTask* aTask); + void SetDelayedConnectTask(CancelableRunnable* aTask); void ClearDelayedConnectTask(); void CancelDelayedConnectTask(); @@ -84,7 +84,7 @@ private: * Task member for delayed connect task. Should only be access on consumer * thread. */ - CancelableTask* mDelayedConnectTask; + CancelableRunnable* mDelayedConnectTask; /** * I/O buffer for received data @@ -146,7 +146,7 @@ StreamSocketIO::GetDataSocket() } void -StreamSocketIO::SetDelayedConnectTask(CancelableTask* aTask) +StreamSocketIO::SetDelayedConnectTask(CancelableRunnable* aTask) { MOZ_ASSERT(IsConsumerThread()); @@ -208,7 +208,7 @@ public: MOZ_COUNT_DTOR(ReceiveTask); } - void Run() override + NS_IMETHOD Run() override { StreamSocketIO* io = SocketTask::GetIO(); @@ -217,13 +217,15 @@ public: if (NS_WARN_IF(io->IsShutdownOnConsumerThread())) { // Since we've already explicitly closed and the close // happened before this, this isn't really an error. - return; + return NS_OK; } StreamSocket* streamSocket = io->GetStreamSocket(); MOZ_ASSERT(streamSocket); streamSocket->ReceiveSocketData(mBuffer); + + return NS_OK; } private: @@ -233,8 +235,8 @@ private: void StreamSocketIO::ConsumeBuffer() { - GetConsumerThread()->PostTask(FROM_HERE, - new ReceiveTask(this, mBuffer.release())); + GetConsumerThread()->PostTask( + MakeAndAddRef(this, mBuffer.release())); } void @@ -302,12 +304,14 @@ public: MOZ_COUNT_DTOR(ReceiveTask); } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(!GetIO()->IsConsumerThread()); MOZ_ASSERT(!IsCanceled()); GetIO()->Connect(); + + return NS_OK; } }; @@ -326,21 +330,23 @@ public: MOZ_COUNT_DTOR(DelayedConnectTask); } - void Run() override + NS_IMETHOD Run() override { MOZ_ASSERT(GetIO()->IsConsumerThread()); if (IsCanceled()) { - return; + return NS_OK; } StreamSocketIO* io = GetIO(); if (io->IsShutdownOnConsumerThread()) { - return; + return NS_OK; } io->ClearDelayedConnectTask(); - io->GetIOLoop()->PostTask(FROM_HERE, new ConnectTask(io)); + io->GetIOLoop()->PostTask(MakeAndAddRef(io)); + + return NS_OK; } }; @@ -381,12 +387,12 @@ StreamSocket::Connect(UnixSocketConnector* aConnector, int aDelayMs, SetConnectionStatus(SOCKET_CONNECTING); if (aDelayMs > 0) { - StreamSocketIO::DelayedConnectTask* connectTask = - new StreamSocketIO::DelayedConnectTask(mIO); + RefPtr connectTask = + MakeAndAddRef(mIO); mIO->SetDelayedConnectTask(connectTask); - MessageLoop::current()->PostDelayedTask(FROM_HERE, connectTask, aDelayMs); + MessageLoop::current()->PostDelayedTask(connectTask.forget(), aDelayMs); } else { - aIOLoop->PostTask(FROM_HERE, new StreamSocketIO::ConnectTask(mIO)); + aIOLoop->PostTask(MakeAndAddRef(mIO)); } return NS_OK; @@ -430,8 +436,8 @@ StreamSocket::SendSocketData(UnixSocketIOBuffer* aBuffer) MOZ_ASSERT(!mIO->IsShutdownOnConsumerThread()); mIO->GetIOLoop()->PostTask( - FROM_HERE, - new SocketIOSendTask(mIO, aBuffer)); + MakeAndAddRef>( + mIO, aBuffer)); } // |SocketBase| @@ -448,7 +454,7 @@ StreamSocket::Close() // the relationship here so any future calls to |Connect| will create // a new I/O object. mIO->ShutdownOnConsumerThread(); - mIO->GetIOLoop()->PostTask(FROM_HERE, new SocketIOShutdownTask(mIO)); + mIO->GetIOLoop()->PostTask(MakeAndAddRef(mIO)); mIO = nullptr; NotifyDisconnect(); diff --git a/layout/build/nsLayoutModule.cpp b/layout/build/nsLayoutModule.cpp index 92b3792943..7940df1f27 100644 --- a/layout/build/nsLayoutModule.cpp +++ b/layout/build/nsLayoutModule.cpp @@ -235,8 +235,6 @@ static void Shutdown(); #include "AudioChannelService.h" #include "mozilla/net/WebSocketEventService.h" -#include "mozilla/dom/DataStoreService.h" - #include "mozilla/dom/power/PowerManagerService.h" #include "mozilla/dom/alarm/AlarmHalService.h" #include "mozilla/dom/time/TimeService.h" @@ -637,17 +635,12 @@ NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(Geolocation, Init) #define NS_WEBSOCKETEVENT_SERVICE_CID \ { 0x31689828, 0xda66, 0x49a6, { 0x87, 0x0c, 0xdf, 0x62, 0xb8, 0x3f, 0xe7, 0x89 }} -#define NS_DATASTORE_SERVICE_CID \ - { 0x0d4285fe, 0xf1b3, 0x49fa, { 0xbc, 0x51, 0xa4, 0xa8, 0x3f, 0x0a, 0xaf, 0x85 }} - NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsGeolocationService, nsGeolocationService::GetGeolocationService) NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(AudioChannelService, AudioChannelService::GetOrCreate) NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(WebSocketEventService, WebSocketEventService::GetOrCreate) -NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(DataStoreService, DataStoreService::GetOrCreate) - #ifdef MOZ_WEBSPEECH_TEST_BACKEND NS_GENERIC_FACTORY_CONSTRUCTOR(FakeSpeechRecognitionService) #endif @@ -801,7 +794,6 @@ NS_DEFINE_NAMED_CID(NS_GEOLOCATION_SERVICE_CID); NS_DEFINE_NAMED_CID(NS_GEOLOCATION_CID); NS_DEFINE_NAMED_CID(NS_AUDIOCHANNEL_SERVICE_CID); NS_DEFINE_NAMED_CID(NS_WEBSOCKETEVENT_SERVICE_CID); -NS_DEFINE_NAMED_CID(NS_DATASTORE_SERVICE_CID); NS_DEFINE_NAMED_CID(NS_FOCUSMANAGER_CID); NS_DEFINE_NAMED_CID(NS_CONTENTSECURITYMANAGER_CID); NS_DEFINE_NAMED_CID(CSPSERVICE_CID); @@ -1109,7 +1101,6 @@ static const mozilla::Module::CIDEntry kLayoutCIDs[] = { { &kNS_GEOLOCATION_CID, false, nullptr, GeolocationConstructor }, { &kNS_AUDIOCHANNEL_SERVICE_CID, false, nullptr, AudioChannelServiceConstructor }, { &kNS_WEBSOCKETEVENT_SERVICE_CID, false, nullptr, WebSocketEventServiceConstructor }, - { &kNS_DATASTORE_SERVICE_CID, false, nullptr, DataStoreServiceConstructor }, { &kNS_FOCUSMANAGER_CID, false, nullptr, CreateFocusManager }, #ifdef MOZ_WEBSPEECH_TEST_BACKEND { &kNS_FAKE_SPEECH_RECOGNITION_SERVICE_CID, false, nullptr, FakeSpeechRecognitionServiceConstructor }, @@ -1277,7 +1268,6 @@ static const mozilla::Module::ContractIDEntry kLayoutContracts[] = { { "@mozilla.org/geolocation;1", &kNS_GEOLOCATION_CID }, { "@mozilla.org/audiochannel/service;1", &kNS_AUDIOCHANNEL_SERVICE_CID }, { "@mozilla.org/websocketevent/service;1", &kNS_WEBSOCKETEVENT_SERVICE_CID }, - { "@mozilla.org/datastore-service;1", &kNS_DATASTORE_SERVICE_CID }, { "@mozilla.org/focus-manager;1", &kNS_FOCUSMANAGER_CID }, #ifdef MOZ_WEBSPEECH_TEST_BACKEND { NS_SPEECH_RECOGNITION_SERVICE_CONTRACTID_PREFIX "fake", &kNS_FAKE_SPEECH_RECOGNITION_SERVICE_CID }, diff --git a/layout/build/nsLayoutStatics.cpp b/layout/build/nsLayoutStatics.cpp index 2cc56d54b1..39de78771e 100644 --- a/layout/build/nsLayoutStatics.cpp +++ b/layout/build/nsLayoutStatics.cpp @@ -71,7 +71,6 @@ #include "LayerAnimationInfo.h" #include "AudioChannelService.h" -#include "mozilla/dom/DataStoreService.h" #include "mozilla/dom/PromiseDebugging.h" #include "mozilla/dom/WebCryptoThreadPool.h" @@ -437,8 +436,6 @@ nsLayoutStatics::Shutdown() nsHyphenationManager::Shutdown(); nsDOMMutationObserver::Shutdown(); - DataStoreService::Shutdown(); - ContentParent::ShutDown(); nsRefreshDriver::Shutdown(); diff --git a/modules/libpref/init/all.js b/modules/libpref/init/all.js index 6bfe0e4381..a53667ab7d 100644 --- a/modules/libpref/init/all.js +++ b/modules/libpref/init/all.js @@ -5245,9 +5245,6 @@ pref("dom.forms.inputmode", true); // InputMethods for soft keyboards in B2G pref("dom.mozInputMethod.enabled", false); -// DataStore is disabled by default -pref("dom.datastore.enabled", false); - // Telephony API #ifdef MOZ_B2G_RIL pref("dom.telephony.enabled", true); diff --git a/netwerk/protocol/rtsp/RtspChannelChild.cpp b/netwerk/protocol/rtsp/RtspChannelChild.cpp index 235c2f6ef4..74f832e0aa 100644 --- a/netwerk/protocol/rtsp/RtspChannelChild.cpp +++ b/netwerk/protocol/rtsp/RtspChannelChild.cpp @@ -82,7 +82,7 @@ RtspChannelChild::GetContentType(nsACString& aContentType) return NS_OK; } -class CallListenerOnStartRequestEvent : public nsRunnable +class CallListenerOnStartRequestEvent : public Runnable { public: CallListenerOnStartRequestEvent(nsIStreamListener *aListener, @@ -185,7 +185,7 @@ RtspChannelChild::OnDataAvailable(nsIRequest *aRequest, //----------------------------------------------------------------------------- // nsBaseChannel::nsIChannel::nsIRequest //----------------------------------------------------------------------------- -class CallListenerOnStopRequestEvent : public nsRunnable +class CallListenerOnStopRequestEvent : public Runnable { public: CallListenerOnStopRequestEvent(nsIStreamListener *aListener, diff --git a/netwerk/protocol/rtsp/controller/RtspController.cpp b/netwerk/protocol/rtsp/controller/RtspController.cpp index 5afccf59e0..6079ce8d86 100644 --- a/netwerk/protocol/rtsp/controller/RtspController.cpp +++ b/netwerk/protocol/rtsp/controller/RtspController.cpp @@ -194,7 +194,7 @@ RtspController::AsyncOpen(nsIStreamingProtocolListener *aListener) //----------------------------------------------------------------------------- // nsIStreamingProtocolListener //----------------------------------------------------------------------------- -class SendMediaDataTask : public nsRunnable +class SendMediaDataTask : public Runnable { public: SendMediaDataTask(nsIStreamingProtocolListener *listener, @@ -244,7 +244,7 @@ RtspController::OnMediaDataAvailable(uint8_t index, return NS_ERROR_NOT_AVAILABLE; } -class SendOnConnectedTask : public nsRunnable +class SendOnConnectedTask : public Runnable { public: SendOnConnectedTask(nsIStreamingProtocolListener *listener, @@ -283,7 +283,7 @@ RtspController::OnConnected(uint8_t index, return NS_ERROR_NOT_AVAILABLE; } -class SendOnDisconnectedTask : public nsRunnable +class SendOnDisconnectedTask : public Runnable { public: SendOnDisconnectedTask(nsIStreamingProtocolListener *listener, diff --git a/netwerk/protocol/rtsp/controller/RtspControllerChild.cpp b/netwerk/protocol/rtsp/controller/RtspControllerChild.cpp index 5dd847c2ff..2d4a668165 100644 --- a/netwerk/protocol/rtsp/controller/RtspControllerChild.cpp +++ b/netwerk/protocol/rtsp/controller/RtspControllerChild.cpp @@ -254,7 +254,7 @@ enum IPCEvent SendPlaybackEndedEvent }; -class SendIPCEvent : public nsRunnable +class SendIPCEvent : public Runnable { public: SendIPCEvent(RtspControllerChild *aController, IPCEvent aEvent) diff --git a/testing/mochitest/manifest.webapp b/testing/mochitest/manifest.webapp index c886163de2..4d4c5e41cc 100644 --- a/testing/mochitest/manifest.webapp +++ b/testing/mochitest/manifest.webapp @@ -36,9 +36,5 @@ "description": "Mochitests" } }, - "datastores-access" : { - "foo" : { "readonly": false }, - "bar" : { "readonly": false } - }, "default_locale": "en-US" } diff --git a/testing/web-platform/tests/service-workers/service-worker/fetch-event-redirect.https.html b/testing/web-platform/tests/service-workers/service-worker/fetch-event-redirect.https.html index 556d04413f..23bb85612c 100644 --- a/testing/web-platform/tests/service-workers/service-worker/fetch-event-redirect.https.html +++ b/testing/web-platform/tests/service-workers/service-worker/fetch-event-redirect.https.html @@ -65,6 +65,7 @@ function redirect_fetch_test(t, test) { url: url, request_init: test.request_init, redirect_dest: test.redirect_dest, + expected_type: test.expected_type, }, '*', [channel.port2]); }); @@ -225,12 +226,10 @@ async_test(function(t) { redirect: 'manual', mode: 'no-cors' }, - // should reject because only navigations can be intercepted with - // opaqueredirect responses - should_reject: true + should_reject: false }); }, 'Non-navigation, manual redirect, no-cors mode Request redirected to ' + - 'no-cors without credentials should fail opaqueredirect interception'); + 'no-cors without credentials should succeed interception'); async_test(function(t) { redirect_fetch_test(t, { @@ -242,12 +241,10 @@ async_test(function(t) { redirect: 'manual', mode: 'no-cors' }, - // should reject because only navigations can be intercepted with - // opaqueredirect responses - should_reject: true + should_reject: false }); }, 'Non-navigation, manual redirect, no-cors mode Request redirected to ' + - 'cors without credentials should fail opaqueredirect interception'); + 'cors without credentials should succeed interception'); async_test(function(t) { redirect_fetch_test(t, { @@ -378,12 +375,10 @@ async_test(function(t) { redirect: 'manual', mode: 'no-cors' }, - // should reject because only navigations can be intercepted with - // opaqueredirect responses - should_reject: true + should_reject: false }); }, 'Non-navigation, manual redirect, no-cors mode Request redirected to ' + - 'no-cors with credentials should fail opaqueredirect interception'); + 'no-cors with credentials should succeed interception'); async_test(function(t) { redirect_fetch_test(t, { @@ -395,12 +390,10 @@ async_test(function(t) { redirect: 'manual', mode: 'no-cors' }, - // should reject because only navigations can be intercepted with - // opaqueredirect responses - should_reject: true + should_reject: false }); }, 'Non-navigation, manual redirect, no-cors mode Request redirected to ' + - 'cors with credentials should fail opaqueredirect interception'); + 'cors with credentials should succeed interception'); async_test(function(t) { redirect_fetch_test(t, { diff --git a/testing/web-platform/tests/service-workers/service-worker/resources/fetch-event-redirect-iframe.html b/testing/web-platform/tests/service-workers/service-worker/resources/fetch-event-redirect-iframe.html index 499e967756..fbe3bda847 100644 --- a/testing/web-platform/tests/service-workers/service-worker/resources/fetch-event-redirect-iframe.html +++ b/testing/web-platform/tests/service-workers/service-worker/resources/fetch-event-redirect-iframe.html @@ -4,10 +4,11 @@ window.addEventListener('message', function(evt) { var data = evt.data; fetch(new Request(data.url, data.request_init)).then(function(response) { if (data.request_init.mode === 'no-cors' && data.redirect_dest != 'same-origin') { - if (response.type === 'opaque') { + if (response.type === data.expected_type && + (response.type === 'opaque' || response.type === 'opaqueredirect')) { return {result: 'success', detail: ''}; } else { - return {result: 'failure', detail: 'expected opaque response'}; + return {result: 'failure', detail: 'expected ' + data.expected_type + ' response'}; } } return response.json(); diff --git a/testing/web-platform/tests/service-workers/service-worker/resources/update-recovery-worker.py b/testing/web-platform/tests/service-workers/service-worker/resources/update-recovery-worker.py new file mode 100644 index 0000000000..8aaa5ca934 --- /dev/null +++ b/testing/web-platform/tests/service-workers/service-worker/resources/update-recovery-worker.py @@ -0,0 +1,25 @@ +def main(request, response): + # Set mode to 'init' for initial fetch. + mode = 'init' + if 'update-recovery-mode' in request.cookies: + mode = request.cookies['update-recovery-mode'].value + + # no-cache itself to ensure the user agent finds a new version for each update. + headers = [('Cache-Control', 'no-cache, must-revalidate'), + ('Pragma', 'no-cache')] + + extra_body = '' + + if mode == 'init': + # Install a bad service worker that will break the controlled + # document navigation. + response.set_cookie('update-recovery-mode', 'bad') + extra_body = "addEventListener('fetch', function(e) { e.respondWith(Promise.reject()); });" + elif mode == 'bad': + # When the update tries to pull the script again, update to + # a worker service worker that does not break document + # navigation. Serve the same script from then on. + response.delete_cookie('update-recovery-mode') + + headers.append(('Content-Type', 'application/javascript')) + return headers, '%s' % (extra_body) diff --git a/testing/web-platform/tests/service-workers/service-worker/update-recovery.https.html b/testing/web-platform/tests/service-workers/service-worker/update-recovery.https.html new file mode 100644 index 0000000000..3b3d955b14 --- /dev/null +++ b/testing/web-platform/tests/service-workers/service-worker/update-recovery.https.html @@ -0,0 +1,71 @@ + +Service Worker: recovery by navigation update + + + + + diff --git a/toolkit/identity/IdentityCryptoService.cpp b/toolkit/identity/IdentityCryptoService.cpp index 71616a71a1..e5cc60e72a 100644 --- a/toolkit/identity/IdentityCryptoService.cpp +++ b/toolkit/identity/IdentityCryptoService.cpp @@ -226,11 +226,9 @@ NS_IMETHODIMP IdentityCryptoService::Base64UrlEncode(const nsACString & utf8Input, nsACString & result) { - dom::Base64URLEncodeOptions options; - options.mPad = true; return Base64URLEncode(utf8Input.Length(), - reinterpret_cast(utf8Input.BeginReading()), options, - result); + reinterpret_cast(utf8Input.BeginReading()), + Base64URLEncodePaddingPolicy::Include, result); } KeyPair::KeyPair(SECKEYPrivateKey * privateKey, SECKEYPublicKey * publicKey, @@ -526,9 +524,9 @@ SignRunnable::Run() mRv = MapSECStatus(PK11_Sign(mPrivateKey, &sig, &hashItem)); } if (NS_SUCCEEDED(mRv)) { - dom::Base64URLEncodeOptions encodeOptions; - encodeOptions.mPad = true; - mRv = Base64URLEncode(sig.len, sig.data, encodeOptions, mSignature); + mRv = Base64URLEncode(sig.len, sig.data, + Base64URLEncodePaddingPolicy::Include, + mSignature); } SECITEM_FreeItem(&sig, false); } diff --git a/toolkit/xre/EventTracer.cpp b/toolkit/xre/EventTracer.cpp index 71a5424005..b6e28971ec 100644 --- a/toolkit/xre/EventTracer.cpp +++ b/toolkit/xre/EventTracer.cpp @@ -86,7 +86,7 @@ struct TracerStartClosure { }; #ifdef MOZ_WIDGET_GONK -class EventLoopLagDispatcher : public nsRunnable +class EventLoopLagDispatcher : public Runnable { public: explicit EventLoopLagDispatcher(int aLag) diff --git a/widget/gonk/GonkPermission.cpp b/widget/gonk/GonkPermission.cpp index 7dab1f095f..056670ab3c 100644 --- a/widget/gonk/GonkPermission.cpp +++ b/widget/gonk/GonkPermission.cpp @@ -39,7 +39,7 @@ using namespace mozilla; // Checking permissions needs to happen on the main thread, but the // binder callback is called on a special binder thread, so we use // this runnable for that. -class GonkPermissionChecker : public nsRunnable { +class GonkPermissionChecker : public Runnable { int32_t mPid; bool mCanUseCamera; diff --git a/widget/gonk/HwcComposer2D.cpp b/widget/gonk/HwcComposer2D.cpp index eaf690245b..ae2eee5ec4 100644 --- a/widget/gonk/HwcComposer2D.cpp +++ b/widget/gonk/HwcComposer2D.cpp @@ -206,7 +206,7 @@ HwcComposer2D::Invalidate() } namespace { -class HotplugEvent : public nsRunnable { +class HotplugEvent : public Runnable { public: HotplugEvent(GonkDisplay::DisplayType aType, bool aConnected) : mType(aType) diff --git a/widget/gonk/WidgetTraceEvent.cpp b/widget/gonk/WidgetTraceEvent.cpp index ac14cfa0af..558d9313e3 100644 --- a/widget/gonk/WidgetTraceEvent.cpp +++ b/widget/gonk/WidgetTraceEvent.cpp @@ -13,7 +13,7 @@ using mozilla::Mutex; using mozilla::MutexAutoLock; namespace mozilla { - class TracerRunnable : public nsRunnable { + class TracerRunnable : public Runnable { public: TracerRunnable() { mTracerLock = new Mutex("TracerRunnable"); diff --git a/widget/gonk/nativewindow/FakeSurfaceComposer.cpp b/widget/gonk/nativewindow/FakeSurfaceComposer.cpp index fe4d2581d9..e8b6521b50 100644 --- a/widget/gonk/nativewindow/FakeSurfaceComposer.cpp +++ b/widget/gonk/nativewindow/FakeSurfaceComposer.cpp @@ -101,7 +101,7 @@ sp FakeSurfaceComposer::createGraphicBufferAlloc() return gba; } -class DestroyDisplayRunnable : public nsRunnable { +class DestroyDisplayRunnable : public Runnable { public: DestroyDisplayRunnable(FakeSurfaceComposer* aComposer, ssize_t aIndex) : mComposer(aComposer), mIndex(aIndex) { } @@ -443,14 +443,15 @@ FakeSurfaceComposer::captureScreen(const sp& display return result; } -class RunnableCallTask : public Task { +class RunnableCallTask final : public Runnable +{ public: explicit RunnableCallTask(nsIRunnable* aRunnable) : mRunnable(aRunnable) {} - void Run() override + NS_IMETHOD Run() override { - mRunnable->Run(); + return mRunnable->Run(); } protected: nsCOMPtr mRunnable; @@ -525,7 +526,7 @@ FakeSurfaceComposer::captureScreenImp(const sp& producer }); mozilla::layers::CompositorBridgeParent::CompositorLoop()->PostTask( - FROM_HERE, new RunnableCallTask(runnable)); + MakeAndAddRef(runnable)); } #if ANDROID_VERSION >= 21 diff --git a/widget/gonk/nativewindow/GonkBufferQueueJB.cpp b/widget/gonk/nativewindow/GonkBufferQueueJB.cpp index 69d498f3f4..8cfb3d05be 100644 --- a/widget/gonk/nativewindow/GonkBufferQueueJB.cpp +++ b/widget/gonk/nativewindow/GonkBufferQueueJB.cpp @@ -408,9 +408,10 @@ status_t GonkBufferQueue::dequeueBuffer(int *outBuf, sp* outFence, if (mSlots[buf].mTextureClient) { mSlots[buf].mTextureClient->ClearRecycleCallback(); // release TextureClient in ImageBridge thread - TextureClientReleaseTask* task = new TextureClientReleaseTask(mSlots[buf].mTextureClient); + RefPtr task = + MakeAndAddRef(mSlots[buf].mTextureClient); mSlots[buf].mTextureClient = NULL; - ImageBridgeChild::GetSingleton()->GetMessageLoop()->PostTask(FROM_HERE, task); + ImageBridgeChild::GetSingleton()->GetMessageLoop()->PostTask(task.forget()); } returnFlags |= IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION; } @@ -782,9 +783,10 @@ void GonkBufferQueue::freeAllBuffersLocked() if (mSlots[i].mTextureClient) { mSlots[i].mTextureClient->ClearRecycleCallback(); // release TextureClient in ImageBridge thread - TextureClientReleaseTask* task = new TextureClientReleaseTask(mSlots[i].mTextureClient); + RefPtr task = + MakeAndAddRef(mSlots[i].mTextureClient); mSlots[i].mTextureClient = NULL; - ImageBridgeChild::GetSingleton()->GetMessageLoop()->PostTask(FROM_HERE, task); + ImageBridgeChild::GetSingleton()->GetMessageLoop()->PostTask(task.forget()); } if (mSlots[i].mBufferState == BufferSlot::ACQUIRED) { mSlots[i].mNeedsCleanupOnRelease = true; diff --git a/widget/gonk/nativewindow/GonkBufferQueueKK.cpp b/widget/gonk/nativewindow/GonkBufferQueueKK.cpp index 4f14a1e54e..db46d12cfc 100644 --- a/widget/gonk/nativewindow/GonkBufferQueueKK.cpp +++ b/widget/gonk/nativewindow/GonkBufferQueueKK.cpp @@ -423,9 +423,10 @@ status_t GonkBufferQueue::dequeueBuffer(int *outBuf, sp* outFence, bool a if (mSlots[buf].mTextureClient) { mSlots[buf].mTextureClient->ClearRecycleCallback(); // release TextureClient in ImageBridge thread - TextureClientReleaseTask* task = new TextureClientReleaseTask(mSlots[buf].mTextureClient); + RefPtr task = + MakeAndAddRef(mSlots[buf].mTextureClient); mSlots[buf].mTextureClient = NULL; - ImageBridgeChild::GetSingleton()->GetMessageLoop()->PostTask(FROM_HERE, task); + ImageBridgeChild::GetSingleton()->GetMessageLoop()->PostTask(task.forget()); } returnFlags |= IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION; } @@ -869,9 +870,10 @@ void GonkBufferQueue::freeAllBuffersLocked() if (mSlots[i].mTextureClient) { mSlots[i].mTextureClient->ClearRecycleCallback(); // release TextureClient in ImageBridge thread - TextureClientReleaseTask* task = new TextureClientReleaseTask(mSlots[i].mTextureClient); + RefPtr task = + MakeAndAddRef(mSlots[i].mTextureClient); mSlots[i].mTextureClient = NULL; - ImageBridgeChild::GetSingleton()->GetMessageLoop()->PostTask(FROM_HERE, task); + ImageBridgeChild::GetSingleton()->GetMessageLoop()->PostTask(task.forget()); } if (mSlots[i].mBufferState == BufferSlot::ACQUIRED) { mSlots[i].mNeedsCleanupOnRelease = true; diff --git a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueCore.cpp b/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueCore.cpp index 3b539b9c43..9e8e337f69 100644 --- a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueCore.cpp +++ b/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueCore.cpp @@ -190,9 +190,10 @@ void GonkBufferQueueCore::freeBufferLocked(int slot) { if (mSlots[slot].mTextureClient) { mSlots[slot].mTextureClient->ClearRecycleCallback(); // release TextureClient in ImageBridge thread - TextureClientReleaseTask* task = new TextureClientReleaseTask(mSlots[slot].mTextureClient); + RefPtr task = + MakeAndAddRef(mSlots[slot].mTextureClient); mSlots[slot].mTextureClient = NULL; - ImageBridgeChild::GetSingleton()->GetMessageLoop()->PostTask(FROM_HERE, task); + ImageBridgeChild::GetSingleton()->GetMessageLoop()->PostTask(task.forget()); } mSlots[slot].mGraphicBuffer.clear(); if (mSlots[slot].mBufferState == GonkBufferSlot::ACQUIRED) { diff --git a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueProducer.cpp b/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueProducer.cpp index d8e6c0a3a9..bad20743ed 100644 --- a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueProducer.cpp +++ b/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueProducer.cpp @@ -322,9 +322,10 @@ status_t GonkBufferQueueProducer::dequeueBuffer(int *outSlot, if (mSlots[found].mTextureClient) { mSlots[found].mTextureClient->ClearRecycleCallback(); // release TextureClient in ImageBridge thread - TextureClientReleaseTask* task = new TextureClientReleaseTask(mSlots[found].mTextureClient); + RefPtr task = + MakeAndAddRef(mSlots[found].mTextureClient); mSlots[found].mTextureClient = NULL; - ImageBridgeChild::GetSingleton()->GetMessageLoop()->PostTask(FROM_HERE, task); + ImageBridgeChild::GetSingleton()->GetMessageLoop()->PostTask(task.forget()); } returnFlags |= BUFFER_NEEDS_REALLOCATION; diff --git a/widget/gonk/nativewindow/GonkNativeWindowICS.cpp b/widget/gonk/nativewindow/GonkNativeWindowICS.cpp index f5be860b86..a4adbc2686 100644 --- a/widget/gonk/nativewindow/GonkNativeWindowICS.cpp +++ b/widget/gonk/nativewindow/GonkNativeWindowICS.cpp @@ -72,9 +72,10 @@ void GonkNativeWindow::freeAllBuffersLocked() if (mSlots[i].mTextureClient) { mSlots[i].mTextureClient->ClearRecycleCallback(); // release TextureClient in ImageBridge thread - TextureClientReleaseTask* task = new TextureClientReleaseTask(mSlots[i].mTextureClient); + RefPtr task = + MakeAndAddRef(mSlots[i].mTextureClient); mSlots[i].mTextureClient = NULL; - ImageBridgeChild::GetSingleton()->GetMessageLoop()->PostTask(FROM_HERE, task); + ImageBridgeChild::GetSingleton()->GetMessageLoop()->PostTask(task.forget()); } mSlots[i].mGraphicBuffer = NULL; mSlots[i].mBufferState = BufferSlot::FREE; @@ -94,9 +95,10 @@ void GonkNativeWindow::clearRenderingStateBuffersLocked() if (mSlots[i].mTextureClient) { mSlots[i].mTextureClient->ClearRecycleCallback(); // release TextureClient in ImageBridge thread - TextureClientReleaseTask* task = new TextureClientReleaseTask(mSlots[i].mTextureClient); + RefPtr task = + MakeAndAddRef(mSlots[i].mTextureClient); mSlots[i].mTextureClient = NULL; - ImageBridgeChild::GetSingleton()->GetMessageLoop()->PostTask(FROM_HERE, task); + ImageBridgeChild::GetSingleton()->GetMessageLoop()->PostTask(task.forget()); } mSlots[i].mGraphicBuffer = NULL; mSlots[i].mBufferState = BufferSlot::FREE; @@ -310,9 +312,10 @@ status_t GonkNativeWindow::dequeueBuffer(int *outBuf, uint32_t w, uint32_t h, if (mSlots[buf].mTextureClient) { mSlots[buf].mTextureClient->ClearRecycleCallback(); // release TextureClient in ImageBridge thread - TextureClientReleaseTask* task = new TextureClientReleaseTask(mSlots[buf].mTextureClient); + RefPtr task = + MakeAndAddRef(mSlots[buf].mTextureClient); mSlots[buf].mTextureClient = NULL; - ImageBridgeChild::GetSingleton()->GetMessageLoop()->PostTask(FROM_HERE, task); + ImageBridgeChild::GetSingleton()->GetMessageLoop()->PostTask(task.forget()); } alloc = true; } diff --git a/widget/gonk/nsAppShell.cpp b/widget/gonk/nsAppShell.cpp index 6f3efcf8ca..5137a1e52d 100644 --- a/widget/gonk/nsAppShell.cpp +++ b/widget/gonk/nsAppShell.cpp @@ -354,7 +354,7 @@ KeyEventDispatcher::DispatchKeyUpEvent() DispatchKeyEventInternal(eKeyUp); } -class SwitchEventRunnable : public nsRunnable { +class SwitchEventRunnable : public mozilla::Runnable { public: SwitchEventRunnable(hal::SwitchEvent& aEvent) : mEvent(aEvent) {} diff --git a/widget/gonk/nsScreenManagerGonk.cpp b/widget/gonk/nsScreenManagerGonk.cpp index 051cb12437..1cb9cb570c 100644 --- a/widget/gonk/nsScreenManagerGonk.cpp +++ b/widget/gonk/nsScreenManagerGonk.cpp @@ -56,7 +56,7 @@ using namespace mozilla::dom; namespace { -class ScreenOnOffEvent : public nsRunnable { +class ScreenOnOffEvent : public mozilla::Runnable { public: ScreenOnOffEvent(bool on) : mIsOn(on) @@ -162,7 +162,6 @@ nsScreenGonk::~nsScreenGonk() // Release GLContext on compositor thread if (mGLContext) { CompositorBridgeParent::CompositorLoop()->PostTask( - FROM_HERE, NewRunnableFunction(&ReleaseGLContextSync, mGLContext.forget().take())); mGLContext = nullptr; @@ -669,7 +668,6 @@ nsScreenGonk::EnableMirroring() nsMainThreadPtrHandle primary = nsMainThreadPtrHandle(new nsMainThreadPtrHolder(primaryScreen, false)); CompositorBridgeParent::CompositorLoop()->PostTask( - FROM_HERE, NewRunnableFunction(&UpdateMirroringWidgetSync, primary, window.forget().take())); @@ -695,7 +693,6 @@ nsScreenGonk::DisableMirroring() nsMainThreadPtrHandle primary = nsMainThreadPtrHandle(new nsMainThreadPtrHolder(primaryScreen, false)); CompositorBridgeParent::CompositorLoop()->PostTask( - FROM_HERE, NewRunnableFunction(&UpdateMirroringWidgetSync, primary, nullptr)); @@ -974,7 +971,7 @@ private: NS_IMPL_ISUPPORTS(DisplayInfo, nsIDisplayInfo, nsISupports) -class NotifyTask : public nsRunnable { +class NotifyTask : public mozilla::Runnable { public: NotifyTask(uint32_t aId, bool aConnected) : mDisplayInfo(new DisplayInfo(aId, aConnected)) diff --git a/widget/gonk/nsScreenManagerGonk.h b/widget/gonk/nsScreenManagerGonk.h index ba3b10f032..33ef5edb89 100644 --- a/widget/gonk/nsScreenManagerGonk.h +++ b/widget/gonk/nsScreenManagerGonk.h @@ -31,7 +31,6 @@ #include -class nsRunnable; class nsWindow; namespace android { @@ -40,6 +39,7 @@ namespace android { }; namespace mozilla { + class Runnable; namespace gl { class GLContext; } @@ -216,8 +216,8 @@ protected: bool mInitialized; nsTArray> mScreens; - RefPtr mScreenOnEvent; - RefPtr mScreenOffEvent; + RefPtr mScreenOnEvent; + RefPtr mScreenOffEvent; #if ANDROID_VERSION >= 19 bool mDisplayEnabled; diff --git a/widget/gonk/nsWindow.cpp b/widget/gonk/nsWindow.cpp index d76607a5de..c2b43fc0bc 100644 --- a/widget/gonk/nsWindow.cpp +++ b/widget/gonk/nsWindow.cpp @@ -161,7 +161,7 @@ nsWindow::DispatchTouchInput(MultiTouchInput& aInput) gFocusedWindow->DispatchTouchInputViaAPZ(aInput); } -class DispatchTouchInputOnMainThread : public nsRunnable +class DispatchTouchInputOnMainThread : public mozilla::Runnable { public: DispatchTouchInputOnMainThread(const MultiTouchInput& aInput, @@ -235,18 +235,18 @@ nsWindow::DispatchTouchEventForAPZ(const MultiTouchInput& aInput, ProcessUntransformedAPZEvent(&event, aGuid, aInputBlockId, aApzResponse); } -class DispatchTouchInputOnControllerThread : public Task +class DispatchTouchInputOnControllerThread : public Runnable { public: DispatchTouchInputOnControllerThread(const MultiTouchInput& aInput) - : Task() - , mInput(aInput) + : mInput(aInput) {} - virtual void Run() override { + NS_IMETHOD Run() override { if (gFocusedWindow) { gFocusedWindow->DispatchTouchInputViaAPZ(mInput); } + return NS_OK; } private: @@ -325,7 +325,8 @@ nsWindow::SynthesizeNativeTouchPoint(uint32_t aPointerId, // the function performs so this is fine. Also we can't pass |this| to the // task because nsWindow refcounting is not threadsafe. Instead we just use // the gFocusedWindow static ptr instead the task. - APZThreadUtils::RunOnControllerThread(new DispatchTouchInputOnControllerThread(inputToDispatch)); + APZThreadUtils::RunOnControllerThread( + MakeAndAddRef(inputToDispatch)); return NS_OK; } diff --git a/xpcom/build/Omnijar.cpp b/xpcom/build/Omnijar.cpp index f98c393d32..e1a8a1e5b6 100644 --- a/xpcom/build/Omnijar.cpp +++ b/xpcom/build/Omnijar.cpp @@ -14,11 +14,11 @@ namespace mozilla { -nsIFile* Omnijar::sPath[2] = { nullptr, nullptr }; -nsZipArchive* Omnijar::sReader[2] = { nullptr, nullptr }; +StaticRefPtr Omnijar::sPath[2]; +StaticRefPtr Omnijar::sReader[2]; +StaticRefPtr Omnijar::sOuterReader[2]; bool Omnijar::sInitialized = false; -static bool sIsUnified = false; -static bool sIsNested[2] = { false, false }; +bool Omnijar::sIsUnified = false; static const char* sProp[2] = { NS_GRE_DIR, NS_XPCOM_CURRENT_PROCESS_DIR @@ -31,10 +31,13 @@ Omnijar::CleanUpOne(Type aType) { if (sReader[aType]) { sReader[aType]->CloseArchive(); - NS_IF_RELEASE(sReader[aType]); + sReader[aType] = nullptr; } - sReader[aType] = nullptr; - NS_IF_RELEASE(sPath[aType]); + if (sOuterReader[aType]) { + sOuterReader[aType]->CloseArchive(); + sOuterReader[aType] = nullptr; + } + sPath[aType] = nullptr; } void @@ -85,21 +88,21 @@ Omnijar::InitOne(nsIFile* aPath, Type aType) return; } + RefPtr outerReader; RefPtr handle; if (NS_SUCCEEDED(nsZipHandle::Init(zipReader, NS_STRINGIFY(OMNIJAR_NAME), getter_AddRefs(handle)))) { + outerReader = zipReader; zipReader = new nsZipArchive(); if (NS_FAILED(zipReader->OpenArchive(handle))) { return; } - sIsNested[aType] = true; } CleanUpOne(aType); sReader[aType] = zipReader; - NS_IF_ADDREF(sReader[aType]); + sOuterReader[aType] = outerReader; sPath[aType] = file; - NS_IF_ADDREF(sPath[aType]); } void @@ -126,16 +129,16 @@ Omnijar::GetReader(nsIFile* aPath) bool equals; nsresult rv; - if (sPath[GRE] && !sIsNested[GRE]) { + if (sPath[GRE]) { rv = sPath[GRE]->Equals(aPath, &equals); if (NS_SUCCEEDED(rv) && equals) { - return GetReader(GRE); + return IsNested(GRE) ? GetOuterReader(GRE) : GetReader(GRE); } } - if (sPath[APP] && !sIsNested[APP]) { + if (sPath[APP]) { rv = sPath[APP]->Equals(aPath, &equals); if (NS_SUCCEEDED(rv) && equals) { - return GetReader(APP); + return IsNested(APP) ? GetOuterReader(APP) : GetReader(APP); } } return nullptr; @@ -161,12 +164,12 @@ Omnijar::GetURIString(Type aType, nsACString& aResult) } aResult = "jar:"; - if (sIsNested[aType]) { + if (IsNested(aType)) { aResult += "jar:"; } aResult += omniJarSpec; aResult += "!"; - if (sIsNested[aType]) { + if (IsNested(aType)) { aResult += "/" NS_STRINGIFY(OMNIJAR_NAME) "!"; } } else { diff --git a/xpcom/build/Omnijar.h b/xpcom/build/Omnijar.h index 819bbd2984..35a208bae9 100644 --- a/xpcom/build/Omnijar.h +++ b/xpcom/build/Omnijar.h @@ -13,6 +13,8 @@ #include "nsIFile.h" #include "nsZipArchive.h" +#include "mozilla/StaticPtr.h" + namespace mozilla { class Omnijar @@ -24,18 +26,29 @@ private: * (corresponding to resource:/// and resource://app/), but only * store one when both point to the same location (unified). */ - static nsIFile* sPath[2]; + static StaticRefPtr sPath[2]; /** * Cached nsZipArchives for the corresponding sPath */ - static nsZipArchive* sReader[2]; + static StaticRefPtr sReader[2]; + + /** + * Cached nsZipArchives for the outer jar, when using nested jars. + * Otherwise nullptr. + */ + static StaticRefPtr sOuterReader[2]; /** * Has Omnijar::Init() been called? */ static bool sInitialized; + /** + * Is using unified GRE/APP jar? + */ + static bool sIsUnified; + public: enum Type { @@ -43,6 +56,29 @@ public: APP = 1 }; +private: + /** + * Returns whether we are using nested jars. + */ + static inline bool IsNested(Type aType) + { + MOZ_ASSERT(IsInitialized(), "Omnijar not initialized"); + return !!sOuterReader[aType]; + } + + /** + * Returns a nsZipArchive pointer for the outer jar file when using nested + * jars. Returns nullptr in the same cases GetPath() would, or if not using + * nested jars. + */ + static inline already_AddRefed GetOuterReader(Type aType) + { + MOZ_ASSERT(IsInitialized(), "Omnijar not initialized"); + RefPtr reader = sOuterReader[aType].get(); + return reader.forget(); + } + +public: /** * Returns whether SetBase has been called at least once with * a valid nsIFile @@ -71,7 +107,7 @@ public: static inline already_AddRefed GetPath(Type aType) { MOZ_ASSERT(IsInitialized(), "Omnijar not initialized"); - nsCOMPtr path = sPath[aType]; + nsCOMPtr path = sPath[aType].get(); return path.forget(); } @@ -92,7 +128,7 @@ public: static inline already_AddRefed GetReader(Type aType) { MOZ_ASSERT(IsInitialized(), "Omnijar not initialized"); - RefPtr reader = sReader[aType]; + RefPtr reader = sReader[aType].get(); return reader.forget(); } diff --git a/xpcom/idl-parser/xpidl/typelib.py b/xpcom/idl-parser/xpidl/typelib.py index 6420a46d52..911e3873da 100644 --- a/xpcom/idl-parser/xpidl/typelib.py +++ b/xpcom/idl-parser/xpidl/typelib.py @@ -242,10 +242,10 @@ def build_interface(iface, ifaces): def write_typelib(idl, fd, filename): """ Generate the typelib. """ - # We only care about interfaces + # We only care about interfaces that are scriptable. ifaces = [] for p in idl.productions: - if p.kind == 'interface': + if p.kind == 'interface' and p.attributes.scriptable: ifaces.append(build_interface(p, ifaces)) typelib = xpt.Typelib(interfaces=ifaces) diff --git a/xpcom/io/Base64.cpp b/xpcom/io/Base64.cpp index 23381aa36c..99461e87eb 100644 --- a/xpcom/io/Base64.cpp +++ b/xpcom/io/Base64.cpp @@ -408,7 +408,7 @@ Base64Decode(const nsAString& aBinaryData, nsAString& aString) nsresult Base64URLDecode(const nsACString& aString, - const dom::Base64URLDecodeOptions& aOptions, + Base64URLDecodePaddingPolicy aPaddingPolicy, FallibleTArray& aOutput) { // Don't decode empty strings. @@ -429,8 +429,8 @@ Base64URLDecode(const nsACString& aString, // Determine whether to check for and ignore trailing padding. bool maybePadded = false; - switch (aOptions.mPadding) { - case dom::Base64URLDecodePadding::Require: + switch (aPaddingPolicy) { + case Base64URLDecodePaddingPolicy::Require: if (sourceLength % 4) { // Padded input length must be a multiple of 4. return NS_ERROR_INVALID_ARG; @@ -438,7 +438,7 @@ Base64URLDecode(const nsACString& aString, maybePadded = true; break; - case dom::Base64URLDecodePadding::Ignore: + case Base64URLDecodePaddingPolicy::Ignore: // Check for padding only if the length is a multiple of 4. maybePadded = !(sourceLength % 4); break; @@ -446,8 +446,8 @@ Base64URLDecode(const nsACString& aString, // If we're expecting unpadded input, no need for additional checks. // `=` isn't in the decode table, so padded strings will fail to decode. default: - MOZ_FALLTHROUGH_ASSERT("Invalid decode padding option"); - case dom::Base64URLDecodePadding::Reject: + MOZ_FALLTHROUGH_ASSERT("Invalid decode padding policy"); + case Base64URLDecodePaddingPolicy::Reject: break; } if (maybePadded && source[sourceLength - 1] == '=') { @@ -504,7 +504,7 @@ Base64URLDecode(const nsACString& aString, nsresult Base64URLEncode(uint32_t aLength, const uint8_t* aData, - const dom::Base64URLEncodeOptions& aOptions, + Base64URLEncodePaddingPolicy aPaddingPolicy, nsACString& aString) { // Don't encode empty strings. @@ -550,7 +550,7 @@ Base64URLEncode(uint32_t aLength, const uint8_t* aData, } uint32_t length = rawBuffer - aString.BeginWriting(); - if (aOptions.mPad) { + if (aPaddingPolicy == Base64URLEncodePaddingPolicy::Include) { if (length % 4 == 2) { *rawBuffer++ = '='; *rawBuffer++ = '='; @@ -559,6 +559,9 @@ Base64URLEncode(uint32_t aLength, const uint8_t* aData, *rawBuffer++ = '='; length += 1; } + } else { + MOZ_ASSERT(aPaddingPolicy == Base64URLEncodePaddingPolicy::Omit, + "Invalid encode padding policy"); } // Null terminate and truncate to the actual number of characters. diff --git a/xpcom/io/Base64.h b/xpcom/io/Base64.h index 1072693bb2..590c365797 100644 --- a/xpcom/io/Base64.h +++ b/xpcom/io/Base64.h @@ -9,8 +9,6 @@ #include "nsString.h" -#include "mozilla/dom/ThreadSafeChromeUtilsBinding.h" - class nsIInputStream; namespace mozilla { @@ -36,6 +34,11 @@ Base64Decode(const nsACString& aBinaryData, nsACString& aString); nsresult Base64Decode(const nsAString& aBinaryData, nsAString& aString); +enum class Base64URLEncodePaddingPolicy { + Include, + Omit, +}; + /** * Converts |aData| to an unpadded, Base64 URL-encoded string per RFC 4648. * Aims to encode the data in constant time. The caller retains ownership @@ -43,15 +46,21 @@ Base64Decode(const nsAString& aBinaryData, nsAString& aString); */ nsresult Base64URLEncode(uint32_t aLength, const uint8_t* aData, - const dom::Base64URLEncodeOptions& aOptions, + Base64URLEncodePaddingPolicy aPaddingPolicy, nsACString& aString); +enum class Base64URLDecodePaddingPolicy { + Require, + Ignore, + Reject, +}; + /** * Decodes a Base64 URL-encoded |aString| into |aOutput|. */ nsresult Base64URLDecode(const nsACString& aString, - const dom::Base64URLDecodeOptions& aOptions, + Base64URLDecodePaddingPolicy aPaddingPolicy, FallibleTArray& aOutput); } // namespace mozilla diff --git a/xpcom/threads/StateMirroring.h b/xpcom/threads/StateMirroring.h index 84275e44bf..bcb65fea38 100644 --- a/xpcom/threads/StateMirroring.h +++ b/xpcom/threads/StateMirroring.h @@ -234,6 +234,8 @@ private: }; public: + // NB: Because mirror-initiated disconnection can race with canonical- + // initiated disconnection, a canonical should never be reinitialized. // Forward control operations to the Impl. void DisconnectAll() { return mImpl->DisconnectAll(); } diff --git a/xpcom/threads/moz.build b/xpcom/threads/moz.build index 2718954260..45d723989a 100644 --- a/xpcom/threads/moz.build +++ b/xpcom/threads/moz.build @@ -77,7 +77,12 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk': # BHR disabled for Release builds because of bug 965392. # BHR disabled for debug builds because of bug 979069. -if CONFIG['MOZ_UPDATE_CHANNEL'] not in ('release') and not CONFIG['MOZ_DEBUG']: +# BHR disabled on gonk because of bug 1180533 +# BHR disabled for TSan builds because of bug 1121216. +if CONFIG['MOZ_UPDATE_CHANNEL'] not in ('release') and \ + not CONFIG['MOZ_DEBUG'] and \ + not CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk' and \ + not CONFIG['MOZ_TSAN']: DEFINES['MOZ_ENABLE_BACKGROUND_HANG_MONITOR'] = 1 FINAL_LIBRARY = 'xul' diff --git a/xpcom/threads/nsThread.cpp b/xpcom/threads/nsThread.cpp index 56bbc84181..4aca421951 100644 --- a/xpcom/threads/nsThread.cpp +++ b/xpcom/threads/nsThread.cpp @@ -704,7 +704,7 @@ nsThreadShutdownContext* nsThread::ShutdownInternal(bool aSync) { MOZ_ASSERT(mThread); - + MOZ_ASSERT(mThread != PR_GetCurrentThread()); if (NS_WARN_IF(mThread == PR_GetCurrentThread())) { return nullptr; } diff --git a/xpcom/typelib/xpt/tools/runtests.py b/xpcom/typelib/xpt/tools/runtests.py index 09f874cbda..a86e6625df 100644 --- a/xpcom/typelib/xpt/tools/runtests.py +++ b/xpcom/typelib/xpt/tools/runtests.py @@ -32,15 +32,14 @@ import difflib import os -import shutil from StringIO import StringIO import subprocess -import sys import tempfile import mozunit import unittest import xpt + def get_output(bin, file): p = subprocess.Popen([bin, file], stdout=subprocess.PIPE) stdout, _ = p.communicate() @@ -53,7 +52,7 @@ if "MOZILLA_OBJDIR" in os.environ: xptdump = os.path.abspath(os.path.join(MOZILLA_OBJDIR, "dist", "bin", "xpt_dump")) components = os.path.abspath(os.path.join(MOZILLA_OBJDIR, - "dist", "bin", "components")) + "dist", "bin", "components")) for f in os.listdir(components): if not f.endswith(".xpt"): continue @@ -72,6 +71,7 @@ if "MOZILLA_OBJDIR" in os.environ: print line self.assert_(out == out2, "xpt_dump output should be identical for %s" % f) + class TestIIDString(unittest.TestCase): def test_iid_str_roundtrip(self): iid_str = "11223344-5566-7788-9900-aabbccddeeff" @@ -83,6 +83,7 @@ class TestIIDString(unittest.TestCase): iid_str = xpt.Typelib.iid_to_string(iid) self.assertEqual(iid, xpt.Typelib.string_to_iid(iid_str)) + class TypelibCompareMixin: def assertEqualTypelibs(self, t1, t2): self.assert_(t1 is not None, "Should not be None") @@ -134,7 +135,7 @@ class TypelibCompareMixin: for p1, p2 in zip(m1.params, m2.params): self.assertEqualParams(p1, p2) self.assertEqualParams(m1.result, m2.result) - + def assertEqualConstants(self, c1, c2): self.assert_(c1 is not None, "Should not be None") self.assert_(c2 is not None, "Should not be None") @@ -152,7 +153,7 @@ class TypelibCompareMixin: self.assertEqual(p1.shared, p2.shared) self.assertEqual(p1.dipper, p2.dipper) self.assertEqual(p1.optional, p2.optional) - + def assertEqualTypes(self, t1, t2): self.assert_(t1 is not None, "Should not be None") self.assert_(t2 is not None, "Should not be None") @@ -174,6 +175,7 @@ class TypelibCompareMixin: self.assertEqual(t1.size_is_arg_num, t2.size_is_arg_num) self.assertEqual(t1.length_is_arg_num, t2.length_is_arg_num) + class TestTypelibReadWrite(unittest.TestCase, TypelibCompareMixin): def test_read_file(self): """ @@ -191,7 +193,7 @@ class TestTypelibReadWrite(unittest.TestCase, TypelibCompareMixin): self.assertEqualTypelibs(t, t2) -#TODO: test flags in various combinations +# TODO: test flags in various combinations class TestTypelibRoundtrip(unittest.TestCase, TypelibCompareMixin): def checkRoundtrip(self, t): s = StringIO() @@ -200,13 +202,13 @@ class TestTypelibRoundtrip(unittest.TestCase, TypelibCompareMixin): t2 = xpt.Typelib.read(s) self.assert_(t2 is not None) self.assertEqualTypelibs(t, t2) - + def test_simple(self): t = xpt.Typelib() # add an unresolved interface t.interfaces.append(xpt.Interface("IFoo")) self.checkRoundtrip(t) - + t = xpt.Typelib() # add an unresolved interface with an IID t.interfaces.append(xpt.Interface("IBar", "11223344-5566-7788-9900-aabbccddeeff")) @@ -305,7 +307,7 @@ class TestTypelibRoundtrip(unittest.TestCase, TypelibCompareMixin): xpt.Param(xpt.SimpleType(xpt.Type.Tags.int32)), ])) self.checkRoundtrip(t) - + # add a method with a StringWithSize and WideStringWithSize arguments i.methods.append(xpt.Method("StringWithSizeMethod", xpt.Param(xpt.SimpleType(xpt.Type.Tags.void)), params=[ @@ -320,11 +322,12 @@ class TestTypelibRoundtrip(unittest.TestCase, TypelibCompareMixin): ])) self.checkRoundtrip(t) + class TestInterfaceCmp(unittest.TestCase): def test_unresolvedName(self): """ Test comparison function on xpt.Interface by name. - + """ i1 = xpt.Interface("ABC") i2 = xpt.Interface("DEF") @@ -334,7 +337,7 @@ class TestInterfaceCmp(unittest.TestCase): def test_unresolvedEqual(self): """ Test comparison function on xpt.Interface with equal names and IIDs. - + """ i1 = xpt.Interface("ABC") i2 = xpt.Interface("ABC") @@ -343,7 +346,7 @@ class TestInterfaceCmp(unittest.TestCase): def test_unresolvedIID(self): """ Test comparison function on xpt.Interface with different IIDs. - + """ # IIDs sort before names i1 = xpt.Interface("ABC", iid="22334411-5566-7788-9900-aabbccddeeff") @@ -355,7 +358,7 @@ class TestInterfaceCmp(unittest.TestCase): """ Test comparison function on xpt.Interface with interfaces with identical names and IIDs but different resolved status. - + """ i1 = xpt.Interface("ABC", iid="11223344-5566-7788-9900-aabbccddeeff") p = xpt.Param(xpt.SimpleType(xpt.Type.Tags.void)) @@ -369,7 +372,7 @@ class TestInterfaceCmp(unittest.TestCase): """ Test comparison function on xpt.Interface with interfaces with identical names and IIDs, both of which are resolved. - + """ p = xpt.Param(xpt.SimpleType(xpt.Type.Tags.void)) m = xpt.Method("Bar", p) @@ -379,12 +382,13 @@ class TestInterfaceCmp(unittest.TestCase): methods=[m]) self.assert_(i2 == i1) + class TestXPTLink(unittest.TestCase): def test_mergeDifferent(self): """ Test that merging two typelibs with completely different interfaces produces the correctly merged typelib. - + """ t1 = xpt.Typelib() # add an unresolved interface @@ -393,7 +397,7 @@ class TestXPTLink(unittest.TestCase): # add an unresolved interface t2.interfaces.append(xpt.Interface("IBar", scriptable=True)) t3 = xpt.xpt_link([t1, t2]) - + self.assertEqual(2, len(t3.interfaces)) # Interfaces should wind up sorted self.assertEqual("IBar", t3.interfaces[0].name) @@ -407,7 +411,7 @@ class TestXPTLink(unittest.TestCase): # add an unresolved interface t2.interfaces.append(xpt.Interface("IBar", iid="44332211-6655-8877-0099-aabbccddeeff", scriptable=True)) t3 = xpt.xpt_link([t1, t2]) - + self.assertEqual(2, len(t3.interfaces)) # Interfaces should wind up sorted self.assertEqual("IFoo", t3.interfaces[0].name) @@ -417,7 +421,7 @@ class TestXPTLink(unittest.TestCase): """ Test that merging two typelibs with conflicting interface definitions raises an error. - + """ # Same names, different IIDs t1 = xpt.Typelib() @@ -452,7 +456,7 @@ class TestXPTLink(unittest.TestCase): # add an unresolved interface, no IID t2.interfaces.append(xpt.Interface("IFoo")) t3 = xpt.xpt_link([t1, t2]) - + self.assertEqual(1, len(t3.interfaces)) self.assertEqual("IFoo", t3.interfaces[0].name) self.assertEqual("11223344-5566-7788-9900-aabbccddeeff", t3.interfaces[0].iid) @@ -464,7 +468,7 @@ class TestXPTLink(unittest.TestCase): # add an unresolved interface with a valid IID t2.interfaces.append(xpt.Interface("IFoo", iid="11223344-5566-7788-9900-aabbccddeeff", scriptable=True)) t3 = xpt.xpt_link([t1, t2]) - + self.assertEqual(1, len(t3.interfaces)) self.assertEqual("IFoo", t3.interfaces[0].name) self.assertEqual("11223344-5566-7788-9900-aabbccddeeff", t3.interfaces[0].iid) @@ -488,7 +492,7 @@ class TestXPTLink(unittest.TestCase): t2.interfaces.append(xpt.Interface("IFoo", iid="11223344-5566-7788-9900-aabbccddeeff", methods=[m], scriptable=True)) t3 = xpt.xpt_link([t1, t2]) - + self.assertEqual(1, len(t3.interfaces)) self.assertEqual("IFoo", t3.interfaces[0].name) self.assertEqual("11223344-5566-7788-9900-aabbccddeeff", t3.interfaces[0].iid) @@ -507,7 +511,7 @@ class TestXPTLink(unittest.TestCase): # add an unresolved interface t2.interfaces.append(xpt.Interface("IFoo")) t3 = xpt.xpt_link([t1, t2]) - + self.assertEqual(1, len(t3.interfaces)) self.assertEqual("IFoo", t3.interfaces[0].name) self.assertEqual("11223344-5566-7788-9900-aabbccddeeff", t3.interfaces[0].iid) @@ -538,7 +542,7 @@ class TestXPTLink(unittest.TestCase): t2.interfaces.append(xpt.Interface("IFoo", iid="11223344-5566-7788-9900-aabbccddeeff", methods=[m], scriptable=True)) t3 = xpt.xpt_link([t1, t2]) - + self.assertEqual(2, len(t3.interfaces)) self.assertEqual("IChild", t3.interfaces[0].name) self.assertEqual("11111111-1111-1111-1111-111111111111", t3.interfaces[0].iid) @@ -566,7 +570,7 @@ class TestXPTLink(unittest.TestCase): t2.interfaces.append(xpt.Interface("IChild", iid="11111111-1111-1111-1111-111111111111", resolved=True, parent=pi, scriptable=True)) t3 = xpt.xpt_link([t1, t2]) - + self.assertEqual(2, len(t3.interfaces)) self.assertEqual("IChild", t3.interfaces[0].name) self.assertEqual("11111111-1111-1111-1111-111111111111", t3.interfaces[0].iid) @@ -603,7 +607,7 @@ class TestXPTLink(unittest.TestCase): t2.interfaces.append(xpt.Interface("IFoo", iid="11223344-5566-7788-9900-aabbccddeeff", methods=[m], scriptable=True)) t3 = xpt.xpt_link([t1, t2]) - + self.assertEqual(2, len(t3.interfaces)) self.assertEqual("IRetval", t3.interfaces[0].name) self.assertEqual("11111111-1111-1111-1111-111111111111", t3.interfaces[0].iid) @@ -636,7 +640,7 @@ class TestXPTLink(unittest.TestCase): t2.interfaces.append(xpt.Interface("IRetval", iid="11111111-1111-1111-1111-111111111111", methods=[m], scriptable=True)) t3 = xpt.xpt_link([t1, t2]) - + self.assertEqual(2, len(t3.interfaces)) self.assertEqual("IRetval", t3.interfaces[0].name) self.assertEqual("11111111-1111-1111-1111-111111111111", t3.interfaces[0].iid) @@ -675,7 +679,7 @@ class TestXPTLink(unittest.TestCase): t2.interfaces.append(xpt.Interface("IFoo", iid="11223344-5566-7788-9900-aabbccddeeff", methods=[m], scriptable=True)) t3 = xpt.xpt_link([t1, t2]) - + self.assertEqual(2, len(t3.interfaces)) self.assertEqual("IParam", t3.interfaces[0].name) self.assertEqual("11111111-1111-1111-1111-111111111111", t3.interfaces[0].iid) @@ -708,7 +712,7 @@ class TestXPTLink(unittest.TestCase): t2.interfaces.append(xpt.Interface("IParam", iid="11111111-1111-1111-1111-111111111111", methods=[m], scriptable=True)) t3 = xpt.xpt_link([t1, t2]) - + self.assertEqual(2, len(t3.interfaces)) self.assertEqual("IParam", t3.interfaces[0].name) self.assertEqual("11111111-1111-1111-1111-111111111111", t3.interfaces[0].iid) @@ -721,7 +725,6 @@ class TestXPTLink(unittest.TestCase): self.assertEqual(t3.interfaces[1], t3.interfaces[0].methods[0].params[0].type.iface) - def test_mergeReplaceArrayTypeParams(self): """ Test that merging an interface correctly updates ArrayType @@ -750,7 +753,7 @@ class TestXPTLink(unittest.TestCase): t2.interfaces.append(xpt.Interface("IFoo", iid="11223344-5566-7788-9900-aabbccddeeff", methods=[m], scriptable=True)) t3 = xpt.xpt_link([t1, t2]) - + self.assertEqual(2, len(t3.interfaces)) self.assertEqual("IParam", t3.interfaces[0].name) self.assertEqual("11111111-1111-1111-1111-111111111111", t3.interfaces[0].iid)